【问题标题】:Check if Android foreground service is active on app restart?检查Android前台服务是否在应用重启时处于活动状态?
【发布时间】:2023-09-18 13:35:01
【问题描述】:

我有一个通过蓝牙与我的应用程序连接的传感器。我创建了一个前台服务,即使在用户关闭应用程序后,它也能保持应用程序处于活动状态并与传感器连接。要停止前台服务,用户重新启动应用程序并停止前台服务。

以上所有内容都已完美完成,并且适用于 NOW

我的问题是——

有一个播放和暂停按钮来启动和停止服务。启动后,图标会更改,但在完全关闭应用程序(不停止前台服务)后重新启动应用程序,应用程序不会更改。当然它不会改变,因为我不知道如何检查服务是否仍在前台运行。

是的,我已经阅读了所有以前的答案,其中大多数已被弃用或不再起作用。

由于 Commonsware 要求提供我迄今为止阅读的所有帖子的链接,所以你去 -

  1. Determining the current foreground application from a background task or service
  2. How to check is app in foreground from service?
  3. check android application is in foreground or not?
  4. Check if Foreground service is running in Android OREO
  5. How to determine if an Android Service is running in the foreground?

【问题讨论】:

  • “我已经阅读了所有以前的答案”——请链接。 “它们中的大多数都已弃用”-请提供链接。 “或不再工作” - 链接,请。假设您的服务在一个单独的进程中(android:process 属性),您应该能够尝试在没有BIND_AUTO_CREATE 的情况下绑定到它并查看绑定是否成功。或者,使用广播(小心)。如果您已经尝试过,也许minimal reproducible example 会帮助我们找到您实施中的问题。
  • 好的——我会把它们添加到我原来的帖子中
  • @CommonsWare 感谢您的提示。
  • 为什么要检查服务是否正在运行??您可以轻松地保存共享首选项存储您的服务“开”或“关”的状态,并在 on resume 事件中检查它以更改按钮的图像
  • @MohammedAlloboany 如果用户完全关闭应用程序怎么办?该应用将继续在后台运行。

标签: android service foreground


【解决方案1】:

试试这个工具来检查服务是否正在运行:

    public static boolean isServiceRunning(Context context, Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

【讨论】:

  • getSystemServices 已弃用。
【解决方案2】:

我找到了一个非常肮脏的解决方法来检查它,但它确实有效。我宁愿离开 UI 不一致的问题,我没有使用它,因为我有开关而不是按钮,并且可以轻松切换由用户更改。

在我的情况下,前台服务与通知一起运行,因此可以检查通知状态而不是前台服务状态。

var isServiceRunning = false;

val manager = getSystemService(NotificationManager::class.java)
for (notification in manager.activeNotifications){
    if (notification.notification.channelId == "ServiceChannel") {
        isServiceRunning = true;
        break;
    }
}

【讨论】:

    最近更新 更多