Search code examples
androidnotificationsbroadcastreceivernotificationmanager

Android: How to react to notification touch events?


I'm displaying a notification via the NotificationManager from a BroadcastReceiver, but if the user touches the notification, nothing happens. If I create notifications from a view, the containing activity is brought to front when touching the notification.

How can I display a specific activity/view or otherwise react to the user touching a notification?


Solution

  • when you receive the broadcast message from the NotificationManager you have to create a new PendingIntent which will be fired when user touch in the proper notification. Now, that PendingIntent must have an inner Intent wich will have an action to perform, like start an activity.

    on your "onReceive" method in the BroadcastReceiver call to an auxiliary method, like "showProximityAlertNotification"

    @Override
            public void onReceive(Context context, Intent intent) {
    showProximityAlertNotification();
    }
    
    
    //now when the user touch the notification on the notification bar, an activity named //"ItemListActivity" will be launched. You can put an IntentFilter, a Category, an Action 
    //to perform any different operations within your activity
    private void showProximityAlertNotification(  ){
    
            String titulo = getString(R.string.notification_proximity_alerts_fired_title);
            String tickerText = getString(R.string.notification_proximity_alerts_fired_ticker);
            String contextText = getString(R.string.notification_proximity_alerts_fired_content);
            int icon = R.drawable.wk_logo;
            long when = System.currentTimeMillis();
    
            Notification notification = new Notification(icon, tickerText, when);
    
            //define the actions to perform when user touch the notification
            Intent launchApp = new Intent(getApplicationContext(), ItemListActivity.class);
            launchApp.putExtra("com.xxxxxxx.xxxxxxxxx.bean.Item", "anyObjectYouWant");
            launchApp.setAction( "VIEW_DETAILS_PROPERTY" );
            PendingIntent launchNotification = PendingIntent.getActivity(getApplicationContext(), 0, launchApp, 0);
            notification.setLatestEventInfo(getApplicationContext(), titulo, contextText, launchNotification);
    
            notificationManager.notify(NOTIFICATION_ID_PROXIMITY_ALERT_FIRED, notification);
        }
    

    if you are executing the newly launched activity and want to cancel the launched notification just do this:

    String notManagerName = Context.NOTIFICATION_SERVICE;
                    NotificationManager notificationManager = (NotificationManager) getSystemService(notManagerName);
                    notificationManager.cancel(ProximityAlerts.NOTIFICATION_ID_PROXIMITY_ALERT_FIRED);
    

    cheers