Send broadcast by notification click

I have an application that is basically web browsing and GCM. I want to achieve the following: if the user is in the application and receives a notification when he clicks on the notification, I want the webview to download the URL specified in the notification.

I am trying to accomplish this using a broadcast receiver, but it does not work.

I dynamically register the receiver in 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); } 

And in the GCM receiver, I use 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); 

I do not understand why onReceive in the MainActivity class is not called. The message "received notification" is not displayed. Could you help me? Thanks:)

+6
source share
1 answer

I can’t find a reason now, but there is a security reason. Recent versions of Android do not allow you to start a listener from a "kind" of a remote process without explicit instructions.

The intent you are broadcasting MUST be explicit for it to work. Explicit means that you must explicitly call the component that will handle the intent (the receiver). Therefore, this recipient must be declared in its own class and in the manifest as <receiver> .

Follow the example of this guy in the section " Explicit Broadcast Intents http://codetheory.in/android-broadcast-receivers/ and everything will be ready.

+6
source

All Articles