adndroid service生命周期

http://blog.csdn.net/yangkele/article/details/6791456

adndroid service生命周期:
  一、context.startService(Intent)调用:
      onCreate()-->onStart()
      1、onStart()后调用bindService该service则调用onBind(),调用onBind以后调stopService将无法释放该service必须再调unbindService才触发onUnbind()-->onDestroy()
         bindService后如果没有调用unbindService就退出activity,则只会调用unbind()方法,并且无法释该service
         结论:如果先startService再bindService,则只有调用unbindService和stopService了后才能释放该service,否则只调用其中一个无法释放该service
         释放顺序1:unbindService-->unBind()-->stopService-->onDestroy()
         释放顺序2:stopService-->unbindService-->unBind()-->onDestroy()
         释放顺序3:stopService-->推出active-->unBind()-->onDestroy()
      2、onStart()后调用unbindService,unbindService方法会抛异常,该service对象会消失,没有调用生命周期中得任何方法,
         异常抛出后会自动调用onCreate()-->onStart()创建对象
      3、onStart()后调用stopService释放该service,执行顺序:onDestroy()
      4、onStart()后调用startService不会创建新的service,执行顺序:onStart()
      执行顺序列表(on开头的方法位service生命周期方法,其他为context对象方法):
      1、context.startService(Intent)-->onCreate()-->onStart()-->context.unbindService()(方法会抛异常)-->onCreate()-->onStart()
      2、context.startService(Intent)-->onCreate()-->onStart()-->context.stopService-->onDestroy()
      3、context.startService(Intent)-->onCreate()-->onStart()-->context.startService-->onStart()
     
      4、context.startService(Intent)-->onCreate()-->onStart()-->context.bindService()-->onBind-->context.unbindService-->unBind()-->context.stopService-->onDestroy()
      5、context.startService(Intent)-->onCreate()-->onStart()-->context.bindService()-->onBind-->context.stopService-->context.unbindService-->unBind()-->onDestroy()
      6、context.startService(Intent)-->onCreate()-->onStart()-->context.bindService()-->onBind-->context.stopService-->退出active-->unBind()-->onDestroy()
  二、context.bindService()调用:  
 
      1、context.bindService()-->onCreate()-->onBind()-->context.unbindService()-->unBind()-->onDestroy()
      2、context.bindService()-->onCreate()-->onBind()-->context.stopService
      3、context.bindService()-->onCreate()-->onBind()-->context.startService-->onStart()
     
      4、context.bindService()-->onCreate()-->onBind()-->context.startService()-->context.unbindService-->unBind()-->context.stopService-->onDestroy()
      5、context.bindService()-->onCreate()-->onBind()-->context.startService()-->context.stopService-->context.unbindService-->unBind()-->onDestroy()
      6、context.bindService()-->onCreate()-->onBind()-->context.startService()-->context.stopService-->退出active-->unBind()-->onDestroy()  
     
综合以上2点,在对service调用时最好只用一种方式,start或者bind,如果使用了2种方式,2种方式得到的是同一个service对象,并且必须是2种方式都调用了退出方式才能释放service
bind方式默认退出activity则启动释放service


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值