单击通知发送广播

Send broadcast on notification click

我有一个基本上是 webview 和 GCM 通知的应用程序。我想实现以下目标:如果用户在应用程序中并收到通知,当他单击通知时我希望 webview 加载通知中提供的 url。

我正在尝试使用广播接收器来完成此操作,但它不起作用。

我在MainActivity中动态注册接收者:

private void registerNotificationReceiver() {
        final IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_LOAD_URL_FROM_NOTIFICATION);
        Log.i(TAG, "registerNotificationReceiver()");
        this.receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "notification received");

            }
        };

        super.registerReceiver(this.receiver, filter);
    }

我在 GCM 监听器中使用 PendingIntent.getBroadast():

final Intent broadcastIntent = new Intent(MainActivity.ACTION_LOAD_URL_FROM_NOTIFICATION);
        PendingIntent intent = PendingIntent.getBroadcast(getApplicationContext(), 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        notificationBuilder.setContentIntent(intent);

        notification = notificationBuilder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, notification);

我不明白为什么不调用 MainActivity class 中的 onReceive。消息 "notification received" 未显示。 你能帮助我吗?谢谢:)

我现在找不到原因,但出于安全考虑。最新的 Android 版本不允许您在不明确的情况下从“某种”远程进程触发侦听器。

您广播的意图必须明确才能生效。显式意味着您必须显式调用将处理意图的组件(接收者)。所以这个接收器必须在它自己的 class 中声明,并且在清单中声明为 <receiver>.

Explicit Broadcast Intents http://codetheory.in/android-broadcast-receivers/ 部分按照这个人的示例进行操作 愿你的旨意实现。