点击通知后发送广播

9
我有一个应用程序,基本上是一个Web视图和GCM通知。我想实现以下内容:如果用户在应用程序中并收到通知,则当他单击通知时,我希望Web视图加载通知中提供的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类中的onReceive方法没有被调用。消息“notification received”没有显示。 你能帮忙吗?谢谢 :)
1个回答

8

我现在无法找到原因,但有一个安全原因。最新的Android版本不允许您在“类似于”远程进程中触发监听器而不显式执行。

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

在“明确广播意图”部分中遵循这个人的示例http://codetheory.in/android-broadcast-receivers/,就可以完成了。


1
是的,现在当接收器在清单中定义时它可以工作了。谢谢 :) 为了实现我的目标,我需要在MainActivity中使用另一个接收器,在这里我加载URL。来自第一个接收器(我在清单中定义的那个)的广播被发送到它。现在它可以工作了,但我不太喜欢这种方法。在我看来,这似乎是一种不好的做法... - dephinera

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接