我对安卓有点陌生。我想知道如何与前台启动的服务通信。
所以,我得到了一个带有通知的前台服务。 此通知有一个 (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?
预先感谢您的回复。
Same question like mien...但我想知道除了 broadcastReceiver 之外还有哪些解决方案。谢谢
最佳答案
在您的通知中,您将有一个 X 按钮的 PendingIntent。我假设您已经使用
构建了 PendingIntentPendingIntent.getBroadcast(/* ... */);
您可以做的是为您的服务创建一个 PendingIntent
Intent intent = /* intent for starting your service */;
intent.putExtra("STOP_FOREGROUND", true);
PendingIntent.getService(context, requestCode, intent, flags);
在传递给 PendingIntent 的 Intent 中,您将添加一个额外的 (STOP_FOREGROUND)。当此 Intent 被触发时,您的服务将在 onStartCommand() 中被调用。在这里您检查 Intent ,如果它包含您的额外内容,您知道您应该调用 stopForeground。
关于Android 与前台服务通信的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40313651/