在 FCM 中单击通知时打开特定活动 [英] Open specific Activity when notification clicked in FCM

查看:42
本文介绍了在 FCM 中单击通知时打开特定活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发需要在其中显示通知的应用.对于通知,我正在使用 FireBase Cloud Messaging (FCM).当应用程序在后台时,我可以收到通知.

但是当我点击通知时,它重定向到 home.java 页面.我希望它重定向到 Notification.java 页面.

所以,请告诉我如何在点击通知时指定活动.我正在使用两项服务:

1.)MyFirebaseMessagingService

2.)MyFirebaseInstanceIDService

这是 MyFirebaseMessagingService 类中 onMessageReceived() 方法的代码示例.

public class MyFirebaseMessagingService 扩展 FirebaseMessagingService {私有静态最终字符串 TAG = "FirebaseMessageService";位图位图;public void onMessageReceived(RemoteMessage remoteMessage) {Log.d(TAG, "From: " + remoteMessage.getFrom());//检查消息是否包含数据负载.如果 (remoteMessage.getData().size() > 0) {Log.d(TAG, "消息数据负载:" + remoteMessage.getData());}//检查消息是否包含通知负载.如果 (remoteMessage.getNotification() != null) {Log.d(TAG, "消息通知正文:" + remoteMessage.getNotification().getBody());}//此外,如果您打算根据收到的 FCM 生成自己的通知//消息,这里是应该启动的地方.请参阅下面的 sendNotification 方法.}/*** 创建并显示包含收到的 FCM 消息的简单通知.*/private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {Intent intent = new Intent(this, Notification.class);intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);intent.putExtra("通知", TrueOrFalse);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0/* 请求代码 */, intent,PendingIntent.FLAG_ONE_SHOT);Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this).setLargeIcon(image)/*通知图标图片*/.setContentTitle(messageBody).setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))/*带图像的通知*/.setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);通知管理器通知管理器 =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);NotificationManager.notify(0/* 通知 ID */, notificationBuilder.build());}/**从接收到的 URL 中获取位图图像* */公共位图 getBitmapfromUrl(String imageUrl) {尝试 {URL url = 新 URL(imageUrl);HttpURLConnection 连接 = (HttpURLConnection) url.openConnection();connection.setDoInput(true);连接.connect();InputStream 输入 = connection.getInputStream();位图 bitmap = BitmapFactory.decodeStream(input);返回位图;} 捕获(异常 e){//TODO 自动生成的 catch 块e.printStackTrace();返回空;}}

解决方案

使用 FCM,您可以发送两个 消息类型给客户:

1.通知消息:有时被认为是显示消息".

FCM 会自动代表客户端应用向最终用户设备显示消息.通知消息具有一组预定义的用户可见键.

2.数据消息:由客户端应用处理.

客户端应用程序负责处理数据消息.数据消息只有自定义键值对.

根据 FCM 文档在 Android 应用程序中接收消息 <块引用>

  • 当您的应用在后台时发送通知.在这种情况下,通知发送到设备的系统托盘.默认情况下,用户点按通知会打开应用启动器.
  • 具有通知和数据有效载荷的消息,包括后台和前台.在这种情况下,通知被传送到
    设备的系统托盘,数据有效载荷在额外内容中传递启动器 Activity 的意图.

在通知负载中设置click_action:

所以,如果你想处理后台到达的消息,你必须发送带有消息的click_action.

click_action 是一个 通知负载的参数

如果您想打开您的应用并执行特定操作,请在通知负载中设置 click_action 并将其映射到您要启动的 Activity 中的 Intent 过滤器.

例如,将 click_action 设置为 OPEN_ACTIVITY_1 以触发如下所示的意图过滤器:

<action android:name="OPEN_ACTIVITY_1"/><category android:name="android.intent.category.DEFAULT"/></意图过滤器>

FCM 负载如下所示:

<代码>{"to":"some_device_token",content_available":真,通知": {"title": "你好","body": "测试消息","click_action": "OPEN_ACTIVITY_1"},数据": {"额外":"果汁"}}

I am working on App in which I am required to show notification. For notification, i am using FireBase Cloud Messaging (FCM). I am able to get Notification when app is in background.

But when I click on notification, it redirect to home.java page. I want it to redirect to Notification.java page.

So,please tell me how to specify Activity in on Click of notification. I am using two services:

1.)MyFirebaseMessagingService

2.)MyFirebaseInstanceIDService

This is my code sample for onMessageReceived() method in MyFirebaseMessagingService class.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "FirebaseMessageService";
Bitmap bitmap;


public void onMessageReceived(RemoteMessage 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());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + 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.
}
/**
 * Create and show a simple notification containing the received FCM message.
 */

private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {
    Intent intent = new Intent(this, Notification.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    intent.putExtra("Notification", TrueOrFalse);
    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)
            .setLargeIcon(image)/*Notification icon image*/
            .setContentTitle(messageBody)
            .setStyle(new NotificationCompat.BigPictureStyle()
             .bigPicture(image))/*Notification with Image*/
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

/*
*To get a Bitmap image from the URL received
* */
public Bitmap getBitmapfromUrl(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;

    }
}

解决方案

With FCM, you can send two types of messages to clients:

1. Notification messages: sometimes thought of as "display messages."

FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user-visible keys.

2. Data messages: which are handled by the client app.

Client app is responsible for processing data messages. Data messages have only custom key-value pairs.

According to FCM document Receive Messages in an Android App

  • 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.

Set click_action in the notification payload:

So, if you want to process the messages arrived in the background, you have to send click_action with message.

click_action is a parameter of the notification payload

If you want to open your app and perform a specific action, set click_action in the notification payload and map it to an intent filter in the Activity you want to launch.

For example, set click_action to OPEN_ACTIVITY_1 to trigger an intent filter like the following:

<intent-filter>
  <action android:name="OPEN_ACTIVITY_1" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

FCM payload looks like below:

{
  "to":"some_device_token",
  "content_available": true,
  "notification": {
      "title": "hello",
      "body": "test message",
      "click_action": "OPEN_ACTIVITY_1"
  },
  "data": {
      "extra":"juice"
  }
}

这篇关于在 FCM 中单击通知时打开特定活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