您的位置:首页 > 职场人生

IntentService面试知识小结

2018-01-29 18:20 337 查看
今天我们来回顾复习下IntentService,它是一个特殊Service,继承自Service并且是个抽象类。它可用于执行后台耗时任务,当任务执行完毕后会自动停止。由于IntentService是服务的原因,所以它的优先级比单纯的线程高,不容易被系统杀死,比较适合执行一些高优先级的后台任务。

一、什么是IntentService?

1、它是一个特殊的Service,继承自Service并且是个抽象类;

2、内部封装了HandlerThread、Handler 实现异步操作;

3、内部有一个工作线程来处理耗时的后台任务,任务完成后会自动停止;

4、可以多次启动,IntentService 会按顺序依次执行后台任务;

二、IntentService使用方法

1、创建一个IntentService的子类,实现onHandlerIntent和构造方法。

2、在onHandleIntent( Intent intent)方法中,执行耗时操作,intent中可以取出启动IntentService所携带的数据。

三、代码实践

1、创建MyIntentService 类继承自intentservice。 在onHandleIntent方法中调用SystemClock.sleep(3000); 休眠3000秒,来模拟耗时操作,并在 onDestroy方法中打印服务停止的日志。

package com.example.ling.review.intentservice;
import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

public class MyIntentService extends IntentService {
private static final String TAG = "MyIntentService";

public MyIntentService() {
super(TAG);
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
String action = intent.getStringExtra("task_action");
Log.d(TAG, "接收到任务:" + action + "开始执行!");
SystemClock.sleep(3000); // 休眠3000秒,模拟耗时操作
Log.d(TAG, action + "执行完毕!");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "服务已销毁关闭! ");
}
}


2、创建IntentServiceActivity 来测试,我们启动3次service 。

package com.example.ling.review.intentservice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class IntentServiceActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Intent service = new Intent(this, MyIntentService.class);
// 启动任务1
service.putExtra("task_action", "任务1");
startService(service);
// 启动任务2
service.putExtra("task_action", "任务2");
startService(service);
// 启动任务2
service.putExtra("task_action", "任务3");
startService(service);
}
}


3、在manifest清单文件中进行注册

<activity android:name=".intentservice.IntentServiceActivity"/>
<service android:name=".intentservice.MyIntentService" />


4、运行结果:



总结:

通过打印的日志我们发现多个任务时,它是串行执行的,所有的任务执行完成时,会自动停止服务。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: