【发布时间】:2013-01-28 07:14:42
【问题描述】:
我正在尝试在我的音乐播放器应用中添加通知操作项。当流启动时,应触发通知,并且应在通知中显示流的停止按钮。到目前为止,通知工作正常,我遇到了停止操作项的问题。以下是它在启动流的服务中的声明方式:
Intent stopIntent = new Intent(this, MusicPlayerNew.class);
stopIntent.putExtra("STOP", "STOP");
PendingIntent stopPendingIntent = PendingIntent.getActivity(this, 0,
stopIntent, PendingIntent.FLAG_UPDATE_CURRENT, null);
mBuilder.addAction(R.drawable.ic_stat_stop, "Stop", stopPendingIntent);
现在在我的活动的 onResume() 方法中,我使用 getIntent().getStringExtra() 检查“STOP”额外内容,但我通过 getIntent() 检索到的意图没有设置额外内容:(
我还尝试检查是否发送广播(我有一个广播接收器,用于从服务到活动进行通信)
Intent stopIntent2 = new Intent(MusicPlayerNew.STOP_MEDIAPLAYER);
PendingIntent stopPendingIntent2 = PendingIntent.getBroadcast(this, 0,
stopIntent2, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.ic_stat_stop, "Stop", stopPendingIntent2);
现在,如果活动当前处于前台,则此方法有效。如果活动在后台,停止按钮什么也不做:(
编辑: 我的 Activity 中有 BroadcastReceiver 作为私有类
private class DataUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
..
}}
在 onResume() 中为这个接收者注册我的应用程序:
intentFilter = new IntentFilter(STOP_MEDIAPLAYER);
registerReceiver(dataUpdateReceiver, intentFilter);
onPause()
unregisterReceiver(dataUpdateReceiver);
现在,如果我从 onPause() 方法中删除取消注册,即使应用程序/活动不再处于前台,也会收到广播。但这是正确的方法吗?我认为我从网上的教程中得到了这个注册/取消注册的东西..
【问题讨论】:
-
我在 KitKat 上有同样的问题。我有两个动作,第一个叫罚款,第二个根本不叫。你找到解决这个问题的方法了吗?
-
好的,我找到了解决方案。看看我的答案底部。
标签: android android-intent android-activity android-notifications android-pendingintent