IntentServer是什么?怎么用?
看以下它的关系
public abstract class IntentService extends Service {
1、继承自server它是一个特殊的server,同时是一个抽象类。
2、通过注解就可以了解到,它用于处理异步任务,处理完成自动停止,无需手动调用stopSelf()
3、其内部自己创建线程执行Intent请求,处理onHandleIntent()里的代码,这点不同于Server,Server运行在主线程,往往在需要处理耗时操作时需要我们自己创建子线程。
用法十分简单:
1、创建子类
class MyIntentServer(name: String) : IntentService(name) {
//用Intent传入数据执行
override fun onHandleIntent(intent: Intent?) {
...//写自己需要处理的代码
}
2、向清单文件注册
<service android:name=".MyIntentServer"></service>
然后在startService()就行了,很简单啊,下面通过源码看看怎么执行的
看源码
1、上面我们创建子类的时候传入了一个name,是用来设置线程名的;
看看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(),里面先时创建线程,然后开启线程,随后获取looper,我们知道在哪个线程获取looper,哪个线程就是相对的主线程,随后利用HandlerThread在子线程中的Looper生成一个在子线程中工作的ServiceHandler。
我们看下ServiceHandler干了什么:
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);
}
}
handleMessage()里调用了onHandleIntent()方法,同时传入msg对象,完成后调用了stopSelf(msg.arg1),上面讲的都还是初始化操作。
那好,离真相又近一步,因为service的生命周期,不用猜都知道现在需要找onStarCommand()方法看它怎么调用的:
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
调用onstart():
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
首先获取mServiceHandler,获取消息对象并sendMessage,开始执行onHandleIntent()里的逻辑
只是浅浅的了解以下,日后完善。