標籤:
IntentService定義
IntentService繼承與Service,用來處理非同步請求。用戶端可以通過startService(Intent)方法傳遞請求給IntentService。IntentService在onCreate()函數中通過HandlerThread單獨開啟一個線程來依次處理所有Intent請求對象所對應的任務。
這樣以免交易處理阻塞主線程(ANR)。執行完所一個Intent請求對象所對應的工作之後,如果沒有新的Intent請求達到,則**自動停止**Service;否則執行下一個Intent請求所對應的任務。
IntentService在處理事務時,還是採用的Handler方式,建立一個名叫ServiceHandler的內部Handler,並把它直接綁定到HandlerThread所對應的子線程。 ServiceHandler把處理一個intent所對應的事務都封裝到叫做onHandleIntent的虛函數;因此我們直接實現虛函數onHandleIntent,再在裡面根據Intent的不同進行不同的交易處理就可以了。
另外,IntentService預設實現了Onbind()方法,傳回值為null。
使用IntentService需要實現的兩個方法:
IntentService與Service的區別
Service不是獨立的進程,也不是獨立的線程,它是依賴於應用程式的主線程的,不建議在Service中編寫耗時的邏輯和操作,否則會引起ANR。
IntentService 它建立了一個獨立的背景工作執行緒來處理所有的通過onStartCommand()傳遞給服務的intents(把intent插入到工作隊列中)。通過工作隊列把intent逐個發送給onHandleIntent()。
不需要主動調用stopSelft()來結束服務。因為,在所有的intent被處理完後,系統會自動關閉服務。
預設實現的onBind()返回null。
IntentService執行個體介紹
首先是myIntentService.java
public class myIntentService extends IntentService { //------------------必須實現----------------------------- public myIntentService() { super("myIntentService"); // 注意建構函式參數為空白,這個字串就是worker thread的名字 } @Override protected void onHandleIntent(Intent intent) { //根據Intent的不同進行不同的交易處理 String taskName = intent.getExtras().getString("taskName"); switch (taskName) { case "task1": Log.i("myIntentService", "do task1"); break; case "task2": Log.i("myIntentService", "do task2"); break; default: break; } } //--------------------用於列印生命週期-------------------- @Override public void onCreate() { Log.i("myIntentService", "onCreate"); super.onCreate();} @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("myIntentService", "onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.i("myIntentService", "onDestroy"); super.onDestroy(); }}
然後記得在Manifest.xml中註冊服務
<service android:name=".myIntentService"> <intent-filter > <action android:name="cn.scu.finch"/> </intent-filter> </service>
最後在Activity中開啟服務
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //同一服務只會開啟一個worker thread,在onHandleIntent函數裡依次處理intent請求。 Intent i = new Intent("cn.scu.finch"); Bundle bundle = new Bundle(); bundle.putString("taskName", "task1"); i.putExtras(bundle); startService(i); Intent i2 = new Intent("cn.scu.finch"); Bundle bundle2 = new Bundle(); bundle2.putString("taskName", "task2"); i2.putExtras(bundle2); startService(i2); startService(i); //多次啟動 }}
運行結果:
IntentService在onCreate()函數中通過HandlerThread單獨開啟一個線程來依次處理所有Intent請求對象所對應的任務。
通過onStartCommand()傳遞給服務intent被依次插入到工作隊列中。工作隊列又把intent逐個發送給onHandleIntent()。
注意:
它只有一個背景工作執行緒,名字就是建構函式的那個字串,也就是“myIntentService”,我們知道多次開啟service,只會調用一次onCreate方法(建立一個背景工作執行緒),多次onStartCommand方法(用於傳入intent通過工作隊列再發給onHandleIntent函數做處理)。
[Android] IntentService使用詳解和執行個體介紹