Service和IntentService 源码分析和总结

本文详细介绍了Android中的Service组件,包括其作用、类型(如绑定服务与启动服务)以及如何使用Intent进行组件间通信。同时深入探讨了IntentService的工作原理,包括线程创建、消息处理流程等。

转载请注明出处:http://blog.youkuaiyun.com/onlybeyond99/article/details/50611275   挨踢人one
service
    Android 四大组建之一,存放一些需要长时间存活的对象,但并不是耗时操作,一般Service也是在主线程中。耗时的操作应该用AntentService。
    Service绑定的和非绑定的
   

Activity给非绑定的Service传值:在onStartCommand()中可以获得相应的Intent,Intent的可以用传参数
Activity给绑定的Service传值,在onbind()中可以获得相应的Intent,Intent的可以用于传参数
service给activity传值Handler或者EventBus都行。

Service销毁:当Service于所有的Activity都没有关系时才能被销毁。

IntentService
 可以简单的理解成执行耗时操作的Service


执行过程 oncreate的创建工作线程,获取线程Looper,创建ServiceHandler
.这是实现工作线程和子线程交互的关键。如果Service被启动过就不会在调用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);
}


每回startService后都会调用onStartCommand()方法。
public int onStartCommand(Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return mRedelivery START_REDELIVER_INTENT START_NOT_STICKY;
}

然后在onStart()方法中回调用onCreate()方法中创建的ServiceHandler,发送消息并传递Intent,
加入消息队列。收到消息后,执行onHandlerIntent()
@Override
public void onStart(Intent intent, int startId) {
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    msg.obj = intent;
    mServiceHandler.sendMessage(msg);
}

注意一般IntentService的工作线程只有一个,因此所有传进来的任务都是按顺序执行




 独学而无友,则孤陋而寡闻!分享知识,交流技术,碰撞思想。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值