IntentService:異步處理服務,新開一個線程:handlerThread在線程中發消息,然后接受處理完成后,會清理線程,並且關掉服務。
IntentService有以下特點:
(1) 它創建了一個獨立的工作線程來處理所有的通過onStartCommand()傳遞給服務的intents。
(2) 創建了一個工作隊列,來逐個發送intent給onHandleIntent()。
(3) 不需要主動調用stopSelft()來結束服務。因為,在所有的intent被處理完后,系統會自動關閉服務。
(4) 默認實現的onBind()返回null
(5) 默認實現的onStartCommand()的目的是將intent插入到工作隊列中
繼承IntentService的類至少要實現兩個函數:構造函數和onHandleIntent()函數。要覆蓋IntentService的其它函數時,注意要通過super調用父類的對應的函數。
界面設置兩按鈕:
<Button android:id="@+id/btnStartIntentService" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="開始下載" > </Button> <Button android:id="@+id/btnStopIntentService" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="結束下載" > </Button>
聲明IntentServiceSub繼承IntentService
public class IntentServiceSub extends IntentService { private static final String TAG = "IntentServiceSub"; public IntentServiceSub() { super("IntentServiceSub"); Log.i(TAG, "=>IntentServiceSub"); } /* (non-Javadoc) * @see android.app.IntentService#onCreate() */ @Override public void onCreate() { Log.i(TAG, "=>onCreate"); super.onCreate(); } /* (non-Javadoc) * @see android.app.IntentService#onDestroy() */ @Override public void onDestroy() { Log.i(TAG, "=>onDestroy"); super.onDestroy(); } @Override protected void onHandleIntent(Intent arg0) { Log.i(TAG, "IntentService 線程:"+Thread.currentThread.getId());
Thread.sleep(2000);
}
頁面按鈕事件
btnStartIntentService = (Button) this.findViewById(R.id.btnStartIntentService); btnStopIntentService = (Button) this.findViewById(R.id.btnStopIntentService); private OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { case R.id.btnStartIntentService: Log.i(TAG, "主線程ID:"+Thread.currentThread.getId()); if (mServiceIntent == null) mServiceIntent = new Intent(AndroidServiceActivity.this,IntentServiceSub.class); startService(mServiceIntent); break; case R.id.btnStopIntentService: Log.i(TAG, "btnStopIntentService"); if (mServiceIntent != null) { stopService(mServiceIntent); mServiceIntent = null; } break; } } };