首页 文章

如何在Firebase中的后台应用时处理通知

提问于
浏览
297

这是我的清单

<service android:name=".fcm.PshycoFirebaseMessagingServices">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name=".fcm.PshycoFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

当应用程序处于后台并且通知到达时,默认通知会出现,并且不会运行我的 onMessageReceived 代码 .

这是我的 onMessageReceived 代码 . 如果我的应用程序在前台运行,而不是在后台应用程序时,则调用此方法 . 如何在应用程序处于后台时运行此代码?

// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO(developer): Handle FCM messages here.
    // If the application is in the foreground handle both data and notification messages here.
    // 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.
    data = remoteMessage.getData();
    String title = remoteMessage.getNotification().getTitle();
    String message = remoteMessage.getNotification().getBody();
    String imageUrl = (String) data.get("image");
    String action = (String) data.get("action");
    Log.i(TAG, "onMessageReceived: title : "+title);
    Log.i(TAG, "onMessageReceived: message : "+message);
    Log.i(TAG, "onMessageReceived: imageUrl : "+imageUrl);
    Log.i(TAG, "onMessageReceived: action : "+action);

    if (imageUrl == null) {
        sendNotification(title,message,action);
    } else {
        new BigPictureNotification(this,title,message,imageUrl,action);
    }
}
// [END receive_message]

