为什么要用IntentService?
service的代码默认运行在主线程中,如果在service中执行一些耗时操作,会出现UI无响应的情况,因此IntentService自动创建子线程,执行任务后,自动停止
使用步骤:
1.新建一个类,extends IntentService类,实现onHandleIntent()方法:
public class MyIntentService3 extends IntentService { public MyIntentService3() { super("MyIntentService3"); } @Override protected void onHandleIntent(Intent intent) { //执行耗时操作,执行完后,IntentService自动关闭 } }
2.主线程中启动Service
Intent intent =new Intent(this,MyService.class); startService(intent);