1.IntentService
(1).介绍Service
Android中的Service是用于后台服务的,当应用程序被挂起到后台或者启动Service的Activity被销毁时,为了保证应用某些组件仍然可以工作而引入了Service这个概念,但是Service既不是独立的进程,也不是独立的线程,它是依赖于应用程序的主线程的,在大部分时候不建议在Service中编写耗时的逻辑和操作,否则会引起ANR。(阻塞主线程5s,会导致ANR)
(2).IntentService||JobIntentService应用场景
如果我们编写的耗时逻辑,不得不被service来管理的时候,就需要使用IntentService,IntentService是继承Service的,那么它包含了Service的所有特性,当然也包含service的生命周期,那么与service不同的是,IntentService在执行onCreate操作的时候,内部开了一个线程,去你执行你的耗时操作。
public abstract class IntentService extends Service {
protected abstract void onHandleIntent(@Nullable Intent intent);
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);
}
}
public void onCreate() {
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);
}
}
(3).继承抽象类IntentService,然后实现handleIntent方法即可.
public class TestService extends IntentService {
public TestService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
}
}
(4).HandleThread实现
继承了Thread,Looper.prepare()将当前线程和Looper对象存储到ThreadLocalMap中,然后提供getLooper方法。
public class HandlerThread extends Thread {
public void run(){
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
}
public Looper getLooper() {
return mLooper;
}
}
2.JobIntentService
(1).通过内部的AysncTask来处理耗时操作
public abstract class JobIntentService extends Service {
protected abstract void onHandleWork(@NonNull Intent intent);
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
ensureProcessorRunningLocked(true);
}
void ensureProcessorRunningLocked(boolean reportStarted) {
if (mCurProcessor == null) {
mCurProcessor = new CommandProcessor();
if (mCompatWorkEnqueuer != null && reportStarted) {
mCompatWorkEnqueuer.serviceProcessingStarted();
}
mCurProcessor.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
final class CommandProcessor extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
GenericWorkItem work;
if (DEBUG) Log.d(TAG, "Starting to dequeue work...");
while ((work = dequeueWork()) != null) {
if (DEBUG) Log.d(TAG, "Processing next work: " + work);
onHandleWork(work.getIntent());//回调onHandlerWork方法
if (DEBUG) Log.d(TAG, "Completing work: " + work);
work.complete();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
processorFinished();
}
}
}
(2).使用继承抽象类JobIntentService,实现onHandleWork来处理耗时操作
public class TestService extends JobIntentService {
@Override
protected void onHandleWork(@NonNull Intent intent) {
//在AsyncTask启动的异步线程中执行
}
}