9

I want to automatically open app when receive push notification. I've tried but it still does not work as I expected. This code below is work when the app is active or in MainActivity, but it's not work when the app in the background or just show notification on tray. Did I miss something?

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getNotification() != null) {
        if (PreferencesUtil.getInstance(this).isLoggedIn()) {
            sendNotification(remoteMessage.getData().get("order_id"));
        }
    }

}


public void sendNotification(String messageBody) {
    NotificationManager notificationManager = null;
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder notificationBuilder;

    notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Notification")
            .setSmallIcon(R.mipmap.icon_notif)
            .setContentText(messageBody)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_LIGHTS );
    //add sound
    try {
        Uri sound = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.siren);
        Ringtone ringtone = RingtoneManager.getRingtone(this, sound);
        ringtone.play();
        notificationBuilder.setSound(sound);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //vibrate
    long[] v = {1000, 1000, 1000, 1000, 1000};
    notificationBuilder.setVibrate(v);
    notificationManager.notify(0, notificationBuilder.build());

    Intent i = new Intent(this, NotificationActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}
}
2
  • Do you want to see NotificationActivity when app is background, don't you? Commented May 16, 2018 at 10:47
  • yes, I want open NotificationActivity from background when receive push notification. Commented May 16, 2018 at 11:43

4 Answers 4

4

This is something need to handle from backend,

Here is a sample payload you are using right now, { "message":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification":{ "title":"Portugal vs. Denmark", "body":"great match!" } } }

Which will only give you control to manipulate and do some action when your app will be in foreground otherwise just raise notification.

In details you can check here.

Now, To always get control over your notification, you need payload like following,

{ "message":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "data":{ "Nick" : "Mario", "body" : "great match!", "Room" : "PortugalVSDenmark" } } }

The difference is you need to send data payload instead of notification poayload from backend.

Sign up to request clarification or add additional context in comments.

3 Comments

here is my notification data I set it from firebase console { "message":{ "token":"...", "data":{ "order_id" : "123", "first" : "Maulana", "last" : "Firdaus" } } }
Here is sample from firebase doc, { "message":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification":{ "title":"Portugal vs. Denmark", "body":"great match!" }, "data" : { "Nick" : "Mario", "Room" : "PortugalVSDenmark" } } }
If you are sending above data from firebase console you should debug whether you are receiving it in On onMessageReceived . Payload is looking fine to me.
1
int requestID = (int) System.currentTimeMillis();
Intent notificationIntent = new Intent(getApplicationContext(), NotificationActivity.class);

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

PendingIntent contentIntent = PendingIntent.getActivity(this, requestID,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

And add PendingIntent like this

notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Notification")
            .setSmallIcon(R.mipmap.icon_notif)
            .setContentText(messageBody)
            .setContentIntent(contentIntent);
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_LIGHTS );

1 Comment

Thanks, but I want to open app automatically without click or touch the notification.
0

Firstly, the concept of "application" in Android is slightly an extended one.

An application - technically a process - can have multiple activities, services, content providers and/or broadcast listeners. If at least one of them is running, the application is up and running (the process).

So, what you have to identify is how do you want to "start the application".

Ok... here's what you can try out:

  1. Create an intent with action=MAIN and category=LAUNCHER
  2. Get the PackageManager from the current context using context.getPackageManager
  3. packageManager.queryIntentActivity(<intent>, 0) where intent has category=LAUNCHER, action=MAIN or packageManager.resolveActivity(<intent>, 0) to get the first activity with main/launcher
  4. Get the ActivityInfo you're interested in
  5. From the ActivityInfo, get the packageName and name
  6. Finally, create another intent with with category=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name) and setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
  7. Finally, context.startActivity(newIntent)

Comments

0

I going to give you complete example for this type of situation. Where i'll send a msg to a number (whether my app is completely killed or is in background or is in foreground ) according to received data payload

{
"registration_ids":["cMcyU3CaSlCkjPh8C0qo-n:APA91bFwOhNAwYp5vEEztv_yD_vo1fWt7TsiKZQ8ZvIWx8CUKZa8CNVLAalxmV0FK-zwYgZnwdAnnVaHjUHYpqC89raTLXxAfUWc2wZu94QWCnv14zW4b_DwDUMBpDo3ybP3qf5Y5KM2"],
"data": {
    "number": "6299018534",
    "msg": "Hii i am sidharth"
}

}

When you send this type data notification from your server then this will receive in onMessageReceived whether your app is in background or foreground. So, Android code looks like this:

 public class NotificationServices extends FirebaseMessagingService {


 @Override
 public void onMessageReceived(@NonNull RemoteMessage message) {
    super.onMessageReceived(message);

    if(message.getData().size()>0){
        String number = null,msg = null;
        if(message.getData().get("number") !=null){
            number= message.getData().get("number");

        }
        if(message.getData().get("msg") !=null){
            msg= message.getData().get("msg");

        }
        sendSms(number,msg);



    }

}

@Override
public void onNewToken(@NonNull String token) {
    super.onNewToken(token);
}

private void sendSms(String phone,String sms){
    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(phone,null,sms,null,null);

}
}

Happy coding :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.