一、什么是IntentService?有什么作用?
IntentService是Android里的一个封装类,继承了四大组件之一的Service,一般用来处理异步请求或者实现多线程
二、使用场景
IntentService用来执行线程任务,需按顺序在后台执行,例如离线下载等
三、使用步骤
-->定义IntentService的子类,需重写onHandleIntent()方法
public class myIntentService extends IntentService {
/**
* 在构造函数中传入线程名字
**/
public myIntentService() {
// 调用父类的构造函数
// 参数 = 工作线程的名字
super("myIntentService");
}
/**
* 复写onHandleIntent()方法
* 根据 Intent实现 耗时任务 操作
**/
@Override
protected void onHandleIntent(Intent intent) {
// 根据 Intent的不同,进行不同的事务处理
String taskName = intent.getExtras().getString("taskName");
switch (taskName) {
case "task1":
Log.i("myIntentService", "do task1");
break;
case "task2":
Log.i("myIntentService", "do task2");
break;
default:
break;
}
}
@Override
public void onCreate() {
Log.i("myIntentService", "onCreate");
super.onCreate();
}
/**
* 复写onStartCommand()方法
* 默认实现 = 将请求的Intent添加到工作队列里
**/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("myIntentService", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("myIntentService", "onDestroy");
super.onDestroy();
}
}
-->在清单文件里注册服务
<service android:name=".myIntentService">
<intent-filter >
<action android:name="com.test.intentservice"/>
</intent-filter>
</service>
-->在Activity中开启Service服务
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 同一服务只会开启1个工作线程
// 在onHandleIntent()函数里,依次处理传入的Intent请求
// 将请求通过Bundle对象传入到Intent,再传入到服务里
// 请求1
Intent i = new Intent("com.test.intentservice");
Bundle bundle = new Bundle();
bundle.putString("taskName", "task1");
i.putExtras(bundle);
startService(i);
// 请求2
Intent i2 = new Intent("com.test.intentservice");
Bundle bundle2 = new Bundle();
bundle2.putString("taskName", "task2");
i2.putExtras(bundle2);
startService(i2);
startService(i); //多次启动
}
}
四、对比
1.与Service对比
-->运行线程
IntentService :创建1个工作线程处理多线程任务
Service:主线程(不能处理耗时操作,否则会出现ANR)
-->结束服务操作
IntentService:不需要,在所有Intent被处理后,系统会自动关闭服务
Service:需主动调用stopService
其他:
IntentService为Service的onBind()提供了默认实现,返回null
IntentService为Service的onStartCommand()方法提供了默认实现,将请求的Intent添加到了队列当中
2.与其他线程的对比
-->线程属性:
IntentService:类似后台线程(采用HandlerThread实现)
其他线程:普通线程
-->作用:
IntentService :后台服务(继承了Service)
其他线程:普通线程作用
-->线程优先级
IntentService:高 不容易被系统杀死
其他线程:低(如果进程中没有活动的四大组件,则该线程的优先级很低,容易被系统杀死)