【发布时间】:2017-01-14 22:02:25
【问题描述】:
我正在尝试在音乐播放服务运行时构建通知,并使用通知通过广播机制与服务交互(播放、暂停、停止)。
(我知道也可以使用 PendingIntent.getService() 作为通知中的操作按钮,但我不喜欢这个想法,因为这会触发服务的 onStartCommand() 和我需要解析和分析 Intent 对象以采取行动,这似乎不如 BroadcastReceiver 方法干净,如下所述)。
让我们用一些(截断的)代码来说明我们目前所拥有的。
-
我们正在服务生命周期内创建一个通知对象,添加一个操作按钮,并使用
startForeground()显示通知。... Intent i = new Intent(getBaseContext(), PlayerService.class); PendingIntent piStop = PendingIntent.getBroadcast(getBaseContext(), 1, i, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Action actionStopPlayback = new NotificationCompat.Action(R.drawable.ic_stop_white_36dp, "Stop playback", piStop); notification.addAction(actionStopPlayback); ... -
然后我们在服务的 onCreate() 中注册一个 BroadcastReceiver(当然在 onDestroy 中取消注册;这是一个更简化的示例)。
IntentFilter intentFilter = new IntentFilter(); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(getClass().toString(), "Broadcast received"); } }, intentFilter);
最后的结果是接收者的onReceive()永远不会被调用。该服务是连续的,并且在通知操作发送广播时处于活动状态。由于广播的性质,我无法调试广播,所以我在这里有点受阻。
【问题讨论】:
-
我使用了一种机制,通知将广播发送到广播接收器“A”。此 BroadcastReceiver 'A' 将广播发送到内部(内部服务)BroadcastReceiver 'B'。在 B 的 onReceive() 中,我处理任务。这是我为另一个答案所做的sample github repo。 查看 Mike 的回答。
标签: android android-service android-notifications android-broadcastreceiver