【问题标题】:Send broadcast on notification click点击通知发送广播
【发布时间】:2015-08-11 09:00:26
【问题描述】:

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

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

我在MainActivity中动态注册receiver:

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 类中的 onReceive 没有被调用。不显示消息“收到通知”。 你能帮助我吗?谢谢你:)

【问题讨论】:

    标签: android push-notification broadcastreceiver google-cloud-messaging android-pendingintent


    【解决方案1】:

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

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

    Explicit Broadcast Intentshttp://codetheory.in/android-broadcast-receivers/部分中按照这个人的例子 你会完成的。

    【讨论】:

    • 是的,它现在可以在清单中定义接收器时工作。谢谢 :) 为了实现我的目标,我需要在 MainActivity 中使用另一个接收器,我在其中加载 url。对它的广播是从第一个接收器(我在清单中定义的那个)发送的。它现在有效,但我有点不喜欢这种方法。在我看来,这是一种不好的做法......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2011-05-19
    相关资源
    最近更新 更多