当前位置: 移动技术网 > 移动技术>移动开发>Android > Android:IntentService详情

Android:IntentService详情

2018年11月01日  | 移动技术网移动技术  | 我要评论

借鉴自开发艺术

构造方法中必须调用父类的有参构造

intentservice是一个抽象类

适合,需要高优先级的,短期的,后台耗时任务,执行完后会自动停止。

封装了handlerthread和handler。

@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来构造一个handler对象mservicehandler。通过mservicehandler发送的消息,都会在handlerthread中执行。intentservice在onstartcommond中处理每个后台任务的intent。

onstartcommand中调用了onstart

@override
public int onstartcommand(@nullable intent intent, int flags, int startid) {
    onstart(intent, startid);
    return mredelivery ? start_redeliver_intent : start_not_sticky;
}

onstart

@override
public void onstart(@nullable intent intent, int startid) {
    message msg = mservicehandler.obtainmessage();
    msg.arg1 = startid;
    msg.obj = intent;
    mservicehandler.sendmessage(msg);
}
发送消息(包含intent),最后在onhandleintent中处理
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);
    }
}

在onhandleintent调用完后停止他自身,采用的是带参数的stopself,带参会等全部消息处理完后才停止服务,无参数的会立刻停止服务。

每执行一个后台任务必须启动一次intentservice,不难得知,后台任务执行的顺序也如消息队列一样,按外界发起的顺序来执行。但是service的特性是只有1个实例。当所有后台任务执行完后,执行ondestory。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网