Search code examples
androidfirebaseandroid-notificationsfirebase-cloud-messagingfirebase-notifications

Firebase send notification with key pair value from server API


I want to send notification with data from the server side and display those data in activity of my choice. So far I have managed to send notification from the server and display them to any activity of my choice.

What I do not get is

  1. How to include data in notification?
  2. How receive them in an activity?

I have tried so followed guides, but I only found those send notification with data from Firebase console.

// for server side

 <?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);
    ?>

// receive message service

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);
    }

// processing message in an 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);
     }
 }

Solution

  • In your PHP code, you have

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

    This would result in a payload like this:

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

    You are only sending a notification-only payload. So to answer #1, in order to add data in your notification, you should simply make use of the data parameter like you would do with the notification parameter. Like so:

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

    Then simply add it in your $fields:

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

    For #2, you already have the code to receive a data message, but as mentioned above, you were sending notification-only message, so it won't be able to catch anything. Just make sure you're specifying the correct key:

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

    If you were simply hoping to get the details from the notification message, you should use RemoteMessage.getNotification(). Then send the data to your preferred activity. Just make sure that you understand how to handle the messages you sent, depending on the payload.

    See the Handling Messages in Android for more details.