简体   繁体   中英

How can I handle a notification from Firebase when it arrives and I have the app open?

I want to update activities when a notification arrives but I can't get the current Activity where the user is. I'm working with FirebaseMessagingService.

Code

You have to consider that when receiving the notification the application may be in the foreground or background and that depending on it the handling is different.

You cannot get the activity from that service, instead, you have to tell it which activity appears in the foreground when the notification is clicked and get the "extras" data.

For example using a configuration like this in the notification server (nodejs):

var message = {
        notification: {
            title: title,
            body: text
        },
        data: {
            title: title,
            body: text,
            latitude: latitude,
            longitude: longitude,
            name: name
        },
        android: {
            priority: 'high',
            notification: {
                sound: 'default',
                clickAction: '.PetNotificationActivity'
            },
        },
        apns: {
            payload: {
                aps: {
                    sound: 'default'
                },
            },
        },
        tokens: registrationTokens
    };

In that example, PetNotificationActivity is the activity that I want to bring to the foreground when opening the notification.

And, In the PetNotificationActivity something like this ( for background/closed app case ):

public class PetNotificationActivity extends AppCompatActivity {

    ....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pet_notification);
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            String latitudeValue = bundle.getString("latitude");
            String longitudeValue = bundle.getString("longitude");
            String nameValue = bundle.getString("name");
            ...
        }
    }

And in the service something like this ( for foreground case ):

public class PetNotificationService extends FirebaseMessagingService {

    ...

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

        if (remoteMessage.getData().size() > 0) {
            sendNotification(remoteMessage);
        }
    }

    private void sendNotification(RemoteMessage remoteMessage) {
        String title = remoteMessage.getData().get("title");
        String messageBody = remoteMessage.getData().get("body");
        String latitude = remoteMessage.getData().get("latitude");
        String longitude = remoteMessage.getData().get("longitude");
        String name = remoteMessage.getData().get("name");

        Intent intent = new Intent(this, PetNotificationActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("latitude", latitude);
        intent.putExtra("longitude", longitude);
        intent.putExtra("name", name);

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

        ...

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        ...
                        .setContentIntent(pendingIntent);

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        notificationManager.notify(0, notificationBuilder.build());
    }
}

FCM documentation at Handling messages

A better approach would be for your interested activities to register a broadcast receiver and for your service to send a broadcast when a message arrives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM