[TOC]
大綱
生命周期
- onCreate()
- onStartCommand()
- onBind()
- onUnbind()
- onDestroy()
Service和Activity通信
Binder
Broadcast
onStartCommand()返回值
START_STICKY
當系統(tǒng)因回收資源而銷毀了 Service,當資源再次充足時自動啟動 Service蒋腮。而且再次調(diào)用 onStartCommand() 方法淘捡,但是不會傳遞最后一次的 Intent,相反系統(tǒng)在回調(diào) onStartCommand() 的時候會傳一個空 Intent池摧,除非有未處理的 Intent 準備發(fā)送焦除。
START_NOT_STICKY
當系統(tǒng)因回收資源而銷毀了 Service,當資源再次充足時不再自動啟動 Service作彤,除非有未處理的 Intent 準備發(fā)送膘魄。
START_REDELIVER_INTENT
當系統(tǒng)因回收資源而銷毀了 Service,當資源再次充足時自動啟動 Service竭讳,并且再次調(diào)用 onStartCommand() 方法创葡,并會把最后一次 Intent 再次傳遞給 onStartCommand(),相應的在隊列里的 Intent 也會按次序一次傳遞绢慢。此模式適用于下載等服務灿渴。
START_STICKY_COMPATIBILITY
是START_STICKY的兼容版本,但是不能保證Service被清理后一定會重新調(diào)用onStartCommand方法呐芥。
前臺服務
前臺服務與普通服務最大的區(qū)別在于,它會一直有一個正在運行的圖標在系統(tǒng)的狀態(tài)欄
創(chuàng)建前臺服務
public class MyService extends Service {
...
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService", "onCreate executed");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.build();
startForeground(1, notification);
}
...
}
啟動與停止前臺服務
Intent foregroundIntent = new Intent(this, ForegroundService.class);
startService(foregroundIntent); // 啟動前臺服務
stopService(foregroundIntent); // 停止前臺服務
IntentService
IntentService 是 Service 的子類奋岁,并且所有的請求操作都是在異步線程里思瘟。如果不需要 Service 來同時處理多個請求的話,IntentService 將會是最佳的選擇闻伶。
使用該服務只需要繼承并重寫 IntentService 中的 onHandleIntent() 方法滨攻,就可以對接受到的 Intent 做后臺的異步線程操作了。這個服務會在運行結束之后自動停止蓝翰。
MyService:
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
//TODO: 耗時操作光绕,運行在子線程中
Log.d("MyIntentService","Thread is "+Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService","onDestroy executed");
}
}
MyActivity:
public class MyActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MyActivity","Thread is "+Thread.currentThread().getId());
Intent intent = new Intent(MyActivity.this,MyIntentService.class);
startService(intent);
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService","onDestroy executed");
}
}
點擊按鈕之后即可看到以下效果