本文內容與 ID 233780 完全相同,疑為資料重複。此處保留相同完整解析,實際專案中請去重。
| 模式 | 啟動方式 | 生命週期關鍵方法 | 特點 |
|---|---|---|---|
| 純 Start | startService() | onCreate → onStartCommand (多次) → onDestroy | 後台長期運行,與調用者解耦 |
| 純 Bind | bindService() | onCreate → onBind → onUnbind → onDestroy | 客戶端生命週期綁定,無客戶端自動銷毀 |
| Start + Bind | 先 start 再 bind | onCreate → onStartCommand → onBind → onUnbind → onDestroy | 兼具長期運行與交互能力 |
| IntentService | startService() | onCreate → onHandleIntent (子線程) → onDestroy | 順序處理異步任務,任務結束自動停止 |
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();
}
}
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();
}
}
<service android:name=".TimerService">
<intent-filter>
<action android:name="com.example.TIMER_SERVICE" />
</intent-filter>
</service>
START_STICKY(重建)、START_NOT_STICKY(不重建)、START_REDELIVER_INTENT(重傳 Intent)。onDestroy 或 onStop 中調用 unbindService,否則洩漏。startForeground() 顯示通知。Service 是 Android 後台運算核心組件。理解Start/Bind 雙模式、onStartCommand 返回語義、主線程限制與前台服務適配,是編寫穩健後台服務的基石。