IntentService 详解(从使用到源码撸一遍)

来源:互联网 发布:mac chrome 常用插件 编辑:程序博客网 时间:2024/06/06 07:08

为什么会有IntentService?

我们知道,Service作为四大组件之一,也会是运行在主线程的,所以我们如果有耗时的操作,应该新开一个线程。
为此android专门提供了一个类,就是IntentService,它的里边包含了一个handler用于处理后台线程。
使用IntentService,首先继承它,然后实现onHandleIntent()方法。

举个例子,模拟上传和下载文件的demo:
我的IntentService:

package example.ylh.com.service_demo;import android.app.IntentService;import android.content.Intent;import android.util.Log;/** * Created by yangLiHai on 2017/8/30. */public class TestIntentService extends IntentService {    private String TAG = TestIntentService.class.getSimpleName();    public static final String ACTION_UPLOAD_FILE = "action_upload_file";    public static final String ACTION_DOWNLOAD_FILE = "action_download_file";    /**     * Creates an IntentService.  Invoked by your subclass's constructor.     *     *  Used to name the worker thread, important only for debugging.     */    public TestIntentService() {        super("test intent service");        Log.e(TAG,"construction");    }    @Override    public void onCreate() {        Log.e(TAG,"oncreate");        super.onCreate();    }    @Override    public void onDestroy() {        Log.e(TAG,"ondestroy");        super.onDestroy();    }    @Override    protected void onHandleIntent(Intent intent) {        String action = intent.getAction();        if (action.equals(ACTION_DOWNLOAD_FILE)){            downloadFile();        }else if (action.equals(ACTION_UPLOAD_FILE)){            uploadFile();        }        try {            Thread.sleep(300);        } catch (InterruptedException e) {            e.printStackTrace();        }    }    private void uploadFile(){        Log.e(TAG,"handleintent upload:"+Thread.currentThread().getId()+"");    }    private void downloadFile(){        Log.e(TAG,"handleintent download:"+Thread.currentThread().getId()+"");    }}

activity代码:

package example.ylh.com.service_demo;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.util.Log;import android.view.View;import example.ylh.com.R;/** * Created by yanglihai on 2017/8/17. */public class ServiceTestActivity extends Activity {    public static final String TAG = ServiceTestActivity.class.getSimpleName();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.service_test_activity);        findViewById(R.id.btn4).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                startUploadService();            }        });        findViewById(R.id.btn5).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                startDownloadService();            }        });    }    public void startDownloadService(){        Intent i = new Intent(ServiceTestActivity.this, TestIntentService.class);        i.setAction(TestIntentService.ACTION_DOWNLOAD_FILE);        startService(i);    }    public void startUploadService(){        Intent i = new Intent(ServiceTestActivity.this, TestIntentService.class);        i.setAction(TestIntentService.ACTION_UPLOAD_FILE);        startService(i);    }}

通过Intent来传递数据,分发不同的任务。多次调用会被内部的handler放到队列中,任意时间只有一个intent正在被处理,队列中没有需要处理的任务的时候,就会销毁自己。
多次点击两个按钮的打印结果如下:

可以清楚地看到,上传和下载任务都是在子线程中执行的,当所有的任务执行完之后就会destroy。所以使用IntentService我们不用考虑Service的生命周期,也不用自己创建子线程开启任务,一切都帮我们做好了,用起来还是很方便的。

IntentService源码解析
IntentService继承自Service,他是一个特殊的service,它的内部封装了HandlerThread和Handler。
这是它的onCreate方法:

    @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);    }

第一次启动的时候,onCreate方法会被调用,创建了一个HandlerThread,然后使用它的looper来构造mServiceHandler(一个handler对象)。这样mServiceHandler就可以在子线程处理任务了。执行完oncreat之后,就会执行onStartCommand方法,多次启动IntentService就会多次调用onStartCommand方法,
这是onStartCommand方法的具体代码:

@Overridepublic int onStartCommand(@Nullable Intent intent, int flags, int startId) {    onStart(intent, startId);    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;}

可以看见里边调用了onStart方法,我们再来看看onStart方法:

@Override   public void onStart(@Nullable Intent intent, int startId) {       Message msg = mServiceHandler.obtainMessage();       msg.arg1 = startId;       msg.obj = intent;       mServiceHandler.sendMessage(msg);   }

在onStart方法中,每次都会用mServiceHandler发送一个消息,然后我们在看看mServiceHandler的代码:

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);      }  }

可以清楚地看到,每次收到intent之后,都会把intent交给onHandleIntent方法去处理,也就是我们需要重写的方法,通过intent我们可以解析出来外界传进来的数据,做相应的处理。onHandleIntent执行完之后,又执行了stopSelf(int startid)方法去关闭自身。但是他不是立刻去关闭,而是等待所有的intent被处理完之后才终止服务。一般来说,stopSelf(int startId)在关闭之前都会判断最近启动服务的次数和startId是否相等,如果相等就立刻停止服务,如果不相等,则不停止。

IntentService多数情况下都非常简单实用,你只需要生成后台任务操作,而不用关系启动时机,如果给IntentService发送多个Intent,这些Intent会按顺序执行,每次执行一个。如果有并发需求,并不适合用IntentService,还是自己写Service吧。

IntentService到这里已经说完了,看完我的例子在看看源码,相信你已经能完全理解了。
如果那里说的不够准确请给我留言,谢谢。