在停止时在服务上调用onStart()

时间:2015-03-10 07:43:29

标签: android service

我有一个应用程序,我在启动时启动服务:

    Intent networkingService=new Intent(MainActivity.this, SocketMngr.class);
    networkingService.putExtra("FbID",myFbId);
    if (mService==null) mService=new Messenger(messageHandler); //mService is private messenger variable of the activity 
    networkingService.putExtra("MESSENGER", mService);
    networkingService.putExtra("REGIDID", regid);
    startService(networkingService);
    bindService(networkingService, mConnection, Context.BIND_AUTO_CREATE);  //mConnection is a private variable of the activity

现在,当用户退出应用程序时,我将主活动中的静态标志变量设置为服务将在每个间隔秒查看的值,以了解是否自杀。

在主要活动中:

 @Override
public void onDestroy()
{
   this.SERVICE_KILL_YOURSELF=true; //this flag is false when app launched
}

并在服务中,例如:

 while(MainActivity.SERVICE_KILL_YOURSELF==false)
 {
    ProcessData(); //can take long time thus can be processed while main activity finished
 }
 stopMySelf()

现在,我正在使用所描述的场景,因为当用户退出应用程序时,该服务仍然可以从服务器接收最后的数据包或发送此类数据,只有在此之后,该服务才能自杀。

现在,如果服务在应用销毁后仍在处理最后一个数据,那么在服务查看MainActivity.SERVICE_KILL_YOURSELF之前再次启动应用,然后应用在启动时设置SERVICE_KILL_YOURSELF=false,那么{{1}将被调用,服务将不会被停止,这很好。

我担心和质疑的是,如果服务查看onStart() MainActivity.SERVICE_KILL_YOURSELF因为应用程序被销毁,那么服务开始停止并且当它被停止时会发生什么应用程序再次启动,并调用服务true

在那种情况下会发生什么,有什么我应该关注的吗?

1 个答案:

答案 0 :(得分:-1)

退出计划可能无法调用onDestroy()甚至onStop()您只知道当程序退出时肯定会调用onPause()因此在使用onDestroy()

即使用户关闭了您的应用,您的服务也可能保留原样。