一、IntentService介绍
(1)一个封装了HandlerThread和Handler的异步框架。
(2)一种特殊Service,继承自Service,是抽象类,必须创建子类才可以使用。
(3)可用于执行后台耗时的任务,任务执行后会自动停止。
(4)具有高优先级(服务的原因),优先级比单纯的线程高很多,适合高优先级的后台任务,且不容易被系统杀死。
(5)启动方式和Service一样。
(6)可以多次启动,每个耗时操作都会以工作队列的方式在IntentService的onHandleIntent回调方法中执行。
(7)串行执行。
二、IntentService的使用
1、创建IntentService
/**
* @ClassName MyIntentService
* @Description TODO
* @Author xia
* @Date 2022/8/9 16:19
* @Version 1.0
*/
public class MyIntentService extends IntentService {
/**
* 是否正在运行
*/
private boolean isRunning;
/**
*进度
*/
private int count;
/**
* 广播
*/
private LocalBroadcastManager mLocalBroadcastManager;
public MyIntentService() {
super("MyIntentService");
Log.e("xia","MyIntentService");
}
@Override
public void onCreate() {
super.onCreate();
Log.e("xia","onCreate");
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.e("xia","onHandleIntent");
try {
Thread.sleep(1000);
isRunning = true;
count = 0;
while (isRunning) {
count++;
if (count >= 100) {
isRunning = false;
}
Thread.sleep(50);
sendThreadStatus("线程运行中...", count);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 发送进度消息
*/
private void sendThreadStatus(String status, int progress) {
Intent intent = new Intent(IntentServiceActivity.ACTION_TYPE_THREAD);
intent.putExtra("status", status);
intent.putExtra("progress", progress);
mLocalBroadcastManager.sendBroadcast(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("xia","线程结束运行..." + count);
}
}
2、注册服务
<service android:name=".service.MyIntentService"/>
3、调用IntentService
/**
* @ClassName IntentServiceActivity
* @Description TODO
* @Author xiazhenjie
* @Date 2022/8/9 16:25
* @Version 1.0
*/
public class IntentServiceActivity extends AppCompatActivity {
//状态文字
TextView tv_status;
//进度文字
TextView tv_progress;
//进度条
ProgressBar progressbar;
private LocalBroadcastManager mLocalBroadcastManager;
private MyBroadcastReceiver mBroadcastReceiver;
public final static String ACTION_TYPE_THREAD = "action.type.thread";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_service);
tv_status = findViewById(R.id.tv_status);
tv_progress = findViewById(R.id.tv_progress);
progressbar = findViewById(R.id.progressbar);
//点击开启IntentService, 启动多次,则IntentService内执行多次onHandleIntent()
findViewById(R.id.btn_start).setOnClickListener(v -> {
Intent intent = new Intent(IntentServiceActivity.this, MyIntentService.class);
startService(intent);
});
//注册广播
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
mBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_TYPE_THREAD);
mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);
initView();
}
public void initView() {
tv_status.setText("线程状态:未运行");
progressbar.setMax(100);
progressbar.setProgress(0);
tv_progress.setText("0%");
}
@Override
protected void onDestroy() {
super.onDestroy();
//注销广播
mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
}
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case ACTION_TYPE_THREAD:
//更改UI
int progress = intent.getIntExtra("progress", 0);
tv_status.setText("线程状态:" + intent.getStringExtra("status"));
progressbar.setProgress(progress);
tv_progress.setText(progress + "%");
if (progress >= 100) {
tv_status.setText("线程结束");
}
break;
}
}
}
}
4、现象
三、IntentService的原理分析
1、首先贴出IntentService的源码
package android.app;
import android.annotation.Nullable;
import android.annotation.WorkerThread;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
@Deprecated
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
@UnsupportedAppUsage
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {
super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*/
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
@Nullable
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*/
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent);
}
2、源码分析
(1)IntentService的onCreate() 底层原理:
- 首先构造了HandlerThread;
- 然后保存了HandlerThread的Looper;
- 并且使用该Looper创建了ServiceHandler;
(2)因为上一步,已经构建了一个消息队列,所以HandlerThread会在队列取出任务并且执行,会调用ServiceHandler的handleMessage去处理任务。
(3)handlerMessage会去把数据传给onHandleIntent方法。onHandleIntent是个抽象方法,需要在IntentService实现,所以每次onStart方法之后都会调用我们自己写的onHandleIntent方法去处理。
(4)任务处理完毕后,使用stopSelf通知HandlerThread已经处理完毕,HandlerThread继续观察消息队列,如果还有未执行玩的message则继续执行,否则在onDestory()中会退出HandlerThread中Looper的循环。