1.什么是IntentService?
IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作。
当任务执行完后,IntentService 会自动停止,不需要我们去手动结束。
如果启动 IntentService 多次,那么每一个耗时操作会以工作队列的方式在 IntentService 的 onHandleIntent 回调方法中执行,依次去执行,使用串行的方式,执行完自动结束。
2.IntentService使用优缺点:
1.是一种服务,比较适合高优先级的后台任务
2.任务结束自动退出
3.IntentService是Service的子类,用来处理异步请求,IntentService在onCreate()通过HandlerThread开启一个线程
4.IntentService在onHandlerIntent()中处理完一个Intent请求的时候,如果后面没有intent请求的时候,会自动停止,如果有,则接着处理下一个
5.与一般service相比, 开启了子线程,会自动停止
3.IntentService的使用示例:
新建类继承IntentService
重写onHandleIntent方法
public class MyIntentService extends IntentService {
public MyIntentService(String name) {
super(name);
}
public MyIntentService() {
super("");
}
@Override
//重写onHandleIntent方法
protected void onHandleIntent(@Nullable Intent intent) {
for (int i=0;i<5;i++){
Log.e("onHandleIntent: ", i+"---------------------");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
新建一个Activity,布置其XML代码:
两个Button用来启动、停止Service
<Button
android:id="@+id/start_service3"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="StartService" />
<Button
android:id="@+id/stop_service3"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="StopService" />
布置java代码:
public class Main3Activity extends AppCompatActivity implements View.OnClickListener{
private Button startBtn;
private Button stopBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
bindid();
}
private void bindid() {
startBtn=findViewById(R.id.start_service3);
stopBtn=findViewById(R.id.stop_service3);
stopBtn.setOnClickListener(this);
startBtn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.start_service3:
Intent intent1=new Intent(this,MyIntentService.class);
startService(intent1);
break;
case R.id.stop_service3:
Intent intent2=new Intent(this,MyIntentService.class);
startService(intent2);
break;
default:
break;
}
}
}
IntentService与Service使用区别:
- 首先IntentService是继承自Service;
- Service不是一个单独的进程,它和应用程序在同一个进程中;
- Service也不是一个线程,所以我们要避免在Service中进行耗时的操作;
- IntentService使用队列的方式将请求的Intent加入队列,然后开启了一个Worker Thread(工作线程)在处理队列中的Intent,对于异步的startService请求,
IntentService会处理完成一个之后在处理第二个,每一个请求都会在一个单独的Worker Thread中处理,不会阻塞应用程序的主线程。
因此,如果我们如果要在Service里面处理一个耗时的操作,我们可以用IntentService来代替使用。 - 使用IntentService 必须首先继承IntentService并实现onHandleIntent()方法,将耗时的任务放在这个方法执行,其他方面,IntentService和Service一样。