0

The FCM is working fine and notification came on device when app is in foreground state, and when tapped on notification, it is redirecting to my specified Activity, so it is working fine.

But my challenge is when the notification comes when app is in background state and when tapped, it redirects to Default Activity but I want to navigate to specified activity.

Here is MyFirebaseMessagingService class:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    private String title, messageBody;

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // [START_EXCLUDE]

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            if (remoteMessage.getData() != null && remoteMessage.getData().size() > 0) {
                title = remoteMessage.getData().get("title");
                if (TextUtils.isEmpty(title)) title = "Bocawest";
                messageBody = remoteMessage.getData().get("message");
            }
            handleNow();
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
        if (!TextUtils.isEmpty(messageBody))
            sendNotification(title, messageBody);
        //sendNotification(remoteMessage.getNotification().getBody());
        Intent intent = new Intent();
        intent.setAction("com.android.bocawest");
        sendBroadcast(intent);
    }
    // [END receive_message]

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String title, String messageBody) {
        PendingIntent pendingIntent;
        if (SharedPreference.getBoolean(getApplicationContext(), getApplicationContext().getResources().getString(R.string.sp_isLoginIN))) {
            Intent intent = new Intent(this, NotificationsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
        }


        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle(title)
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Bocawest",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }
}

Note : NotificationsActivity is my specified activity. HomeActivity is Default Activity

I know there are lot of similar questions but I haven't found anything specific to my usecase. Please Help me.

KENdi
  • 7,576
  • 2
  • 16
  • 31

3 Answers3

0

@Laxman parlapelly as per Firebase standered when your app receive notification in background and user tap on notification then it will open default activity only. If you want to open your specified activity then you have to pass through your default activity only.

For example in your case when user tap on notification it will open your Home activity and from oncreate method of HomeActivity you need to open NotificationsActivity(along with bundle incase needed)


When

Notification is tapped when app is in background then onCreate() method of HomeActivity will be called so with in that you can write code to open Notification Activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        animLay = findViewById(R.id.root_lay_la);
        Intent intent = new Intent(this,NotificationActivity.class);
        //intent.putExtra("KEY",getIntent().getStringExtra("data")); if u need to pass data
        startActivity(intent);
    }
Jaykishan Sewak
  • 822
  • 6
  • 13
  • Yeah i'm aware of this information but i'm not able to write the sort of code in my oncreate method of HomeActivity you need to open NotificationsActivity. Can you please give me that logic here – Laxman parlapelly Mar 13 '19 at 06:30
  • If you achieve this for notification tap when app is in background then check my edited answer – Jaykishan Sewak Mar 13 '19 at 06:42
  • How it will know it is came from background or not? i mean when app login it entered to Home Activity, but as per your above code in Home activity navigate to NotificationActivity directly without any logic? – Laxman parlapelly Mar 13 '19 at 06:57
  • How it will know it is came from background or not?--> \When your app is in front then you dont need to show notification in tray, also I suppose you have taken broad cast receiver in your respective activity which will trigger when notification arrive – Jaykishan Sewak Mar 13 '19 at 07:05
  • It means everytime app logins it directly goes to Notification Activity rather than Home Activity. – Laxman parlapelly Mar 13 '19 at 07:05
  • No i didn't use any broadcast listeners , and idk how to use with notifications can you please give me proper the sample – Laxman parlapelly Mar 13 '19 at 07:08
  • Actually in FCM we need to manage notification scenario in 2 cases 1 is when app is in front(via broadcast receiver, so no need to show notification in tray) and 2nd when app is in background (on create method of default activity will be called when notification tapped) For more detail see below example https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ – Jaykishan Sewak Mar 13 '19 at 07:12
0

if(SharedPreference.getBoolean(getApplicationContext(), getApplicationContext().getResources().getString(R.string.sp_isLoginIN))) write this logic in HomeActivity(in onCreate() before setContentView()) so every time user will be re-directed to HomeActivity and if the above condition satisfies the user will be redirected again to NotificationsActivity else will continue with HomeActivity

check - Navigate to different activities on notification click

Debu
  • 615
  • 7
  • 21
0

this works for me - just add the code below inside onMessageReceived()

Intent intent = new Intent(this, NotificationsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "111")
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.yhnn))
.setContentText(title)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setSound(sound)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

// notificationId is a unique int for each notification that you must define
notificationManager.notify(5, builder.build());
Ahmed Abdalla
  • 2,356
  • 2
  • 14
  • 27