Firebase 从服务器 API 发送带有密钥对值的通知

Firebase send notification with key pair value from server API

我想从服务器端发送包含数据的通知,并在我选择的 activity 中显示这些数据。到目前为止,我已经设法从服务器发送通知并将它们显示到我选择的任何 activity。

我没有得到的是

  1. 如何在通知中包含数据?
  2. 如何在 activity 中接收它们?

我已经尝试按照指南进行操作,但我只发现那些从 Firebase 控制台发送带有数据的通知。

// 对于服务器端

 <?php
  require "init.php";
   $message =$_POST['message'];
   $title=$_POST['title'];
 //firebase server  url
  $path_to_fcm='https://fcm.googleapis.com/fcm/send';
  // Here is the server_key
   $server_key="#########";
  $token="#########";
   $headers= array(
     'Authorization:key='.$server_key, 
     'Content-Type:application/json'
           );
              // here use $tokens as the replace $key
$fields= array('to'=>$token,
'notification'=>array('title'=>$title,'body'=>$message,
  'click_action'=>'com.fredycom.tundevufirebasemysql_TARGET_NOTIFICATION'
));
   $payload= json_encode($fields);
   $curl_session= curl_init();
   curl_setopt($curl_session,CURLOPT_URL,$path_to_fcm);
   curl_setopt($curl_session,CURLOPT_POST,true);
   curl_setopt($curl_session,CURLOPT_HTTPHEADER, $headers);
   curl_setopt($curl_session,CURLOPT_RETURNTRANSFER,true);
   curl_setopt($curl_session,CURLOPT_SSL_VERIFYPEER,false);
   curl_setopt($curl_session,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
   curl_setopt($curl_session,CURLOPT_POSTFIELDS,$payload);
       $result =curl_exec($curl_session);     
       curl_close($curl_session); 
   mysqli_close($con);
    ?>

//接收消息服务

public void onMessageReceived(RemoteMessage remoteMessage) {
    // HANDLE THE FIREBASE NOTIFICATION DATA RECEIVED  WHEN APP RUN IN THE FOREGROUND

    if(remoteMessage.getData().size()>0){
        String title= remoteMessage.getData().get("title");
        String message= remoteMessage.getData().get("message");
        // now we send  the data to the  main activity
        Intent intent= new Intent("com.fredycom.myreartime_FCM_MESSAGE");
        intent.putExtra("title",title);
        intent.putExtra("message",message);
        LocalBroadcastManager localBroadcastManager= LocalBroadcastManager.getInstance(this);
        localBroadcastManager.sendBroadcast(intent);
    }

// 在 activity

中处理消息
   public class MainActivity extends AppCompatActivity {
   TextView title, message;
    @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

        // REGISTER BROADCAT RECEIVER
        LocalBroadcastManager.getInstance(this).registerReceiver(mHandler, new IntentFilter("com.fredycom.myreartime_FCM_MESSAGE"));
    setContentView(R.layout.activity_main);
    title = (TextView) findViewById(R.id.title_content);
    message = (TextView) findViewById(R.id.message_content);

    if (getIntent().getExtras() != null)
    {
        for (String key : getIntent().getExtras().keySet()) {
            if (key.equals("title"))
            {
                title.setText(getIntent().getExtras().getString(key));
            }
            else if (key.equals("message"))
            {
                message.setText(getIntent().getExtras().getString(key));
             }
            }
           }
          }
      // HERE  IS  THE BROADICAST RECEIVER GET DATA FROM SMS RECIVING SERVICE
       private BroadcastReceiver mHandler= new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String Mytitle= intent.getStringExtra("title");
        title.setText(Mytitle);
        String Mymessage= intent.getStringExtra("message");
        message.setText(Mymessage);
        }
       };

     protected  void onPause(){
         super.onPause();
         LocalBroadcastManager.getInstance(this).unregisterReceiver(mHandler);
     }
 }

在您的 PHP 代码中,您有

$fields= array('to'=>$token,
'notification'=>array('title'=>$title,'body'=>$message,
  'click_action'=>'com.fredycom.tundevufirebasemysql_TARGET_NOTIFICATION'
));

这将导致这样的有效负载:

{
  "to": "#######",
  "notification" : {
    "title": "title",
    "body" : "message",
    "click_action" : "com.fredycom.tundevufirebasemysql_TARGET_NOTIFICATION"
  }
}

您只发送 notification 有效载荷。所以回答 #1,为了在通知中添加数据,您应该简单地使用 data parameter like you would do with the notification 参数。像这样:

$datamsg = array
(
    'key'   => 'value',
    'key2'  => 'value2',
    'key3'  => 'value3',
);

然后只需将其添加到您的 $fields:

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'          => $datamsg
);

对于 #2,您已经拥有接收 data 消息的代码,但如上所述,您发送的是仅 notification 消息,因此它无法 抓住任何东西。只要确保您指定了正确的密钥:

String value = remoteMessage.getData().get("key");
String value2 = remoteMessage.getData().get("key2");
String value3 = remoteMessage.getData().get("key3");

如果您只是希望从 notification 消息中获取详细信息,您应该使用 RemoteMessage.getNotification()。然后将数据发送到您的首选activity。只需确保您了解如何根据负载处理您发送的消息。

有关详细信息,请参阅 Handling Messages in Android