1.為何要用子程序
服務是在主線程中執行的,直接在服務中執行耗時操作明顯不可取,於是安卓官方增加了IntentService類來方便使用
在Service中執行子程序代碼如下
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
// 處理具體的邏輯
stopSelf();//需要自行關閉服務
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
在IntentService中執行子程序代碼如下
/**
* 用途:用於測試IntentService類服務的特性
* 特性:1.該服務必須覆蓋onHandleIntent方法,該方法在子線程中運行
* 2.該服務實行結束后會自動關閉,即調用onDestory( )方法
*/
public class MyIntentService extends IntentService {
public MyIntentService() {
//1.創建無參數構造函數,調用父類有參構造器
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG,"線程ID是"+Thread.currentThread().getId());
}
@Override
public void onDestroy() {
Log.d(TAG,"IntentService關閉了");
super.onDestroy();
}
}