App啟動優化

借鑒自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。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容