Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open activity on firebase notification received in foreground

When my application is open and I receive a notification I want to be able to open the activity associated immediately without the need of the user to tap on the notification.

This question is very similar: Open app on firebase notification received (FCM)

But it opens the app when it is in background, I need to do it when my app is in foreground.

From the firebase documentation:

Notifications delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default. Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

This is my implmentation of onMessageReceived

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

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

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

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param remoteMessage FCM message message received.
     */
    private void sendNotification(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, MyActivity.class);

        Map<String, String> hmap ;
        hmap = remoteMessage.getData();
        hmap.get("data_info");
        intent.putExtra("data_info", hmap.get("data_info"));
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);


        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

    }

I am able to get the notification correctly but the activity only starts once I tap the notification on the system tray.

Is there a way to start the activity without tapping the notification while in foreground?

The method onMessageReceived() from the class MyFirebaseMessagingService that extends FirebaseMessagingService is getting called correctly while in foreground, but the activity is not getting started. I have also tried with the flag FLAG_ACTIVITY_NEW_TASK also with no luck. Thanks in advance.

like image 702
bankode Avatar asked Sep 06 '16 22:09

bankode


People also ask

How do I handle the Firebase notification when an app is in foreground?

Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded apps to receive notification messages or data messages, you'll need to write code to handle the onMessageReceived callback.

How do I show notifications on foreground flutter?

Notification messages which arrive while the application is in the foreground will not display a visible notification by default, on both Android and iOS. It is, however, possible to override this behavior: On Android, you must create a "High Priority" notification channel.


2 Answers

(kotlin) use this code inside onMessageReceived if you want to check is app either foreground or background

    var foreground = false

    try {
        foreground = ForegroundCheckTask().execute(this).get()
    } catch (e: InterruptedException) {
        e.printStackTrace()
    } catch (e: ExecutionException) {
        e.printStackTrace()
    }

then use the "foreground" variable to do action as you needed

 if (foregroud) { //app in foreground
            intent = Intent(this, ChatAdminActivity::class.java)
            intent.putExtra("intent_backchat", 1)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            pendingIntent = PendingIntent.getActivity(this, Integer.valueOf(random) /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT)
            startActivity(intent)      // to directly open activity if app is foreground
        } else { //app in background
            intent = Intent(this, ChatAdminActivity::class.java)
            intent.putExtra("intent_backchat", 1)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
            pendingIntent = PendingIntent.getActivity(this, Integer.valueOf(random) /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }
.....

hope its helping..

and you can see my full FCMService code

like image 99
fayerketto Avatar answered Oct 07 '22 03:10

fayerketto


What i usually do is send data message and create a intent from it.

public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    Log.d(TAG, "onMessageReceived: called");

    Log.d(TAG, "onMessageReceived: Message received from: " + remoteMessage.getFrom());

    if (remoteMessage.getNotification() != null) {
        String title = remoteMessage.getNotification().getTitle();
        String body = remoteMessage.getNotification().getBody();
        Log.d(TAG, "onMessageReceived: "+title+" "+body);

        Notification notification = new NotificationCompat.Builder(this, FCM_CHANNEL_ID)
                .setSmallIcon(R.mipmap.ridersquare)
                        .setContentTitle(title)
                .setContentText(body)
                .setColor(Color.BLUE)
                .setSubText("KKKK")
                .build();

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(FCM_CHANNEL_ID, "Default channel", NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
        }
        manager.notify(1002, notification);
    }

    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "onMessageReceived: Data: " + remoteMessage.getData().toString());
        if (remoteMessage.getData().toString().length()>0){
            Notification notification = new NotificationCompat.Builder(this, FCM_CHANNEL_ID)
                    .setSmallIcon(R.mipmap.ridersquare)
                    .setContentTitle("New Order")
                    .setContentText("New order received from"+remoteMessage.getData().get("restaurant_name"))
                    .setSound(App.soundUri)
                    .setLights(Color.RED, 3000, 3000)
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setVibrate(new long[]{0,1000, 500, 1000})
                    .build();

            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(FCM_CHANNEL_ID, "Default channel", NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
            }
            manager.notify(50, notification);
            Intent intent=new Intent(getApplicationContext(), NewOrderNoti.class);
            intent.putExtra("username",remoteMessage.getData().get("username"));
            startActivity(intent);

        }


    }

This basically creates a notification and calls a intent to open new activity

like image 29
junaid ahsan Avatar answered Oct 07 '22 03:10

junaid ahsan