gpt4 book ai didi

未触发 Android 通知操作 (PendingIntent)

转载 作者:IT老高 更新时间:2023-10-28 23:20:56 27 4
gpt4 key购买 nike

我正在尝试在我的音乐播放器应用中添加通知操作项。当流启动时,应触发通知,并且应在通知中显示流的停止按钮。到目前为止,通知工作正常,我遇到了停止操作项的问题。以下是它在启动流的服务中的声明方式:

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);

现在在我的 Activity 的 onResume() 方法中,我使用 getIntent().getStringExtra() 检查“STOP”额外内容,但我通过 getIntent() 检索到的 Intent 没有设置额外内容:(

我还尝试检查是否发送广播(我有一个广播接收器正在工作以从服务通信到 Activity )

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 当前处于前台,则此方法有效。如果 Activity 在后台,停止按钮什么也不做:(

编辑:我的 Activity 中有 BroadcastReceiver 作为私有(private)类

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() 方法中删除取消注册,即使应用程序/Activity 不再处于前台,也会收到广播。但这是正确的方法吗?我认为我从网上的教程中得到了这个注册/取消注册的东西..

最佳答案

这是一个很晚的答案,但它可能对某人有所帮助:

您应该根据要运行的 Intent 选择正确类型的待处理 Intent 。以下是一些示例:

对于 Activity ,请使用以下:

Intent i = new Intent(this, YourActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

对于服务,请使用以下:

Intent i = new Intent(this, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);

对于广播接收器,请使用以下:

Intent i = new Intent(this, YourReciver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

如果需要,您可能需要更改请求代码和标志

关于未触发 Android 通知操作 (PendingIntent),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14841740/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com