温故而知新,最新在复习的时候,突然发现又学到了不少东西。
我们开启一个服务的时候,会调用onStartCommand()方法。
onStartCommand源码:
private boolean mStartCompatibility = false;
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
}
返回值是START_STICKY,那么这玩意到底是啥?除了START_STICKY,还有START_NOT_STICKY ,START_REDELIVER_INTENT。那我们就瞧瞧。
- 如果onStartCommand函数返回Service.START_STICKY,那么系统会对该组件服务“负责”,在强行回收该组件后,在资源宽裕的时候还会调用Service.onStartCommand去重启启动服务,直到服务执行完所有操作后主动调用stopSelf()才能关闭服务,如android原生的音乐播放器在播放音乐时,就是需要返回Service.START_STICKY来保持运行不被系统回收。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
//一堆的if...省略
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return START_STICKY;
}
如果onStartCommand函数返回Serveice.START_NOT_STICKY,则说明系统可以无条件地回收该组件,无需关注服务是否完成。通常情况下,返回Serveice.START_NOT_STICKY的服务都是要长时间运行服务,服务的时效性较低。所以就需要在合适的时机定时启动服务。如一个邮件推送服务。
如果onStartCommand函数返回Serveice.START_DEDELIVER_INTENT,意味着需要保证服务组件能够完整地处理每个Intent对象,如果在服务的后台处理过程中,系统强行终止了该服务,则要求系统在资源允许的情况下重新传入该Intent对象(确保intent对象的请求和数据不丢失),直到服务组件处理完成,显性地调用Service.selfStop来关闭服务为止。 如调用组件传递给服务一些关键的数据(用户输入的账号,密码),就需要保证能够完整地执行完操作。android系统的日历控件的提醒服务,AlertService.onStartCommand源码代码如下:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent.getExtras();
mServiceHandler.sendMessage(msg);
}
return START_REDELIVER_INTENT;
}
另外START_STICKY_COMPATIBILITY,这个是为了兼容START_STICKY,解释是这么说的:
/**
* Constant to return from {@link #onStartCommand}: compatibility
* version of {@link #START_STICKY} that does not guarantee that
* {@link #onStartCommand} will be called again after being killed.
*/
好了,就这样。 :)
5879

被折叠的 条评论
为什么被折叠?



