借鑒自http://gold.xitu.io/post/581d72d5570c350060a069af
IntentService
IntentService是繼承于Service并處理異步請求的一個類,在IntentService的內部,有一個工作線程來處理耗時操作,啟動IntentService的方式和啟動傳統Service一樣,同時,當任務執行完后,IntentService會自動停止,而不需要去手動控制。
public class InitIntentService extends IntentService {
public InitIntentService() {
super("InitIntentService");
}
public static void start(Context context) {
Intent intent = new Intent(context, InitIntentService.class);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
SystemClock.sleep(2000);
Log.d(TAG, "onHandleIntent: ");
}}
我們將耗時任務丟到IntentService中去處理,系統會自動開啟線程去處理,同時,在任務結束后,還能自己結束Service,多么的人性化!OK,只需要在Application或者Activity的onCreate中去啟動這個IntentService即可:
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitIntentService.start(this);
}
最后不要忘記在Mainifest注冊Service。