源码学习之IntenteService

本文详细介绍了Android中的IntentService组件。IntentService是一种特殊的Service,用于处理异步任务。文章讲解了IntentService的工作原理,包括如何通过startService发送请求,如何在子线程中处理Intent,以及如何在处理完毕后自动停止Service。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IntentService是基于Service实现的,它会按需求处理一些异步任务。通过调用startService,客户端就可以发送请求了。如果有需要的话,Service才会被启动,在子线程依次处理每个Intent,处理完任务以后Service会停止。使用的时候要继承IntentService,并实现onHandleIntent(Intent intent)方法。IntentService会接收Intent,开启一个子线程,并在适当的时候停止Service。所有的请求会在一个单线程进行处理,所以在同一时刻只能处理一个任务。

调用onCreate以后,会启动一个工作线程(HandlerThread是继承Thread的),并初始化处理消息的ServiceHandler,和工作线程的Looper进行关联。
@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);
    }
调用这个方法以后,会给mServiceHandler发送一条消息,任务交由mServiceHandler来处理。
@Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
收到消息以后,会调用onHandleIntent方法,在这个方法里可以实现自己的逻辑处理。当处理完所有消息以后,会调用stopSelf来停止Service。
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);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值