通知点击发送广播

def*_*era 6 android broadcastreceiver push-notification android-pendingintent google-cloud-messaging

我有一个基本上是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);
    }
Run Code Online (Sandbox Code Playgroud)

在GCM Listener中我正在使用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);
Run Code Online (Sandbox Code Playgroud)

我不明白为什么不调用MainActivity类中的onReceive.不显示消息"收到通知".你能帮助我吗?谢谢 :)

edu*_*ayo 6

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

您广播的意图必须明确才能起作用。显式意味着您必须显式调用将处理该意图的组件(接收方)。因此,此接收者必须在其自己的类中和在清单中声明为<receiver>

Explicit Broadcast Intents http://codetheory.in/android-broadcast-receivers/部分中遵循此人的示例,您 将完成。