Android Service生命周期 Service里面的onStartCommand()方法详解

来源:互联网 发布:nasa直播软件 编辑:程序博客网 时间:2024/04/30 09:03

在Demo上,Start一个Service之后,执行顺序:onCreate - > onStartCommand

然后关闭应用,会重新执行上面两步。

但是把代码拷贝到游戏工程发现,关闭游戏后,只执行了onStart,却没有执行onStartCommand!

查找到下面的文章:

[plain] view plain copy 在CODE上查看代码片 派生到我的代码片

  1. Service里面的onStartCommand()方法详解  
  2.   
  3. 启动service的时候,onCreate方法只有第一次会调用,onStartCommand和onStart每次都被调用。onStartCommand会告诉系统如何重启服务,如判断是否异常终止后重新启动,在何种情况下异常终止  
  4. onStartCommand和onStart区别  
  5.   
  6. // This is the old onStart method that will be called on the pre-2.0  
  7. // platform. On 2.0 or later we override onStartCommand() so this  
  8. // method will not be called.  
  9. // 2.0 API level之后,实现onStart等同于重写onStartCommand并返回START_STICKY  
  10. @Override  
  11. public void onStart(Intent intent, int startId) {  
  12. handleCommand(intent);  
  13. }  
  14.   
  15. // 2.0 API level之后,onStart()方法被onStartCommand()取代了  
  16. @Override  
  17. public int onStartCommand(Intent intent, int flags, int startId) {  
  18. handleCommand(intent);  
  19. // We want this service to continue running until it is explicitly  
  20. // stopped, so return sticky.  
  21. return START_STICKY;  
  22. }   
  23.   
  24. 启 动服务时依次执行onCreate,onStartCommand,onStart;如果在系统显示调用stopService和stopSelf之前终 止服务,service再次重启,onStartCommand会被调用,重启服务时依次执行onStartCommand,onStart。无论何时, 都会先调用onStartCommand(),在调用onStart()。  
  25. onStartCommand返回值  
  26.   
  27. onStartComand使用时,返回的是一个(int)整形。  
  28. 这个整形可以有四个返回值:start_sticky、start_no_sticky、START_REDELIVER_INTENT、START_STICKY_COMPATIBILITY。  
  29. 它们的含义分别是:  
  30. 1):START_STICKY: 如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由 于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传 递到service,那么参数Intent将为null。  
  31. 2):START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务  
  32. 3):START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。   
  33.   
  34. 4):START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。  
  35.   
  36. onStartComand参数flags含义  
  37.   
  38. flags表示启动服务的方式:  
  39. Additional data about this start request. Currently either 0, START_FLAG_REDELIVERY, or START_FLAG_RETRY.  
  40.   
  41. START_FLAG_REDELIVERY: 如果你实现onStartCommand()来安排异步工作或者在另一个线程中工作, 那么你可能需要使用START_FLAG_REDELIVERY来 让系统重新发送一个intent。这样如果你的服务在处理它的时候被Kill掉, Intent不会丢失.  
  42. START_FLAG_RETRY:表示服务之前被设为START_STICKY,则会被传入这个标记。 
0 0
原创粉丝点击