首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Android Service 生命週期完整解析與程式碼範例 (副本)

     編輯:Java 相關知識

說明

本文內容與 ID 233780 完全相同,疑為資料重複。此處保留相同完整解析,實際專案中請去重。

Service 四大啟動模式

模式啟動方式生命週期關鍵方法特點
純 StartstartService()onCreate → onStartCommand (多次) → onDestroy後台長期運行,與調用者解耦
純 BindbindService()onCreate → onBind → onUnbind → onDestroy客戶端生命週期綁定,無客戶端自動銷毀
Start + Bind先 start 再 bindonCreate → onStartCommand → onBind → onUnbind → onDestroy兼具長期運行與交互能力
IntentServicestartService()onCreate → onHandleIntent (子線程) → onDestroy順序處理異步任務,任務結束自動停止

完整示例:計時 Service

Service 實現

public class TimerService extends Service {
    private static final String TAG = "TimerService";
    public static long elapsedMs = 0;
    private volatile boolean running = true;

    private final IBinder binder = new LocalBinder();
    
    public class LocalBinder extends Binder {
        TimerService getService() { return TimerService.this; }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(() -> {
            while (running) {
                try { Thread.sleep(100); } 
                catch (InterruptedException ignored) {}
                Log.i(TAG, "running " + (elapsedMs += 100) + "ms");
            }
        }).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY; 
    }

    @Override
    public void onDestroy() {
        running = false;
        super.onDestroy();
    }
}

Activity 交互

public class MainActivity extends AppCompatActivity {
    private TimerService timerService;
    private boolean bound = false;

    private ServiceConnection conn = new ServiceConnection() {
        @Override public void onServiceConnected(ComponentName name, IBinder service) {
            timerService = ((TimerService.LocalBinder) service).getService();
            bound = true;
        }
        @Override public void onServiceDisconnected(ComponentName name) {
            bound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        findViewById(R.id.btnStart).setOnClickListener(v -> 
            startService(new Intent(this, TimerService.class)));
        findViewById(R.id.btnStop).setOnClickListener(v -> 
            stopService(new Intent(this, TimerService.class)));
        findViewById(R.id.btnBind).setOnClickListener(v -> 
            bindService(new Intent(this, TimerService.class), conn, BIND_AUTO_CREATE));
    }

    @Override
    protected void onDestroy() {
        if (bound) unbindService(conn);
        super.onDestroy();
    }
}

AndroidManifest 註冊

<service android:name=".TimerService">
    <intent-filter>
        <action android:name="com.example.TIMER_SERVICE" />
    </intent-filter>
</service>

關鍵注意點

  1. onStartCommand 返回值:START_STICKY(重建)、START_NOT_STICKY(不重建)、START_REDELIVER_INTENT(重傳 Intent)。
  2. 主線程阻塞:Service 默認運行在主線程,耗時操作**必須**開子線程。
  3. Bind 解綁時機:onDestroy 或 onStop 中調用 unbindService,否則洩漏。
  4. 前台服務:Android 8+ 後台限制,長期運行需 startForeground() 顯示通知。

總結

Service 是 Android 後台運算核心組件。理解Start/Bind 雙模式、onStartCommand 返回語義、主線程限制與前台服務適配,是編寫穩健後台服務的基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved