美文网首页
App启动优化

App启动优化

作者: 被风扬起的沙 | 来源:发表于2016-11-10 11:34 被阅读15次

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

相关文章

网友评论

      本文标题:App启动优化

      本文链接:https://www.haomeiwen.com/subject/jmxxpttx.html