Adrian Antal Adrian Antal - 20 days ago 7
Android Question

Notification has a different behaviour when the app is backgrounded

I've got a issue regarding notifications. I've got a service in my app that listens for messages from Firebase. Here is my code:

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// super.onMessageReceived(remoteMessage);

Log.d(TAG, "From: " + remoteMessage.getFrom());

// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}

displayNotification(remoteMessage.getNotification().getBody());
}


private void displayNotification(String message) {
if (message.contains("upgrade")) {
upgradeClient(message);
}

}

private void upgradeClient(String message) {

final String appPackageName = getString(R.string.app_package);
String url;
try {
url = "market://details?id=" + appPackageName;
} catch (final Exception e) {
url = "https://play.google.com/store/apps/details?id=" + appPackageName;
}

//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);


PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);


Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(message)
.setSmallIcon(R.drawable.ic_local_notification)
.setSound(notificationSound)
.setContentIntent(pendingIntent);

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());

}


}

When the app is foregrounded, the notification does exactly it should do (in this case, takes the user to the play store). The issue is when the app is backgrounded. Tapping on the notification while the app is backgrounded causes the app to start and user is not taken to play store. The upgradeClient() isn't even called! Thank you in advance!

Answer

please check out the message if you are getting in service

String message might be empty.

private void displayNotification(String message) {
 if (message.contains("upgrade")) {
        upgradeClient(message);
    }

}