正文
前言
目录
示意图
1. 定义
Android
里的一个封装类,继承四大组件之一的
Service
2. 作用
处理异步请求 & 实现多线程
3. 使用场景
线程任务 需
按顺序
、
在后台执行
-
最常见的场景:离线下载
-
不符合多个数据同时请求的场景:所有的任务都在同一个
Thread looper
里执行
4. 使用步骤
步骤1:定义
IntentService
的子类,需复写
onHandleIntent()
方法
步骤2:在
Manifest.xml
中注册服务
步骤3:在
Activity
中开启
Service
服务
5. 实例讲解
步骤1:定义
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();
}
}
步骤2:在Manifest.xml中注册服务
<service android:name=".myIntentService">
<intent-filter >
<action android:name="cn.scu.finch"/>
</intent-filter>
</service>
步骤3:在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("cn.scu.finch");
Bundle bundle = new Bundle();
bundle.putString("taskName", "task1");
i.putExtras(bundle);
startService(i);
// 请求2
Intent i2 = new Intent("cn.scu.finch");
Bundle bundle2 = new Bundle();
bundle2.putString("taskName", "task2");
i2.putExtras(bundle2);
startService(i2);
startService(i); //多次启动
}
}
测试结果
运行结果
6. 对比
此处主要讲解IntentService与四大组件Service、普通线程的区别。
6.1 与Service的区别
示意图
6.2 与其他线程的区别
示意图
7. 总结
请点赞!因为你的鼓励是我写作的最大动力!
相关文章阅读