21 回答

  • 8

    要在后台捕获消息,您需要使用 BroadcastReceiver

    public class FirebaseDataReceiver extends WakefulBroadcastReceiver {
    
        private final String TAG = "FirebaseDataReceiver";
    
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "I'm in!!!");
            Bundle dataBundle = intent.getBundleExtra("data");
            Log.d(TAG, dataBundle.toString());
        }
    }
    

    并将其添加到您的清单:

    <receiver
          android:name="MY_PACKAGE_NAME.FirebaseDataReceiver"
          android:exported="true"
          android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
    </receiver>
    
  • 2

    我遇到了同样的问题并重新编译了firebase库,并阻止它在应用程序处于后台时发送通知

    *图书馆https://github.com/erdalceylan/com-google-firebase-messaging

    dependencies {
            compile 'com.google.firebase:firebase-core:11.2.0'
            compile 'com.github.erdalceylan:com-google-firebase-messaging:v1-11.2.0'
        }
    
    @WorkerThread
    public void onMessageReceived(RemoteMessage var1) {
      //your app is in background or foreground all time calling
    }
    

    希望有所帮助祝好运

  • 19
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    
    }
    

    每次只有当app在forground中时才调用它

    有一个覆盖方法每次调用此方法,无论应用程序在前台或后台还是已杀死,但此方法适用于此firebase api版本

    这是你必须从gradle导入的版本

    compile 'com.google.firebase:firebase-messaging:10.2.1'
    

    这是方法

    @Override
    public void handleIntent(Intent intent) {
        super.handleIntent(intent);
    
        // you can get ur data here 
        //intent.getExtras().get("your_data_key") 
    
    
    }
    

    使用以前的firebase api这个方法不存在,所以在这种情况下,当app在后台时,fire base handle本身....现在你有这个方法你想做什么...你可以在这个方法中做到这一点.. ...

    如果你使用的是以前的版本而不是默认活动将在那种情况下启动,你可以获得相同的数据

    if(getIntent().getExtras() != null && getIntent().getExtras().get("your_data_key") != null) {
    String strNotificaiton = getIntent().getExtras().get("your_data_key").toString();
    

    //做你想做的事......

    通常这是我们收到通知的服务器的结构

    {
        "notification": {
            "body": "Cool offers. Get them before expiring!",
            "title": "Flat 80% discount",
            "icon": "appicon",
            "click_action": "activity name" //optional if required.....
        },
        "data": {
            "product_id": 11,
            "product_details": "details.....",
            "other_info": "......."
        }
    }
    

    这取决于你如何想要提供该数据密钥或者你想要给出任何你可以给出的通知.......你将用相同的密钥给你什么...你会得到那些数据........ .

    如果你没有发送点击动作的情况很少,你会点击通知默认活动会打开,但如果你想在应用程序处于后台时打开你的特定活动你可以在handleIntent方法上调用你的活动,因为这个每次调用

  • 5

    即使应用程序处于后台和前台,也可以通过以下方式发送消息的简便方法: - 要使用API发送消息,您可以使用名为AdvancedREST Client的工具,其chrome扩展名,并使用以下参数发送消息 .

    Rest客户端工具链接:https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo

    使用此URL: - https://fcm.googleapis.com/fcm/send Content-Type:application / json授权:key =您的服务器密钥From或Authoization密钥(参见下面的参考资料)

    { "data": {
        "image": "https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg",
        "message": "Firebase Push Message Using API"
        "AnotherActivity": "True"
         },
      "to" : "device id Or Device token"
    }
    

    可以通过访问Google开发人员控制台并单击项目左侧菜单上的“凭据”按钮来获取授权密钥 . 在列出的API密钥中,服务器密钥将是您的授权密钥 .

    并且您需要将接收器的tokenID放在使用API发送的POST请求的“to”部分中 .

  • 506

    我想出了这些场景,

    当app在前台时,从 FirebaseService 调用 onMessageReceived() 方法 . 因此,将调用服务类中定义的pendingIntent .

    当app在后台时,会调用 first activity .

    现在,如果你使用 splash activity ,那么必须记住 splashactivity 将被调用,否则如果没有splashActivity,那么无论第一个活动是什么,都将被调用 .

    然后你需要检查 firstActivitygetIntent() 以查看它是否有任何 bundle . 如果一切正常,你会看到bundle中有值填充 . 如果从服务器发送的数据标签中的值如下所示,

    "data": {
        "user_name": "arefin sajib",
        "value": "user name notification"
      }
    

    然后在第一个活动中,你会看到,有一个有效的意图(getIntent()不是null),有效的bundle和内部bundle,上面提到的整个JSON将 data 作为 key .

    对于这种情况,提取值的代码将如下所示,

    if(getIntent()!=null){
                Bundle bundle = getIntent().getExtras();
                if (bundle != null) {
                    try {
                       JSONObject object = new JSONObject(bundle.getStringExtra("data"));
    String user_name = object.optString("user_name");
    
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
    
    
                }
            }
    
  • 7

    使用此代码,您可以在后台/前台获取通知并执行操作:

    //Data should come in this format from the notification
    {
      "to": "/xyz/Notifications",
      "data": {
          "key1": "title notification",
          "key2": "description notification"
      }
    }
    

    应用内使用此代码:

    @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
          String key1Data = remoteMessage.getData().get("key1");
          // use key1Data to according to your need
        }
    
  • 1

    要使firebase库在以下情况下调用 onMessageReceived()

    • 应用程序在前台

    • 应用程序在后台

    • App已被杀死

    您不能在请求中将JSON密钥“通知”放入firebase API,而是使用“数据”,请参阅下文 .

    当您的应用在后台或被杀时,以下消息将不会调用您的 onMessageReceived() ,并且您无法自定义您的通知 .

    {
       "to": "/topics/journal",
       "notification": {
       "title" : "title",
       "text": "data!",
       "icon": "ic_notification"
        }
    }
    

    但改为使用它会起作用

    {
      "to": "/topics/dev_journal",
       "data": {
           "text":"text",
           "title":"",
           "line1":"Journal",
           "line2":"刊物"
       }
    }
    

    基本上,消息在参数RemoteMessage中与您的数据对象一起作为Map发送,然后您可以在onMessageReceived中管理通知,就像在这里的片段一样

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) { 
         Map<String, String> data = remoteMessage.getData();
    
         //you can get your text message here.
         String text= data.get("text");
    
    
         NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            // optional, this is to make beautiful icon
                 .setLargeIcon(BitmapFactory.decodeResource(
                                        getResources(), R.mipmap.ic_launcher))  
            .setSmallIcon(smallIcon)  //mandatory
          .......
        /*You can read more on notification here:
        https://developer.android.com/training/notify-user/build-notification.html
        https://www.youtube.com/watch?v=-iog_fmm6mE
        */
    }
    
  • 5

    根据docs

    处理后台应用程序中的消息当您的应用程序处于后台时,Android会将通知消息定向到系统托盘 . 用户点按通知会默认打开应用启动器 . 这包括包含通知和数据有效负载的消息 . 在这些情况下,通知将传递到设备的系统托盘,并且数据有效负载将在启动器活动的附加内容中传递 . 如果你想要打开您的应用并执行特定操作,请在通知有效内容中设置click_action,并将其映射到您要启动的活动中的intent过滤器 . 例如,将click_action设置为OPEN_ACTIVITY_1以触发如下所示的intent过滤器:

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

    编辑:

    基于此thread

    您无法使用Firebase控制台设置click_action有效内容 . 您可以尝试使用curl命令或自定义http服务器进行测试

    curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>" 
         --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send  
         -d "{\"to\":\"/topics/news\",\"notification\": 
             {\"title\": \"Click Action Message\",\"text\": \"Sample message\",
                \"click_action\":\"OPEN_ACTIVITY_1\"}}"
    
  • 2

    我觉得所有的回复都不完整,但是当你的应用处于后台时,所有这些回复都需要处理包含数据的通知 .

    按照以下步骤操作,您就可以在应用处于后台时处理通知 .

    1.添加如下的intent-filter:

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

    到您要处理通知数据的活动 .

    • 使用下一格式发送通知:
    { 
     "notification" : {
            "click_action" : ".MainActivity", 
            "body" : "new Symulti update !", 
            "title" : "new Symulti update !", 
            "icon" : "ic_notif_symulti" }, 
     "data": { ... },
     "to" : "c9Vaa3ReGdk:APA91bH-AuXgg3lDN2WMcBrNhJZoFtYF9" }
    

    这里的关键是添加

    "click_action" : ".MainActivity"
    

    其中.MainActivity是您在步骤1中添加的intent-filter的活动 .

    • 从“.MainActivity”的onCreate中获取通知中的“数据”信息:
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //get notification data info
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
           //bundle must contain all info sent in "data" field of the notification
        }
    }
    

    这应该就是你需要做的一切 . 我希望这有助于某人:)

  • 0

    你想在后台工作onMessageReceived(RemoteMessage remoteMessage)只发送数据部分通知部分:

    "data":    "image": "",    "message": "Firebase Push Message Using API",
    

    “AnotherActivity”:“True”,“to”:“设备ID或设备令牌”

    通过这个onMessageRecivied是调用后台和前台,无需使用启动器活动上的通知托盘处理通知 . 使用此处理数据有效负载:
    public void onMessageReceived(RemoteMessage remoteMessage)if(remoteMessage.getData() . size()> 0)Log.d(TAG,"Message data payload: " remoteMessage.getData());

  • 121

    2017更新了答案

    以下是docs关于此问题的明确答案:

    enter image description here

  • 68

    2018年6月答案 -

    您必须确保消息中的任何位置都没有“通知”关键字 . 只包含“数据”,应用程序将能够处理onMessageReceived中的消息,即使在后台或已杀死 .

    Using Cloud Functions:

    const message = {
        token: token_id,   // obtain device token id by querying data in firebase
        data: {
           title: "my_custom_title",
           body:  "my_custom_body_message"
           }
        }
    
    
    return admin.messaging().send(message).then(response => {
        // handle response
    });
    

    Then in your onMessageReceived(), in your class extending com.google.firebase.messaging.FirebaseMessagingService :

    if (data != null) {
      Log.d(TAG, "data title is: " + data.get("title");
      Log.d(TAG, "data body is: " + data.get("body");
    }
    
    // build notification using the body, title, and whatever else you want.
    
  • 30

    由于从Firebase Notification UI发送的 display-messages 仅在您的应用位于前台时才有效 . 对于 data-messages ,需要对FCM进行POST调用

    Steps

    • 安装高级Rest客户端Google Chrome扩展程序
      enter image description here

    • 添加以下 Headers

    Key :Content-Type, Value :application / json

    Key :授权, Value :key = "your server key"
    enter image description here

    • 添加身体

    • 如果使用主题:

    {
        "to" : "/topics/topic_name",
        "data": {
        "key1" : "value1",
        "key2" : "value2",
        }
    }
    
    • 如果使用注册ID:
    {
        "registration_ids" : "[{"id"},{id1}]",
        "data": {
        "key1" : "value1",
        "key2" : "value2",
         }
    }
    

    而已! . 现在像往常一样听 onMessageReceived 回调 .

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) { 
         Map<String, String> data = remoteMessage.getData();
         String value1 = data.get("key1");
         String value2 = data.get("key2");
    }
    
  • 1

    根据send downstream using firebase中的firebase文档,有两种类型的有效负载:

    • data

    此参数指定消息的有效内容的自定义键值对 . 客户端应用程序负责处理数据消息 . 数据消息只有自定义键值对 .

    • notification

    此参数指定通知有效内容的预定义的,用户可见的键值对 . FCM代表客户端应用自动向最终用户设备显示消息 . 通知消息具有一组预定义的用户可见键 .

    当您在前台时,您可以使用 onMessageReceived() 在FCM中获取数据,您可以从 data 有效负载获取数据 .

    data = remoteMessage.getData();
    String customData = (String) data.get("customData");
    

    当您在后台时,FCM将根据 notification payload中的信息在系统托盘中显示通知 . 用于系统托盘上通知的 Headers ,消息和图标来自 notification 有效负载 .

    {
      "notification": {
            "title" : "title",
            "body"  : "body text",
            "icon"  : "ic_notification",
            "click_action" : "OPEN_ACTIVITY_1"
           }
    }
    

    当您希望在应用程序处于后台时在系统托盘上自动显示通知时,将使用此 notification 有效内容 . 要在后台运行应用时获取通知数据,您应该在 notification payload中添加click_action .

    如果要打开应用程序并执行特定操作[在后台运行时],请在通知有效内容中设置click_action,并将其映射到要启动的活动中的intent过滤器 . 例如,将click_action设置为OPEN_ACTIVITY_1以触发如下所示的intent过滤器:

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

    将intent-filter放在应用程序标记内的清单上 . 单击通知时,它将打开应用程序并直接进入您在click_action中定义的活动,在本例中为“OPEN_ACTIVTY_1” . 在该活动中,您可以通过以下方式获取数据:

    Bundle b = getIntent().getExtras();
    String someData = b.getString("someData");
    

    我正在为我的Android应用程序使用FCM并使用两个有效负载 . 这是我正在使用的示例JSON:

    {
      "to": "FCM registration ID",
      "notification": {
        "title" : "title",
        "body"  : "body text",
        "icon"  : "ic_notification"
       },
       "data": {
         "someData"  : "This is some data",
         "someData2" : "etc"
       }
    }
    
  • 16

    感谢大家的回答 . 但我通过发送 data message 而不是发送 Notification 来解决这个问题 . 服务器代码

    <?php
    $url = "https://fcm.googleapis.com/fcm/send";
    $token = "C-l6T_a7HouUK****";
    $serverKey = "AAAAaOcKS00:********";
    define( 'API_ACCESS_KEY', $serverKey );
    $registrationIds = array($token);
    // prep the bundle
    
    $msg = array
    
    (
     'message'  => 'here is a message. message',
     'title'        => 'This is a title. title',
     'subtitle' => 'This is a subtitle. subtitle',
     'tickerText'   => 'Ticker text here...Ticker text here...Ticker text 
     here',
     'vibrate'  => 1,
     'sound'        => 1,
     'largeIcon'    => 'large_icon',
     'smallIcon'    => 'small_icon'
    
    );
    
    $fields = array
    
    (
      'registration_ids'    => $registrationIds,
      'data'            => $msg
    
    );
    $headers = array
    
    (
      'Authorization: key=' . API_ACCESS_KEY,
     'Content-Type: application/json'
    
    );
    
    
    $ch = curl_init();
    
    curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' 
    );
    
    curl_setopt( $ch,CURLOPT_POST, true );
    
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    
    $result = curl_exec($ch );
    
    curl_close( $ch );
    
    echo $result;
    
    ?>
    

    And caught the Data in onMessageReceived

    public class MyFirebaseMessagingService extends FirebaseMessagingService     {
    
      private static final String TAG = "MyFirebaseMsgService";
    
    @Override
    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());
    
          sendNotification(remoteMessage.getData().get("message"));
         }
       // Check if message contains a notification payload.
        else if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
        }
    
    
    }
       private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, Notify.class).putExtra("msg",messageBody);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
    
        String channelId = "idddd";
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(MyFirebaseMessagingService.this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);
    
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
    }
    
  • 13

    1.为什么会这样?

    FCM(Firebase Cloud 消息传递)中有两种类型的消息:

    • Display Messages :仅当您的应用位于 foreground 时,这些消息才会触发 onMessageReceived() 回调

    • Data Messages :如果您的应用位于 foreground/background/killed ,则这些消息会触发 onMessageReceived() 回调 even

    Firebase团队还没有开发用于向您的设备发送 data-messages 的UI .

    2.怎么样?

    要实现此目的,您必须对以下URL执行 POST 请求:

    POST https://fcm.googleapis.com/fcm/send

    Headers

    • Key: Content-TypeValue: application/json

    • Key: AuthorizationValue: key=<your-server-key>

    使用主题的正文

    {
        "to": "/topics/my_topic",
        "data": {
            "my_custom_key": "my_custom_value",
            "my_custom_key2": true
         }
    }
    

    或者如果要将其发送到特定设备

    {
        "data": {
            "my_custom_key": "my_custom_value",
            "my_custom_key2": true
         },
        "registration_ids": ["{device-token}","{device2-token}","{device3-token}"]
    }
    

    注意:确保您没有添加JSON密钥通知注意:要获取服务器密钥,您可以在firebase控制台中找到它:您的项目 - >设置 - >项目设置 - > Cloud 消息 - >服务器密钥

    3.如何处理推送通知消息?

    这是您处理收到的消息的方式:

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) { 
         Map<String, String> data = remoteMessage.getData();
         String myCustomKey = data.get("my_custom_key");
    
         // Manage data
    }
    
  • 12

    这里有关于firebase消息的更清晰的概念 . 我是从他们的支持团队那里找到的 .

    Firebase has three message types

    Notification messages :通知消息适用于背景或前景 . 当应用程序处于后台时,通知消息将传递到系统托盘 . 如果应用程序位于前台,则消息由 onMessageReceived()didReceiveRemoteNotification 回调处理 . 这些基本上就是所谓的显示消息 .

    Data messages :在Android平台上,数据信息可以在后台和前台工作 . 数据消息将由onMessageReceived()处理 . 这里的平台特定说明如下:在Android上,可以在用于启动活动的Intent中检索数据有效负载 . 详细说明,如果您有 "click_action":"launch_Activity_1" ,则可以仅通过 Activity_1getIntent() 检索此意图 .

    Messages with both notification and data payloads :在后台,应用程序在通知托盘中接收通知有效负载,并仅在用户点击通知时处理数据有效负载 . 在前台时,您的应用会收到一条消息两个有效负载都可用的对象 . 其次, click_action 参数通常用于通知有效负载而不是数据有效负载 . 如果在数据有效内容中使用,则此参数将被视为自定义键值对,因此您需要实现自定义逻辑以使其按预期工作 .

    另外,我建议您使用 onMessageReceived 方法(请参阅数据消息)来提取数据包 . 根据您的逻辑,我检查了bundle对象,但没有找到预期的数据内容 . 以下是对类似案例的引用,可能会提供更清晰的说明 .

    欲了解更多信息,请访问我的this thread

  • 7

    根据文件:2017年5月17日

    当您的应用在后台时,Android会将通知消息定向到系统托盘 . 用户点按通知会默认打开应用启动器 . 这包括包含通知和数据有效负载的消息(以及从通知控制台发送的所有消息) . 在这些情况下,通知将传递到设备的系统托盘,并且数据有效负载将在启动器活动的附加内容中传递 .

    因此,您应该使用两个有效负载通知数据:

    {
      "to": "FCM registration ID",
      "notification": {
        "title" : "title",
        "body"  : "body text",
        "icon"  : "ic_notification"
       },
       "data": {
         "someData"  : "This is some data",
         "someData2" : "etc"
       }
    }
    

    没有必要使用click_action.You应该只是从 LAUNCHER activity 获取exras

    <activity android:name=".MainActivity">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    </activity>
    

    Java代码应该在MainActivity上的onCreate方法上:

    Intent intent = getIntent();
    if (intent != null && intent.getExtras() != null) {
        Bundle extras = intent.getExtras();
        String someData= extras.getString("someData");
        String someData2 = extras.getString("someData2");
    }
    

    您可以从Firebase Notifications Console测试两个有效负载通知数据 . 不要忘记在高级选项部分填写自定义数据字段

  • 2

    Remove notification payload 完全来自您的服务器请求 . 发送 only data 并在 onMessageReceived() 处理它,否则当应用程序处于后台或被杀时,不会触发 onMessageReceived .

    这是我从服务器发送的内容:

    {
      "data":{
        "id": 1,
        "missedRequests": 5
        "addAnyDataHere": 123
      },
      "to": "fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......"
    }
    

    所以你可以像这样在 onMessageReceived(RemoteMessage message) 收到你的数据:(假设我必须得到id)

    Object obj = message.getData().get("id");
            if (obj != null) {
                int id = Integer.valueOf(obj.toString());
            }
    

    同样,您可以在 onMessageReceived() 内获取从服务器发送的任何数据 .

  • 1

    像这样简单的总结

    • 如果您的应用正在运行;
    onMessageReceived()
    

    是触发器 .

    • 如果您的应用未运行(通过滑动杀死);
    onMessageReceived()
    

    并非由direclty触发和交付 . 如果你有任何特定的键值对 . 他们不工作因为onMessageReceived()无法正常工作 .

    我已经找到了这种方式;

    在你的启动器活动中,把这个逻辑,

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_splash);
    
        if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("PACKAGE_NAME")) {
    
            // do what you want
    
            // and this for killing app if we dont want to start
            android.os.Process.killProcess(android.os.Process.myPid());
    
        } else {
    
            //continue to app
        }
    }
    

    在此if块中,根据firebase UI搜索您的密钥 .

    在这个例子中,我的关键和 Value 如上; (抱歉语言=))
    enter image description here

    当我的代码工作时,我得到“com.rda.note” .

    android.os.Process.killProcess(android.os.Process.myPid());
    

    使用这行代码,我关闭了我的应用程序并打开了Google Play Market

    快乐的编码=)

  • -3

    除上述答案外,如果您使用 FCM console 测试推送通知,则'data'键和对象 not 已添加到推送通知包 . 因此,当App处于后台或被杀时,您将不会收到详细的推送通知 .

    在这种情况下,您必须选择后端管理控制台来测试应用程序后台方案 .

    在这里,您将为推送包添加“数据”键 . 因此,详细推送将按预期显示 . 希望这对少有帮助 .

相关问题