0

I want to open a specific activity on notification click. But when the application is in the background, it doent open. I am not even passing the extras(ie, the data). I just want to open the activity and according to user logged in, i do some tasks. I even tried to open my default launcher activity on the notification click and send the user to notification activity from there. Here's the code of my default launcher activity: PS: I am sending the message from the firebase console, but it only has title and body.

(This is the function i call after doing my network task:)

        if (list.size()!=0){
            for (int i=0;i<list.size();i++){
                Users u=list.get(i);
                //Toast.makeText(LoginActivity.this, "Logging in...", Toast.LENGTH_SHORT).show();
                final Intent intent;
                Bundle b=new Bundle();
// This is the solution i found to check whether the extras has the package name or not! But it doesnt seem to work.
                if (Splashscreen.this.getIntent().getExtras() != null){
                    if (Splashscreen.this.getIntent().hasExtra("pushnotification") || Splashscreen.this.getIntent().getExtras().containsKey("com.tracecost")){
                        System.out.println("From notification----------->");
                        intent=new Intent(Splashscreen.this,NotificationReceivedActivity.class);
                        b.putString("pushnotification","yes");
                    }
                    else{
                        intent=new Intent(Splashscreen.this, ProjectSelection.class);
                    }
                }
                else{
                    intent=new Intent(Splashscreen.this, ProjectSelection.class);
                }

                b.putSerializable("user",u);
                b.putSerializable("projectlist",plist);
                intent.putExtras(b);
                //logginDialog.dismiss();
                Handler handler=new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(intent);
                        finish();
                    }
                },3500);

            }
        }
    }```
Adhish Mathur
  • 23
  • 1
  • 4

3 Answers3

0

This works only when app is in foreground. When app is in background, it considers only Notification data from payload and ignores data part. This leads to no control to the app as notification type messages will be handled by system alone. Only option is to use an external server of your own or send from a rest client.

Aditi
  • 389
  • 4
  • 13
0

You can redirect from the Firebase notification when the app is in Foreground or Background as far as you send in data.

I will provide you an example of how to redirect between activities based on key received from the notification, firebase magically handles the rest.

P.S: If you want to handle the activity that is already open in the background, use taskAffinity to play around.

Handle the Firebase data through FirebaseMessagingService:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    System.out.println("MESSAGE BODY :" + remoteMessage.toString());
    if (remoteMessage.getData().size() > 0) {
        //getting the title and the body
        String redirect;
        String title = remoteMessage.getData().get("message_title");
        String body = remoteMessage.getData().get("message_body");
        redirect = remoteMessage.getData().get("redirect");
        String event_id = remoteMessage.getData().get("event_id");
        System.out.println("PUSH MESSAGE = " + remoteMessage.toString());
        JSONObject jsonData = new JSONObject(remoteMessage.getData());
        System.out.println("RESPONSE :" + jsonData.toString());
        if (redirect != null) {
            sendNotification(title, body, event_id, redirect);
        } else {
            redirect = "";
            sendNotification(title, body, event_id, redirect);

        }
    }
}


private void sendNotification(String title, String body, String event_id, String redirect) {
    Intent backIntent = new Intent();
    PendingIntent pendingIntent;
    if (redirect.contentEquals("CHAT")) {
        backIntent = new Intent(MyFirebaseMessagingService.this, ChatScreen.class);
        backIntent.putExtra("item_id", event_id);
    }
    if (redirect.contentEquals("EVENT") || redirect.contentEquals("INVITATION")) {
        backIntent = new Intent(MyFirebaseMessagingService.this, Event_Summary.class);
        backIntent.putExtra("event_id", event_id);
    }
    backIntent.putExtra("MODE", "FIRE_NOTIFICATION");
    backIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(backIntent);
    pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
}
sanjeev
  • 1,664
  • 19
  • 35
0

Firebase console sends only Notification messages(more info here Firebase) but you can use your own server or Firebase API to send Data messages.

Data messages work for Foreground as well as Background app states.

A sample curl to trigger a push notification will look like:

curl -X POST \ https://fcm.googleapis.com/fcm/send \ -H 'Authorization: key=YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -H 'cache-control: no-cache' \ -d '{ "data": { "title":"TITLE", "message":"Notification Content", "custom_key": "custom_value" }, "registration_ids": ["DEVICE_PUSH_TOKEN"] }'

You can pass your custom key-value pair as well and get them in onMessageReceived method.

Note: In this approach, you have to create the notification which will be visible in the system tray. Sample code will look like:

// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, AlertDetails.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that will fire when the user taps the notification
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);

You can find more on this in the official documentation

Hope this helps!

amit srivastava
  • 743
  • 6
  • 25