0

My app receives FCM notification when the admin activate the user account from control panel, I want to to do some action from a method like a toast or deleting some data from my db when the user clicks the push notification.!

Is this possible?

here's the code inside FirebaseMessagingService class

public class CustomFirebaseMessagingService extends FirebaseMessagingService {

  public static String INTENT_FILTER = "INTENT_FILTER";

  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {

    try {

      if (remoteMessage.getNotification() != null) {

        Intent intent = new Intent(INTENT_FILTER);
        sendNotification(remoteMessage.getNotification().getBody(), intent);
        sendBroadcast(intent);
      }
    } catch (Exception ex) {
    }
    }


    private void sendNotification(String messageBody, Intent intent) {

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
        PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.logo)
        .setContentTitle("UPDATE")
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
  }
}
Alaa AbuZarifa
  • 1,171
  • 20
  • 39

5 Answers5

1

Yes you can do it just pass some integer value with intent using putextra for a reference in activity and in onCreate of activity class just check the if condition and make changes accordingly.

Michael
  • 41,989
  • 11
  • 82
  • 128
yash786
  • 1,151
  • 8
  • 18
1

you need to add a LocalBroadcastReceiver to listener to incoming notification inside you activity :

boolean isReceiverRegistered = false ; // to not create receiver twice

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBroadcastReceiver = new MyBroadcastReceiver();
    registerReceiver();
    //code
 }

private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case YOUR_ACTION:
                    handleIncomingAction(intent);
                    break;
            }
        }
    }

private void registerReceiver() {
        if (!isReceiverRegistered) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(YOU_ACTION);
            LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mBroadcastReceiver, intentFilter);
            isReceiverRegistered = true;
        }
    }
Oussema Aroua
  • 5,225
  • 1
  • 24
  • 44
  • I've tried this but nothing happend, what is `handleIncomingAction` really is in your code..!? are you sure this works for when clicking the notification when the app is background !? – Alaa AbuZarifa Jul 15 '17 at 07:15
1

The logic is to add an extra parameter in the intent and check for that in the launching activities onCreate method

private void sendNotification(String messageBody, Intent intent) {
// set extra param
intent.putExtra("is_from_notification", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
    PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.logo)
    .setContentTitle("UPDATE")
    .setContentText(messageBody)
    .setAutoCancel(true)
    .setSound(defaultSoundUri)
    .setContentIntent(pendingIntent);

NotificationManager notificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

In your activity

 @override
 protected void onCreate(Bundle savedInstance) {
     super.onCreate(savedInstance);

     if (getIntent().getBooleanExtra("is_from_notification", false)) {
        // TODO: do whatever you want in here
     } 
 }
Samuel Robert
  • 10,106
  • 7
  • 39
  • 60
1

For notifications to be clickable when your app is in the background, you need the click_action attribute in your notification payload. This is completely separate from the FirebaseMessagingService and other such classes, because these work when the app is in the foreground.

Please check this section of the Firebase docs.

Also, when you define the click_action attribute, you will also need a corresponding <action> attribute in the <intent-filter> of the activity that you wish to launch.

This video explains it in quite a detailed manner.

Though, please note that you can not set the click__action attribute if you're sending notifications from the Firebase Console. You can only do so if you send a notification from your own Admin server or using Firebase Cloud Functions.

Lastly, in the activity that is launched, you can set additional Data using the data attribute ( also shown in the same doc that I linked above ). And when you launch your app by clicking on a notification, you can obtain the notification data using getIntent(). Check out this answer for more details on how to do that.

It really is quite simple and elegant.

UPDATE

For example, if your notification payload has the following structure,

payload = {
  notification: {
    title: `You ordered a new product`,
    click_action : 'HANDLE_NOTIFICATION',

  },
  data : {
        product_id : 'ABC98292',
        type : `Clothes`,
        product_name : 'Cotton spring shirt'
    }
};

then, put the filter in the tag of the activity that you want to open when the notification is clicked. An example is the following :-

<intent-filter>
    <action android:name="HANDLE_NOTIFICATION" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
</intent-filter>

Then you can get the product_id from the notification using getIntent().getStringsExtra("product_id") and so on.

This way, you'll be opening the required activity, and can populate it with the relevant details obtained from your notification.

Rohan Stark
  • 2,346
  • 9
  • 16
  • I tried, but no luck with background, clicking only opens the activity but doesn't perform the condition of the passed data coming from the intent extra, it only apply when i click from foreground..!!? any help here..! I did what in the video exactly – Alaa AbuZarifa Jul 15 '17 at 07:57
  • @SamZar I don't know what exactly is not working in your code, so I made an edit to my answer that is generic and should cover your problem. Please check the edit, and get back if it still doesn't work. – Rohan Stark Jul 15 '17 at 08:36
  • It worked now :D , I didn't work before because I put the `value` of the data inside the `getStringExtra` , but once I replace it with the `key` it worked like a charm. Thanks a lot man! – Alaa AbuZarifa Jul 15 '17 at 19:31
1

I suggest you add a "flag" when you start an intent for an activity, to see from which activity the user comes from like this:

Intent intent = new Intent(NotificationActivity.this, SecondActivity.class);
intent.putExtra("call_from", "NotificationActivity");

and to get back:

String fromActivity = (String) getIntent().getExtras().get("call_from");
if(fromActivity.equals(NotificationActivity.class.getSimpleName())) {
    //call your method to delete what you want
}

Hope it helps.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193