2

我正在构建一个应用程序,该应用程序在调用 BroadcastReceiver 时显示带有两个选项“Dim”和“Full”的通知。每个按钮都广播一个动作。

到目前为止,一切皆有可能,对吧?

问题是通知上显示的按钮不会响应点击,但整个通知会响应(如果我单击图标或文本而不是按钮)。

我有这个功能来构建通知:

private Notification buildReleaseNotification(NotificationManager nManager, Context context) {

    Notification.Builder builder = new Builder(context);
    builder.addAction(R.drawable.rate_star_big_half_holo_dark, "Dim", buildPendingIntent(context, DIM));
    builder.addAction(R.drawable.rate_star_big_on_holo_dark, "Full", buildPendingIntent(context, FULL));

    builder.setContentTitle("Car notification");
    builder.setContentText("Freed");
    builder.setSmallIcon(R.drawable.ic_launcher);
    builder.setOngoing(true);

    Notification notification = builder.build();
    return notification;
}

并在接收广播时调用它:

    public void onReceive(Context context, Intent intent) {

    NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification noty = null;
    noty = buildReleaseNotification(context);
    startService(context, RELEASE);

    if (noty != null) {
        nManager.notify(ChangeLockService.GLOBAL_TAG, ID, noty);
    }

}

- - - 编辑

刚刚注意到以下函数返回 null... 那么,如何构建待处理的意图来执行广播?

private PendingIntent buildPendingIntent(Context context, String action) {

        Intent i = new Intent(action);
        PendingIntent pi = PendingIntent.getBroadcast(context, ID, i, Intent.FLAG_RECEIVER_REPLACE_PENDING);
        return pi;
    }
4

1 回答 1

1

通过创建意图时

PendingIntent pi = PendingIntent.getBroadcast(context, ID, i, Intent.FLAG_RECEIVER_REPLACE_PENDING);

导致它返回null。根据文档,我知道该标志Intent.FLAG_RECEIVER_REPLACE_PENDING将替换该按钮已经存在的任何未决意图。如果我不发送任何标志,那么一切正常:

PendingIntent pi = PendingIntent.getBroadcast(context, ID, i, 0);
于 2013-01-21T12:27:25.657 回答