I've implemented all the mechanism to send a push notification.
My app responds to the clicking the push message is not fixed. That is, when the user click the message, the status of my app (background or foreground) decides next step.
As you know, the method onMessageReceived()
is called when the push message is received (even when the screen is off)
So, I want to insert some code that checks if the app is foreground or background in onMessageReceived()
.
Here's my codes below:
public void onMessageReceived(RemoteMessage remoteMessage) {
String body = remoteMessage.getData().get("body");
title = remoteMessage.getData().get("title");
sendNotification(body);
if(remoteMessage.getData().size() > 0){
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, Activity_CreateAccount.class);
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.intro_logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_MAX);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PowerManager pm = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock =
pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "");
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
wakeLock.acquire();
if(wakeLock!=null){
wakeLock.release();
wakeLock = null;
}
}