Maulana Firdaus
Maulana Firdaus

Reputation: 135

How to automatically open app when receive push notification?

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);
}
}

Upvotes: 9

Views: 11674

Answers (4)

Sidharth Priyadarshi
Sidharth Priyadarshi

Reputation: 31

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 :)

Upvotes: 0

user6693721
user6693721

Reputation:

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)

Upvotes: 0

Randheer
Randheer

Reputation: 1084

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.

Upvotes: 4

theanilpaudel
theanilpaudel

Reputation: 3478

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 );

Upvotes: 1

Related Questions