Android 与前台服务通信的最佳方式

Android Best-Way to communicate with a Foreground Service

我对 android 有点陌生。我想知道如何与前台启动的服务通信。

所以,我得到了一个带有通知的前台服务。 此通知有一个 (X) 按钮来停止服务。

服务获得静态广播接收器。

public static class NotificationStopButtonHandler extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"Close Clicked",Toast.LENGTH_SHORT).show();
            Log.i(LOG_TAG, "In Closed");

            // imposible to do context.stopForground(true) or
            // to call any other private coded by me
        }
}

所以我的问题是: BroadcastReceiver 是最好的方法吗? 如果是:我如何与服务通信以在 broadcastReceiver 中调用 stopForeground?

提前感谢您的回复。

但我想知道除了 broadcastReceiver 之外还有哪些解决方案。谢谢

您可以在构建通知时使用 PendingIntent with an Intent to the Service and tell the Service to shut down. You assign the PendingIntent to the close button action and/or to the notifications onDelete call 而不是广播。

假设您通过通知启动服务,您可以在 Intent 中放置命令以告知服务自行停止。 Service#onStartCommand 将使用新 Intent 在服务上调用。该服务检查关闭调用并在完成后调用 stopSelf()

基本上,之所以可行,是因为只能启动一个服务。每次后续启动服务的尝试都会将意图发送到 Service#onStartCommand,但不会重新启动 Service。因此,这是一种您可以通过绑定之外的方式向服务发送命令的方式。此外,它 way 比使用广播更干净。

在您的通知中,您将有一个 X 按钮的 PendingIntent。我假设您已经使用

构建了 PendingIntent
PendingIntent.getBroadcast(/* ... */);

您可以改为为您的服务创建一个 PendingIntent

Intent intent = /* intent for starting your service */;
intent.putExtra("STOP_FOREGROUND", true);
PendingIntent.getService(context, requestCode, intent, flags);

并且在传递给 PendingIntent 的意图中,您将添加一个额外的 (STOP_FOREGROUND)。当此意图被触发时,您的服务将在 onStartCommand() 中被调用。在这里你检查意图,如果它包含你的额外内容,你知道你应该调用 stopForeground。