4

我正在开发具有后台运行服务的 android 应用程序。

当我从“最近的应用程序列表”中换出应用程序时,它会导致应用程序关闭并停止服务。(以下方法具有相同的代码。)

    @Override
public void onTaskRemoved(Intent rootIntent)
{
       //code to be executed
       //Stop service
       super.onTaskRemoved(rootIntent);
    }

服务启动代码在应用程序类(onCreate())中,如果应用程序恢复,它将永远不会执行。

正面情景

1)如果我在成功执行服务后重新启动应用程序,将创建新的应用程序实例并且服务也将启动。

负面情景

1)由于上述方法中有一些代码负责停止线程和服务,导致应用程序需要一些时间才能停止服务(从最近的应用程序交换后)。在此期间,如果我重新启动应用程序,应用程序将恢复而不是重新创建。现在,正在运行的服务将停止。

因此,在这种情况下,我有应用程序但没有后台服务。

我该如何处理这种情况?

1) 在服务的任务完成之前,不应重新启动应用程序。2)从启动器活动启动服务。

提前致谢。

4

3 回答 3

0

您可以在 OnResume 中检查服务的状态并使用 Intent 从那里重新启动

  @Override
    protected void onResume() 
    {
        /*   This will be called when starting the UI and resume from background
         *   If the service is not running, then start the service and bind to the service. 
         *   If the service is already running, then just bind with the service. The status
         *   of the service is determined by the #DetermineServiceStatus function.
         */


      }
于 2014-02-28T06:56:20.330 回答
0

在 Service 类的 onStartCommand() 中,您必须将 return 设置为“START_STICKY”,以确保重新启动服务,该服务被 android 平台终止(如果应用程序中断)。

于 2014-02-28T06:54:24.587 回答
0

几乎无法控制服务的生命周期。当系统需要更多资源时,后台服务很容易被 Android 杀死。

设计后台服务的最佳方法是START_STICKY从您的onStartCommand()(您已经做过)返回 a,以确保当有足够的资源可用时,您的服务会自动重新启动,并且您在后台服务中执行的作业应该被实施,以便即使如果它被中断,它应该在 Android OS 重新启动时成功地继续其任务。

于 2014-02-28T07:19:13.983 回答