深入探索Android Service

真的是好久没有写博客了,突然觉得自己有时候很容易放弃很多东西,好了,现在重新开始自己的博客之旅。

废话不多说了,首先是,之前也写过一个比较简单的Service解析的文章Android Service初解,但是当时对这个东西理解不是很深入,所以很多东西都是写的很简单的,最近开始看Android的开发文档,然后觉得对Service有了一些更深入的认识,现在写下来,避免以后忘记。

首先什么是Service,我们为什么要使用Service而不是别的组件?

在Android的四大基本组件(Actvitiy,Service,ContentProvider,BroadcastReceiver)中,Service能够为我们提供长时间的后台服务,并且可以实现进程间通信(IPC)


Service中涉及到的方法主要有以下几种:

1)onCreate():服务开始创建时,系统自动调用

2)onStartCommand():每次调用startService()时,系统自动调用

3)onBind():第一次调用bindService()时,系统调用。之后无论bindService()运行多少次,只要服务尚未被销毁,那么系统均会自动将第一次调取onBind()的返回值返回,避免重复调用

4)onDestory():服务销毁时调用


Service的启动方式有以下两种:

1)startService():

以startService()启动的服务,不依赖于应用而存在,当应用关闭后,服务仍然生存,故我们需要调用stopSelf()或者stopService()来结束服务。

2)bindService():

以bindService()启动的服务,在所有绑定他的组件unbindService()之后,就会自动销毁服务,而我们也无法使用stopSelf()或者stopService()来销毁这个服务。

在组件中调用bindService()后,会在onBind()方法中返回一个IBinder对象,这个对象通常会将Service类对象包含起来,用于在组件类中实现交互操作,故bindService()一般用于情况较复杂的时候,然后根据自身需求直接调用Service之中的方法。


常用的Service类:

有android.app.Service和android.app.IntentService。IntentService继承自Service,这两者的主要区别在于IntentService中的这些代码:

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);
        }
    }
 @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

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

故每次启动IntentService,都会新建一个线程,并在新线程中调用onHandleIntent(),之后会自动结束Service。因此,每次调用IntentService()都会经历onCreate(),onStartCommand(),onDestory()的生命周期。而针对IntentService所调取的stopService()对他是没有无效的。

并且IntentService中,对于onBind()模块只是返回一个null值,并未做出其他处理,故一般仅有startService()中会使用到他,在bindService()中我们还是使用的Service。

最后,Service在默认情况下是运行于系统主线程中,所以当你在Service中运行耗时较久的服务,例如播放音乐或者网络连接服务时,最好新建线程处理,以避免出现ui堵塞的情况

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值