Android中Services之异步IntentService
1.IntentService:异步处理服务
1.内部有一个工作线程来完成耗时操作,只需要实现onHandleIntent()方法即可
2.IntentService完成工作后会自动停止服务,同时执行多个任务会以工作队列形式,依次执行
3.不需要主动调用stopSelft()来结束服务。因为,在所有的intent被处理完后,系统会自动关闭服务。
4.通常使用该类完成app中的耗时工作
5. 默认实现的onBind()返回null
2.继承IntentService的类至少要实现两个函数:
构造函数和onHandleIntent()函数
3.下面来看一下源码
1>写一个类继承自IntentService
在里面实现onHandlerIntent()方法,打印输出i
public class MyIntentService extends IntentService {
public MyIntentService() {
//构造方法,需要取一个名字
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.e("TAG", "传递的数据 ====== "+intent.getStringExtra("msg"));
for (int i = 0; i < 3; i++) {
System.out.println("onHandleIntent"+i+Thread.currentThread().getName());
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("TAG", "MyIntentServiceDestory!!");
}
}
2>然后是MainActivity
主要用来启动Service,传递数值
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startIntentService(View view) {
Intent intent = new Intent(this,MyIntentService.class);
intent.putExtra("msg","哈哈哈哈哈哈MyIntentService");
startService(intent);
}
}
xml布局文件就不发了,只用一个按钮
然后点击开启服务按钮,可以发现,LogCat打印的Log,Service在打印完成后,自动执行onDestroy()销毁
E/TAG: 传递的数据 ====== 哈哈哈哈哈哈MyIntentService
I/System.out: onHandleIntent0IntentService[MyIntentService]
I/System.out: onHandleIntent1IntentService[MyIntentService]
I/System.out: onHandleIntent2IntentService[MyIntentService]
E/TAG: MyIntentServiceDestory!!