Android通知操作PendingIntent.getBroadCast不起作用

时间:2015-05-28 20:20:57

标签: android broadcastreceiver manifest

我的Android通知操作按钮根本不起作用。我的服务中有以下代码,接收器在清单中注册 NOT ,因为它没有任何变化。我可以从另一个活动发送广播,但效果很好,但某处存在问题。

以下是与按钮

配对的PendingIntents
    Intent next = new Intent(getString(R.string.receiver_notification_media_change));
    next.setAction(NOTIFICATION_MEDIA_CHANGE_NEXT);
    PendingIntent pendingIntentNext = PendingIntent.getBroadcast(getApplicationContext(), 0, next, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent last = new Intent(getString(R.string.receiver_notification_media_change));
    last.setAction(NOTIFICATION_MEDIA_CHANGE_BACK);
    PendingIntent pendingIntentLast = PendingIntent.getBroadcast(getApplicationContext(), 0, last, PendingIntent.FLAG_UPDATE_CURRENT);

通知:

Notification.Builder mBuilder = new Notification.Builder(getApplicationContext())
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setSmallIcon(smallDrawableResId)
                .addAction(R.drawable.icon1, "as", pendingIntentLast)
                .addAction(R.drawable.icon2, "asdf", pendingIntentNext)
                .setContentTitle(title)
                .setContentText("title")
                .setLargeIcon(icon)
                .setContentIntent(pendingIntent) //to an activity. Works great
                .setOngoing(true)
                .setStyle(new Notification.MediaStyle()
                        .setShowActionsInCompactView(0, 1));

这是在下面的类中声明的BroadcastReceiver。

private BroadcastReceiver notificationMediaChanger = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();

        System.out.println("RECEIVEDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");

        if(action.equals(NOTIFICATION_MEDIA_CHANGE_NEXT))
            playNextSong();
        else if(action.equals(NOTIFICATION_MEDIA_CHANGE_BACK))
            playPreviousSong();
    }
};

OnCreate接收器已注册

        registerReceiver(notificationMediaChanger, new IntentFilter(getString(R.string.receiver_notification_media_change))); //LocalBroadcastManager.getInstance(getApplicationContext()) appears to be equivalent.

OnStop将被删除:

        unregisterReceiver(notificationMediaChanger);

1 个答案:

答案 0 :(得分:1)

您的操作字符串不匹配。

Intent next = new Intent(getString(R.string.receiver_notification_media_change));
next.setAction(NOTIFICATION_MEDIA_CHANGE_NEXT);

出于某种原因,您要将一个操作字符串替换为另一个操作字符串。我不知道为什么。

registerReceiver(notificationMediaChanger, new IntentFilter(getString(R.string.receiver_notification_media_change)));

在这里,您正在使用第一个操作字符串。您的Intent有第二个操作字符串。这些可能不一样。

此外:

    {li>

    LocalBroadcastManager未被PendingIntent

    使用
  • 除非您的活动在屏幕上时Notification仅在屏幕上(这将是奇怪的),否则您需要在清单中注册您的接收器