在Android四大組件中Service是惟一可以後臺運行的服務,廣播接收器是一個等待着的和觀察者的角色,並不屬於後臺程序,此外,他的生命週期也很是短,在OnReceiver中不能超過有10秒的邏輯出現。android
第1點:併發
IntentService的生命很是短暫,執行完onHandleIntent(Intent intent) 會自動結束;異步
第2點:ide
Service容許綁定服務,IntentService不容許綁定服務spa
第3點:.net
IntentService繼承自Service,而且內部實現了Handler消息隊列。注意,此隊列沒法實現併發。code
第4點:繼承
Service生命週期中,不可執行耗時任務(除了Binder方式),但IntentService能夠,在IntentService中,onHandleIntent自己就是在異步環境中執行的方法。生命週期
IntentService不適合常駐,所以,能夠使用Service來實現。隊列
package com.test.background; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BackBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent myIntent = new Intent(); myIntent.setAction("com.test.background.Service.network.Action"); //service服務的Action context.startService(myIntent); } } }
註冊
<receiver android:name="com.test.background.BackBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> </intent-filter> </receiver>
權限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>