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 M
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:
action=MAIN and category=LAUNCHERPackageManager from the current context using context.getPackageManagerpackageManager.queryIntentActivity(<intent>, 0) where intent has category=LAUNCHER, action=MAIN or packageManager.resolveActivity(<intent>, 0) to get the first activity with main/launcherActivityInfo you're interested inActivityInfo, get the packageName and namecategory=LAUNCHER, action=MAIN, componentName = new ComponentName(packageName, name) and setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)context.startActivity(newIntent)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.
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 );