我对android很新。我想知道如何与前台启动的服务进行通信。
所以,我得到了一个带有通知的Foreground服务。 此通知有一个(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之外的其他解决方案。 THX
答案 0 :(得分:1)
您可以使用PendingIntent对服务使用Intent而不是广播,并告知服务关闭。在构建通知时,您将PendingIntent
分配给关闭按钮操作和/或分配给notifications
onDelete call。
假设您通过通知启动服务,您可以在Intent中放置命令以告知服务自行停止。将使用新的Intent在服务上调用Service#onStartCommand
。服务检查关闭呼叫并在完成后调用stopSelf()
。
基本上,这是有效的原因是因为只能启动一个服务。每次后续尝试启动服务都会将意图发送到Service#onStartCommand
,但不会重新启动Service
。因此,这是一种可以通过绑定之外的方式向服务发送命令的方法。加上它的方式比使用广播更干净。
答案 1 :(得分:0)
在您的通知中,您将拥有X按钮的PendingIntent。我认为你用
构建了PendingIntentPendingIntent.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。