Search code examples
androidandroid-intentnotificationsbroadcastreceiverandroid-pendingintent

Receive signal after notification clicked


I fire a notification from MainActivity class. When user click the notification, i'd like to return back to MainActivity class and execute a method. I'd also like to know which notification is clicked (Assuming that i fire multiple notifications with different id). Here what i did and it didn't work

Inside MainActivity.class:

private void showNotification(String title, String message, int id) {
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(message);

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.setAction("mAction");
    PendingIntent resultPendingIntent = PendingIntent.getBroadcast(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(id, mBuilder.build());
}

Same inside MainActivity.class i create a BroadcastReceiver class but it never got called:

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if(action.equals("mAction")) {
                //execute my method here
        }
    }        

}

I did add MyBroadcastReceiver.class receiver in AndroidManifest.xml:

<receiver android:name=".MyBroadcastReceiver" > </receiver>

Solution

  • As @Varun suggestion, here how to solve my problem.

    In showNotification i replace .setAction to .putExtra and change .getBroadcast to .getActivity:

        Intent resultIntent = new Intent(this, MainActivity.class);           
        resultIntent.putExtra("mAction", id); // put id here you know which notification clicked
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); // change getBroadcast to getActivity
    

    No longer need MyBroadcastReceiver class instead i add some lines in onCreate() to get intent result:

        if(getIntent().hasExtra("mAction")){
            Bundle extra = getIntent().getExtras();
            int id = extra.getInt("mAction");
            if(id == 1) {
                //do stuff
            }
        }