【问题标题】:Service stops when application is closed应用程序关闭时服务停止
【发布时间】:2016-04-21 10:41:46
【问题描述】:

我需要一项服务在后台运行并计算两个位置之间的每分钟距离。我使用 Thread 每分钟执行一个方法,然后我明白当应用程序关闭时,服务也会停止,因为应用程序和服务使用相同的线程。 如何在后台创建一个每 1 分钟调用一次的简单方法,即使应用程序已关闭?

【问题讨论】:

标签: android service


【解决方案1】:

可以通过修改清单在单独的进程中运行Service

<service
    android:name="com.example.myapplication.MyBackgroundService"
    android:exported="false"
    android:process=":myBackgroundServiceProcess" >
</service>

但这可能不会真正带来任何好处。大多数时候it may even be a bad idea

当然,最重要的是如果Service 被关闭,它就会重新启动。

ServiceonStartCommand() 可以返回START_STICKY 标志:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Other code goes here...

    return START_STICKY;
}

这个(和其他)选项解释in the documentation。基本上START_STICKY 的意思是“嘿Android!如果你真的因为内存不足而不得不关闭我宝贵的服务,那么请尝试重新启动它。”

START_NOT_STICKY 的意思是“不...不要打扰。如果我真的需要我的服务运行,我会自己再次调用 startService()。”

这(开始粘性)可能大部分时间都很好。您的服务将重新从头开始。如果这适合您的用例,您可以尝试。

还有一些不太可能被 Android 关闭的“前台服务”,因为它们被视为可视应用程序。事实上,它们显示在通知抽屉中,带有一个图标和(如果你这样做的话)一个状态文本。因此它们对用户可见,例如SportsTracker、Beddit 等应用。

这涉及修改您的ServiceonStartCommand()

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Tapping the notification will open the specified Activity.
    Intent activityIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
            activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // This always shows up in the notifications area when this Service is running.
    // TODO: String localization 
    Notification not = new Notification.Builder(this).
            setContentTitle(getText(R.string.app_name)).
            setContentInfo("Doing stuff in the background...").setSmallIcon(R.mipmap.ic_launcher).
            setContentIntent(pendingIntent).build();
    startForeground(1, not);

    // Other code goes here...

    return super.onStartCommand(intent, flags, startId);
}

Service 照常启动,您可以通过以下方式退出前台模式:

myBackgroundService.stopForeground(true);

布尔参数定义是否也应关闭通知。

【讨论】:

  • 很好的解释
  • 第二种方法似乎是大多数应用程序执行此操作的方式。先生,我非常感谢您,您解决了数小时的谷歌搜索和文档搜索。
  • 但是对于 android 8.0,现在一切都改变了...@Markus
【解决方案2】:

您必须为此使用线程并在启动服务时设置一个标志。并检查该标志以停止服务。

【讨论】:

    【解决方案3】:

    除了之前朋友提供的解决方案...

    确保在您的应用设置中选中“允许后台活动”按钮!

    See the picture: In the Battery section

    【讨论】:

      猜你喜欢
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多