在Demo上,Start一个Service以后,执行顺序:onCreate - > onStartCommandphp
而后关闭应用,会从新执行上面两步。html
可是把代码拷贝到游戏工程发现,关闭游戏后,只执行了onStart,却没有执行onStartCommand!app
查找到下面的文章:异步
[plain] view plain copy
ide
Service里面的onStartCommand()方法详解 ui
启动service的时候,onCreate方法只有第一次会调用,onStartCommand和onStart每次都被调用。onStartCommand会告诉系统如何重启服务,如判断是否异常终止后从新启动,在何种状况下异常终止 this
onStartCommand和onStart区别 url
// This is the old onStart method that will be called on the pre-2.0 spa
// platform. On 2.0 or later we override onStartCommand() so this 线程
// method will not be called.
// 2.0 API level以后,实现onStart等同于重写onStartCommand并返回START_STICKY
@Override
public void onStart(Intent intent, int startId) {
handleCommand(intent);
}
// 2.0 API level以后,onStart()方法被onStartCommand()取代了
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
启 动服务时依次执行onCreate,onStartCommand,onStart;若是在系统显示调用stopService和stopSelf以前终 止服务,service再次重启,onStartCommand会被调用,重启服务时依次执行onStartCommand,onStart。不管什么时候, 都会先调用onStartCommand(),在调用onStart()。
onStartCommand返回值
onStartComand使用时,返回的是一个(int)整形。
这个整形能够有四个返回值:start_sticky、start_no_sticky、START_REDELIVER_INTENT、START_STICKY_COMPATIBILITY。
它们的含义分别是:
1):START_STICKY: 若是service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试从新建立service,由 于服务状态为开始状态,因此建立服务后必定会调用onStartCommand(Intent,int,int)方法。若是在此期间没有任何启动命令被传 递到service,那么参数Intent将为null。
2):START_NOT_STICKY:“非粘性的”。使用这个返回值时,若是在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务
3):START_REDELIVER_INTENT:重传Intent。使用这个返回值时,若是在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
4):START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后必定能重启。
onStartComand参数flags含义
flags表示启动服务的方式:
Additional data about this start request. Currently either 0, START_FLAG_REDELIVERY, or START_FLAG_RETRY.
START_FLAG_REDELIVERY: 若是你实现onStartCommand()来安排异步工做或者在另外一个线程中工做, 那么你可能须要使用START_FLAG_REDELIVERY来 让系统从新发送一个intent。这样若是你的服务在处理它的时候被Kill掉, Intent不会丢失.
START_FLAG_RETRY:表示服务以前被设为START_STICKY,则会被传入这个标记。