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

               


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

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


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

查找到下面的文章:

Service里面的onStartCommand()方法详解启动service的时候,onCreate方法只有第一次会调用,onStartCommand和onStart每次都被调用。onStartCommand会告诉系统如何重启服务,如判断是否异常终止后重新启动,在何种情况下异常终止onStartCommand和onStart区别// This is the old onStart method that will be called on the pre-2.0// platform. On 2.0 or later we override onStartCommand() so this// method will not be called.// 2.0 API level之后,实现onStart等同于重写onStartCommand并返回START_STICKY@Overridepublic void onStart(Intent intent, int startId) {handleCommand(intent);}// 2.0 API level之后,onStart()方法被onStartCommand()取代了@Overridepublic 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,则会被传入这个标记。 

于是在onStartCommand函数中返回 START_REDELIVER_INTENT ,问题解决。

 @Override public int onStartCommand(Intent intent, int flags, int startId) {  Log.i("cp","push_service onStartCommand "+" flags="+flags+" startId="+startId+" PackageName="+push_service.this.getPackageName());  m_SdCardPath=Environment.getExternalStorageDirectory().getPath();  m_PushFileDirPath=m_SdCardPath+File.separator+push_service.this.getPackageName();  m_PushFilePath=m_PushFileDirPath+File.separator+"push.txt";    if(mMessageThread!=null)  {   mMessageThread.mRunable=false;  }  mMessageThread=new MessageThread();  mMessageThread.start();  //super.onStartCommand(intent, flags, startId);  return START_REDELIVER_INTENT; }




           

猜你喜欢

转载自blog.csdn.net/qq_44952746/article/details/89472403