不断学习,做更好的自己!💪
视频号CSDN简书欢迎打开微信,关注我的视频号:KevinDev点我点我 简介1. 定义 Android 里的一个封装类,继承四大组件之一的 Service
2. 作用 处理异步请求 & 实现多线程
3. 使用场景 线程任务需按顺序、在后台执行。常见:离线下载。
4. 使用步骤 Tep 1:定义 IntentService的子类,需复写onHandleIntent()方法 Tep 2:在Manifest.xml中注册服务 Tep 3:在Activity中开启Service服务
实例1. 定义 IntentService 的子类
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 中注册服务
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); //多次启动
}
}
4. 测试结果