Firebase (FCM): open activity and pass data on notification click. android












35















There should be clear implementation of how to work with Firebase notification and data. I read many answers but can't seem to make it work. here are my steps:



1.) I am passing notification and data to android in PHP and it seems to be fine:



$msg = array
(
"body" => $body,
"title" => $title,
"sound" => "mySound"
);

$data = array
(

"user_id" => $res_id,
"date" => $date,
"hal_id" => $hal_id,
"M_view" => $M_view
);

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



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


2.) when notification and data is received in Android it shows notification. When I click on this notification it opens app. But I can not figure out the way to handle the data when the app is opened. There are couple differences when app is in foreground and backround. The code that I have now is the following:



public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

String user_id = "0";
String date = "0";
String cal_id = "0";
String M_view = "0";

if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
user_id = remoteMessage.getData().get("user_id");
date = remoteMessage.getData().get("date");
hal_id = remoteMessage.getData().get("hal_id");
M_view = remoteMessage.getData().get("M_view");
}

//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view);
}

private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

intent.putExtra("fcm_notification", "Y");
intent.putExtra("user_id", user_id);
intent.putExtra("date", date);
intent.putExtra("hal_id", hal_id);
intent.putExtra("M_view", M_view);
int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
PendingIntent.FLAG_UPDATE_CURRENT);

Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}


3.) When I use the code above and when I click on notification all it does it opens the app if in background. If app in foreground then on notification click it simply dismisses notification. However, I want to receive data and open specific Activity in both scenarios (background and foreground). I have in MainActivity the following code, but I am not able to get data. fcm_notification, date, hal_id returns null.



public class MainActivity extends Activity {
UserFunctions userFunctions;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Intent intent_o = getIntent();
}

@Override
protected void onResume() {
super.onResume();
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
Intent intent_o = getIntent();
String fcm_notification = intent_o.getStringExtra("fcm_notification") ;
String user_id = intent_o.getStringExtra("user_id");
String date = intent_o.getStringExtra("date");
String hal_id = intent_o.getStringExtra("hal_id");
String M_view = intent_o.getStringExtra("M_view");
Intent intent = new Intent(this, JobList.class);

// THIS RETURNS NULL, user_id = null
System.out.print("FCM" + user_id);
startActivity(intent);
finish();
}else{
// user is not logged in show login screen
Intent login = new Intent(this, LoginActivity.class);
startActivity(login);
// Closing dashboard screen
finish();
}
}}


IF anyone can direct or advice how can I retrieve data in MainActivity.java from Firebase in either scenario (foreground or background) that would be fantastic.










share|improve this question



























    35















    There should be clear implementation of how to work with Firebase notification and data. I read many answers but can't seem to make it work. here are my steps:



    1.) I am passing notification and data to android in PHP and it seems to be fine:



    $msg = array
    (
    "body" => $body,
    "title" => $title,
    "sound" => "mySound"
    );

    $data = array
    (

    "user_id" => $res_id,
    "date" => $date,
    "hal_id" => $hal_id,
    "M_view" => $M_view
    );

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



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


    2.) when notification and data is received in Android it shows notification. When I click on this notification it opens app. But I can not figure out the way to handle the data when the app is opened. There are couple differences when app is in foreground and backround. The code that I have now is the following:



    public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

    String user_id = "0";
    String date = "0";
    String cal_id = "0";
    String M_view = "0";

    if (remoteMessage.getData().size() > 0) {
    Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    user_id = remoteMessage.getData().get("user_id");
    date = remoteMessage.getData().get("date");
    hal_id = remoteMessage.getData().get("hal_id");
    M_view = remoteMessage.getData().get("M_view");
    }

    //Calling method to generate notification
    sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view);
    }

    private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    intent.putExtra("fcm_notification", "Y");
    intent.putExtra("user_id", user_id);
    intent.putExtra("date", date);
    intent.putExtra("hal_id", hal_id);
    intent.putExtra("M_view", M_view);
    int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
    PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
    .setContentText(messageBody)
    .setAutoCancel(true)
    .setSound(defaultSoundUri)
    .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
    }}


    3.) When I use the code above and when I click on notification all it does it opens the app if in background. If app in foreground then on notification click it simply dismisses notification. However, I want to receive data and open specific Activity in both scenarios (background and foreground). I have in MainActivity the following code, but I am not able to get data. fcm_notification, date, hal_id returns null.



    public class MainActivity extends Activity {
    UserFunctions userFunctions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    }

    @Override
    protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    Intent intent_o = getIntent();
    }

    @Override
    protected void onResume() {
    super.onResume();
    userFunctions = new UserFunctions();
    if(userFunctions.isUserLoggedIn(getApplicationContext())){
    Intent intent_o = getIntent();
    String fcm_notification = intent_o.getStringExtra("fcm_notification") ;
    String user_id = intent_o.getStringExtra("user_id");
    String date = intent_o.getStringExtra("date");
    String hal_id = intent_o.getStringExtra("hal_id");
    String M_view = intent_o.getStringExtra("M_view");
    Intent intent = new Intent(this, JobList.class);

    // THIS RETURNS NULL, user_id = null
    System.out.print("FCM" + user_id);
    startActivity(intent);
    finish();
    }else{
    // user is not logged in show login screen
    Intent login = new Intent(this, LoginActivity.class);
    startActivity(login);
    // Closing dashboard screen
    finish();
    }
    }}


    IF anyone can direct or advice how can I retrieve data in MainActivity.java from Firebase in either scenario (foreground or background) that would be fantastic.










    share|improve this question

























      35












      35








      35


      17






      There should be clear implementation of how to work with Firebase notification and data. I read many answers but can't seem to make it work. here are my steps:



      1.) I am passing notification and data to android in PHP and it seems to be fine:



      $msg = array
      (
      "body" => $body,
      "title" => $title,
      "sound" => "mySound"
      );

      $data = array
      (

      "user_id" => $res_id,
      "date" => $date,
      "hal_id" => $hal_id,
      "M_view" => $M_view
      );

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



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


      2.) when notification and data is received in Android it shows notification. When I click on this notification it opens app. But I can not figure out the way to handle the data when the app is opened. There are couple differences when app is in foreground and backround. The code that I have now is the following:



      public class MyFirebaseMessagingService extends FirebaseMessagingService {

      private static final String TAG = "MyFirebaseMsgService";

      @Override
      public void onMessageReceived(RemoteMessage remoteMessage) {

      String user_id = "0";
      String date = "0";
      String cal_id = "0";
      String M_view = "0";

      if (remoteMessage.getData().size() > 0) {
      Log.d(TAG, "Message data payload: " + remoteMessage.getData());
      user_id = remoteMessage.getData().get("user_id");
      date = remoteMessage.getData().get("date");
      hal_id = remoteMessage.getData().get("hal_id");
      M_view = remoteMessage.getData().get("M_view");
      }

      //Calling method to generate notification
      sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view);
      }

      private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) {
      Intent intent = new Intent(this, MainActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

      intent.putExtra("fcm_notification", "Y");
      intent.putExtra("user_id", user_id);
      intent.putExtra("date", date);
      intent.putExtra("hal_id", hal_id);
      intent.putExtra("M_view", M_view);
      int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
      PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
      PendingIntent.FLAG_UPDATE_CURRENT);

      Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
      notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
      .setContentText(messageBody)
      .setAutoCancel(true)
      .setSound(defaultSoundUri)
      .setContentIntent(pendingIntent);

      NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      notificationManager.notify(0, notificationBuilder.build());
      }}


      3.) When I use the code above and when I click on notification all it does it opens the app if in background. If app in foreground then on notification click it simply dismisses notification. However, I want to receive data and open specific Activity in both scenarios (background and foreground). I have in MainActivity the following code, but I am not able to get data. fcm_notification, date, hal_id returns null.



      public class MainActivity extends Activity {
      UserFunctions userFunctions;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      }

      @Override
      protected void onNewIntent(Intent intent) {
      super.onNewIntent(intent);
      setIntent(intent);
      Intent intent_o = getIntent();
      }

      @Override
      protected void onResume() {
      super.onResume();
      userFunctions = new UserFunctions();
      if(userFunctions.isUserLoggedIn(getApplicationContext())){
      Intent intent_o = getIntent();
      String fcm_notification = intent_o.getStringExtra("fcm_notification") ;
      String user_id = intent_o.getStringExtra("user_id");
      String date = intent_o.getStringExtra("date");
      String hal_id = intent_o.getStringExtra("hal_id");
      String M_view = intent_o.getStringExtra("M_view");
      Intent intent = new Intent(this, JobList.class);

      // THIS RETURNS NULL, user_id = null
      System.out.print("FCM" + user_id);
      startActivity(intent);
      finish();
      }else{
      // user is not logged in show login screen
      Intent login = new Intent(this, LoginActivity.class);
      startActivity(login);
      // Closing dashboard screen
      finish();
      }
      }}


      IF anyone can direct or advice how can I retrieve data in MainActivity.java from Firebase in either scenario (foreground or background) that would be fantastic.










      share|improve this question














      There should be clear implementation of how to work with Firebase notification and data. I read many answers but can't seem to make it work. here are my steps:



      1.) I am passing notification and data to android in PHP and it seems to be fine:



      $msg = array
      (
      "body" => $body,
      "title" => $title,
      "sound" => "mySound"
      );

      $data = array
      (

      "user_id" => $res_id,
      "date" => $date,
      "hal_id" => $hal_id,
      "M_view" => $M_view
      );

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



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


      2.) when notification and data is received in Android it shows notification. When I click on this notification it opens app. But I can not figure out the way to handle the data when the app is opened. There are couple differences when app is in foreground and backround. The code that I have now is the following:



      public class MyFirebaseMessagingService extends FirebaseMessagingService {

      private static final String TAG = "MyFirebaseMsgService";

      @Override
      public void onMessageReceived(RemoteMessage remoteMessage) {

      String user_id = "0";
      String date = "0";
      String cal_id = "0";
      String M_view = "0";

      if (remoteMessage.getData().size() > 0) {
      Log.d(TAG, "Message data payload: " + remoteMessage.getData());
      user_id = remoteMessage.getData().get("user_id");
      date = remoteMessage.getData().get("date");
      hal_id = remoteMessage.getData().get("hal_id");
      M_view = remoteMessage.getData().get("M_view");
      }

      //Calling method to generate notification
      sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view);
      }

      private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) {
      Intent intent = new Intent(this, MainActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

      intent.putExtra("fcm_notification", "Y");
      intent.putExtra("user_id", user_id);
      intent.putExtra("date", date);
      intent.putExtra("hal_id", hal_id);
      intent.putExtra("M_view", M_view);
      int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
      PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
      PendingIntent.FLAG_UPDATE_CURRENT);

      Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
      notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
      .setContentText(messageBody)
      .setAutoCancel(true)
      .setSound(defaultSoundUri)
      .setContentIntent(pendingIntent);

      NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      notificationManager.notify(0, notificationBuilder.build());
      }}


      3.) When I use the code above and when I click on notification all it does it opens the app if in background. If app in foreground then on notification click it simply dismisses notification. However, I want to receive data and open specific Activity in both scenarios (background and foreground). I have in MainActivity the following code, but I am not able to get data. fcm_notification, date, hal_id returns null.



      public class MainActivity extends Activity {
      UserFunctions userFunctions;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      }

      @Override
      protected void onNewIntent(Intent intent) {
      super.onNewIntent(intent);
      setIntent(intent);
      Intent intent_o = getIntent();
      }

      @Override
      protected void onResume() {
      super.onResume();
      userFunctions = new UserFunctions();
      if(userFunctions.isUserLoggedIn(getApplicationContext())){
      Intent intent_o = getIntent();
      String fcm_notification = intent_o.getStringExtra("fcm_notification") ;
      String user_id = intent_o.getStringExtra("user_id");
      String date = intent_o.getStringExtra("date");
      String hal_id = intent_o.getStringExtra("hal_id");
      String M_view = intent_o.getStringExtra("M_view");
      Intent intent = new Intent(this, JobList.class);

      // THIS RETURNS NULL, user_id = null
      System.out.print("FCM" + user_id);
      startActivity(intent);
      finish();
      }else{
      // user is not logged in show login screen
      Intent login = new Intent(this, LoginActivity.class);
      startActivity(login);
      // Closing dashboard screen
      finish();
      }
      }}


      IF anyone can direct or advice how can I retrieve data in MainActivity.java from Firebase in either scenario (foreground or background) that would be fantastic.







      android firebase notifications firebase-realtime-database firebase-cloud-messaging






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Oct 21 '16 at 16:40









      VaidasVaidas

      5521614




      5521614
























          4 Answers
          4






          active

          oldest

          votes


















          31














          So first off, I'll put in the detail mentioned in the Handling Messages docs.



          In the summary under the Both row, it shows that when the app is on foreground, the payload will be handled in your onMessageReceived().



          In order to open the activity from onMessageReceived(), you should check if the data you need is in the payload, if it does, call your specific activity then pass all the other details you need via intent.



          Now if the app is in background, it is mentioned in the docs that the notification is received by the Android system tray and that the data payload can be retrieved from the extras of the intent.



          Just adding in the details from my answer here which pretty much just gives the docs statement and a link to a sample:




          Handle notification messages in a backgrounded app



          When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.



          This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, 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.




          I think this answer by @ArthurThompson explains it very well:




          When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.



          From the FCM sample which launches the MainActivity when the notification is tapped:




          if (getIntent().getExtras() != null) {
          for (String key : getIntent().getExtras().keySet()) {
          String value = getIntent().getExtras().getString(key);
          Log.d(TAG, "Key: " + key + " Value: " + value);
          }
          }





          share|improve this answer





















          • 3





            I am only getting payload in my extras. any idea how can I get the notification text and title in Launching activity when the app is not even in background?

            – Syeda Zunairah
            Mar 24 '17 at 10:30











          • The FCM sample link is broken.

            – Red M
            Jan 1 at 21:49











          • @RedM Looks like Google updated their repo to add in a package for kotlin. Fixed the link. Thanks for pointing it out.

            – AL.
            Jan 2 at 4:33



















          21














          After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference



          https://www.youtube.com/watch?v=hi8IPLNq59o



          IN ADDITION to the video to add intents do in MyFirebaseMessagingService:



          public class MyFirebaseMessagingService extends FirebaseMessagingService {

          private static final String TAG = "MyFirebaseMsgService";

          @Override
          public void onMessageReceived(RemoteMessage remoteMessage) {

          String user_id = "0";
          String date = "0";
          String hal_id = "0";
          String M_view = "0";

          if (remoteMessage.getData().size() > 0) {
          Log.d(TAG, "Message data payload: " + remoteMessage.getData());
          user_id = remoteMessage.getData().get("user_id");
          date = remoteMessage.getData().get("date");
          cal_id = remoteMessage.getData().get("hal_id");
          M_view = remoteMessage.getData().get("M_view");
          }

          String click_action = remoteMessage.getNotification().getClickAction();

          //Calling method to generate notification
          sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
          }

          private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
          Intent intent = new Intent(click_action);
          intent.putExtra("user_id", user_id);
          intent.putExtra("date", date);
          intent.putExtra("hal_id", hal_id);
          intent.putExtra("M_view", M_view);

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

          Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
          NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
          notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
          .setContentTitle(messageTitle)
          .setContentText(messageBody)
          .setAutoCancel(true)
          .setSound(defaultSoundUri)
          .setContentIntent(pendingIntent);

          NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
          notificationManager.notify(0, notificationBuilder.build());
          }}


          and in new NotificationReceive activity in onCreate or onResume add this



              notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
          user_id_text = (TextView) findViewById(R.id.user_id_text);

          Intent intent_o = getIntent();
          String user_id = intent_o.getStringExtra("user_id");
          String date = intent_o.getStringExtra("date");
          String hal_id = intent_o.getStringExtra("hal_id");
          String M_view = intent_o.getStringExtra("M_view");

          notification_Y_N.setText(date);
          user_id_text.setText(hal_id);





          share|improve this answer
























          • I didn't notice you already added in an answer. 8mins late. Haha

            – AL.
            Oct 21 '16 at 21:28











          • Thanks for you answer AL. Did more research and finally came up with solution.

            – Vaidas
            Oct 22 '16 at 16:34











          • You're welcome. Do accept your answer as correct so that your post will be properly tagged. Cheers!

            – AL.
            Oct 22 '16 at 21:26













          • Where I can find the code that is used in video ?

            – Web.11
            Apr 1 '18 at 17:39











          • not sure about that. you should check with video maker since I just used this link as an example of YouTube video..

            – Vaidas
            Apr 1 '18 at 20:25



















          1














          To invoke the onMessageReceived() method you will need to use another method to send notifications (like creating a Web API to send notifications). Then using it,




          remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived() method.




          When your app is in the background, data payload is delivered to the onMessageReceived method only if there is no notification payload.




          In case both payloads exist then system automatically handles the
          notification part (system tray) and your app gets the data payload in
          the extras of the intent of launcher Activity (after the user tap on
          the notification).




          For more info please refer to the following links:




          • Why is this happening? How to? How to handle push notifications?

          • Original answer by kws. Give him an upvote.






          share|improve this answer































            0














            You don't need to implement sendNotification and onMessageReceived yourself.



            When sending:



            $data = array
            (
            "user_id" => $res_id
            //whatever fields you want to include
            );

            $msg = array
            (
            "body" => $body,
            "title" => $title,
            "data" => $data
            // more fields
            );


            android side (on your MainACtivity:



            private void handleIntent(Intent intent) {
            String user_id= intent.getStringExtra("user_id");
            if(user_id!= null)
            Log.d(TAG, user_id);
            }


            and of course:



            @Override
            protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            handleIntent(intent);
            }

            @Override
            public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            handleIntent(getIntent());
            }


            whatever fields you put in data will be sent to your intent extra.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40181654%2ffirebase-fcm-open-activity-and-pass-data-on-notification-click-android%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              31














              So first off, I'll put in the detail mentioned in the Handling Messages docs.



              In the summary under the Both row, it shows that when the app is on foreground, the payload will be handled in your onMessageReceived().



              In order to open the activity from onMessageReceived(), you should check if the data you need is in the payload, if it does, call your specific activity then pass all the other details you need via intent.



              Now if the app is in background, it is mentioned in the docs that the notification is received by the Android system tray and that the data payload can be retrieved from the extras of the intent.



              Just adding in the details from my answer here which pretty much just gives the docs statement and a link to a sample:




              Handle notification messages in a backgrounded app



              When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.



              This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, 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.




              I think this answer by @ArthurThompson explains it very well:




              When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.



              From the FCM sample which launches the MainActivity when the notification is tapped:




              if (getIntent().getExtras() != null) {
              for (String key : getIntent().getExtras().keySet()) {
              String value = getIntent().getExtras().getString(key);
              Log.d(TAG, "Key: " + key + " Value: " + value);
              }
              }





              share|improve this answer





















              • 3





                I am only getting payload in my extras. any idea how can I get the notification text and title in Launching activity when the app is not even in background?

                – Syeda Zunairah
                Mar 24 '17 at 10:30











              • The FCM sample link is broken.

                – Red M
                Jan 1 at 21:49











              • @RedM Looks like Google updated their repo to add in a package for kotlin. Fixed the link. Thanks for pointing it out.

                – AL.
                Jan 2 at 4:33
















              31














              So first off, I'll put in the detail mentioned in the Handling Messages docs.



              In the summary under the Both row, it shows that when the app is on foreground, the payload will be handled in your onMessageReceived().



              In order to open the activity from onMessageReceived(), you should check if the data you need is in the payload, if it does, call your specific activity then pass all the other details you need via intent.



              Now if the app is in background, it is mentioned in the docs that the notification is received by the Android system tray and that the data payload can be retrieved from the extras of the intent.



              Just adding in the details from my answer here which pretty much just gives the docs statement and a link to a sample:




              Handle notification messages in a backgrounded app



              When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.



              This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, 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.




              I think this answer by @ArthurThompson explains it very well:




              When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.



              From the FCM sample which launches the MainActivity when the notification is tapped:




              if (getIntent().getExtras() != null) {
              for (String key : getIntent().getExtras().keySet()) {
              String value = getIntent().getExtras().getString(key);
              Log.d(TAG, "Key: " + key + " Value: " + value);
              }
              }





              share|improve this answer





















              • 3





                I am only getting payload in my extras. any idea how can I get the notification text and title in Launching activity when the app is not even in background?

                – Syeda Zunairah
                Mar 24 '17 at 10:30











              • The FCM sample link is broken.

                – Red M
                Jan 1 at 21:49











              • @RedM Looks like Google updated their repo to add in a package for kotlin. Fixed the link. Thanks for pointing it out.

                – AL.
                Jan 2 at 4:33














              31












              31








              31







              So first off, I'll put in the detail mentioned in the Handling Messages docs.



              In the summary under the Both row, it shows that when the app is on foreground, the payload will be handled in your onMessageReceived().



              In order to open the activity from onMessageReceived(), you should check if the data you need is in the payload, if it does, call your specific activity then pass all the other details you need via intent.



              Now if the app is in background, it is mentioned in the docs that the notification is received by the Android system tray and that the data payload can be retrieved from the extras of the intent.



              Just adding in the details from my answer here which pretty much just gives the docs statement and a link to a sample:




              Handle notification messages in a backgrounded app



              When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.



              This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, 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.




              I think this answer by @ArthurThompson explains it very well:




              When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.



              From the FCM sample which launches the MainActivity when the notification is tapped:




              if (getIntent().getExtras() != null) {
              for (String key : getIntent().getExtras().keySet()) {
              String value = getIntent().getExtras().getString(key);
              Log.d(TAG, "Key: " + key + " Value: " + value);
              }
              }





              share|improve this answer















              So first off, I'll put in the detail mentioned in the Handling Messages docs.



              In the summary under the Both row, it shows that when the app is on foreground, the payload will be handled in your onMessageReceived().



              In order to open the activity from onMessageReceived(), you should check if the data you need is in the payload, if it does, call your specific activity then pass all the other details you need via intent.



              Now if the app is in background, it is mentioned in the docs that the notification is received by the Android system tray and that the data payload can be retrieved from the extras of the intent.



              Just adding in the details from my answer here which pretty much just gives the docs statement and a link to a sample:




              Handle notification messages in a backgrounded app



              When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.



              This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, 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.




              I think this answer by @ArthurThompson explains it very well:




              When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.



              From the FCM sample which launches the MainActivity when the notification is tapped:




              if (getIntent().getExtras() != null) {
              for (String key : getIntent().getExtras().keySet()) {
              String value = getIntent().getExtras().getString(key);
              Log.d(TAG, "Key: " + key + " Value: " + value);
              }
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 2 at 4:32

























              answered Oct 21 '16 at 21:26









              AL.AL.

              24.5k858192




              24.5k858192








              • 3





                I am only getting payload in my extras. any idea how can I get the notification text and title in Launching activity when the app is not even in background?

                – Syeda Zunairah
                Mar 24 '17 at 10:30











              • The FCM sample link is broken.

                – Red M
                Jan 1 at 21:49











              • @RedM Looks like Google updated their repo to add in a package for kotlin. Fixed the link. Thanks for pointing it out.

                – AL.
                Jan 2 at 4:33














              • 3





                I am only getting payload in my extras. any idea how can I get the notification text and title in Launching activity when the app is not even in background?

                – Syeda Zunairah
                Mar 24 '17 at 10:30











              • The FCM sample link is broken.

                – Red M
                Jan 1 at 21:49











              • @RedM Looks like Google updated their repo to add in a package for kotlin. Fixed the link. Thanks for pointing it out.

                – AL.
                Jan 2 at 4:33








              3




              3





              I am only getting payload in my extras. any idea how can I get the notification text and title in Launching activity when the app is not even in background?

              – Syeda Zunairah
              Mar 24 '17 at 10:30





              I am only getting payload in my extras. any idea how can I get the notification text and title in Launching activity when the app is not even in background?

              – Syeda Zunairah
              Mar 24 '17 at 10:30













              The FCM sample link is broken.

              – Red M
              Jan 1 at 21:49





              The FCM sample link is broken.

              – Red M
              Jan 1 at 21:49













              @RedM Looks like Google updated their repo to add in a package for kotlin. Fixed the link. Thanks for pointing it out.

              – AL.
              Jan 2 at 4:33





              @RedM Looks like Google updated their repo to add in a package for kotlin. Fixed the link. Thanks for pointing it out.

              – AL.
              Jan 2 at 4:33













              21














              After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference



              https://www.youtube.com/watch?v=hi8IPLNq59o



              IN ADDITION to the video to add intents do in MyFirebaseMessagingService:



              public class MyFirebaseMessagingService extends FirebaseMessagingService {

              private static final String TAG = "MyFirebaseMsgService";

              @Override
              public void onMessageReceived(RemoteMessage remoteMessage) {

              String user_id = "0";
              String date = "0";
              String hal_id = "0";
              String M_view = "0";

              if (remoteMessage.getData().size() > 0) {
              Log.d(TAG, "Message data payload: " + remoteMessage.getData());
              user_id = remoteMessage.getData().get("user_id");
              date = remoteMessage.getData().get("date");
              cal_id = remoteMessage.getData().get("hal_id");
              M_view = remoteMessage.getData().get("M_view");
              }

              String click_action = remoteMessage.getNotification().getClickAction();

              //Calling method to generate notification
              sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
              }

              private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
              Intent intent = new Intent(click_action);
              intent.putExtra("user_id", user_id);
              intent.putExtra("date", date);
              intent.putExtra("hal_id", hal_id);
              intent.putExtra("M_view", M_view);

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

              Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
              NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
              notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
              .setContentTitle(messageTitle)
              .setContentText(messageBody)
              .setAutoCancel(true)
              .setSound(defaultSoundUri)
              .setContentIntent(pendingIntent);

              NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              notificationManager.notify(0, notificationBuilder.build());
              }}


              and in new NotificationReceive activity in onCreate or onResume add this



                  notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
              user_id_text = (TextView) findViewById(R.id.user_id_text);

              Intent intent_o = getIntent();
              String user_id = intent_o.getStringExtra("user_id");
              String date = intent_o.getStringExtra("date");
              String hal_id = intent_o.getStringExtra("hal_id");
              String M_view = intent_o.getStringExtra("M_view");

              notification_Y_N.setText(date);
              user_id_text.setText(hal_id);





              share|improve this answer
























              • I didn't notice you already added in an answer. 8mins late. Haha

                – AL.
                Oct 21 '16 at 21:28











              • Thanks for you answer AL. Did more research and finally came up with solution.

                – Vaidas
                Oct 22 '16 at 16:34











              • You're welcome. Do accept your answer as correct so that your post will be properly tagged. Cheers!

                – AL.
                Oct 22 '16 at 21:26













              • Where I can find the code that is used in video ?

                – Web.11
                Apr 1 '18 at 17:39











              • not sure about that. you should check with video maker since I just used this link as an example of YouTube video..

                – Vaidas
                Apr 1 '18 at 20:25
















              21














              After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference



              https://www.youtube.com/watch?v=hi8IPLNq59o



              IN ADDITION to the video to add intents do in MyFirebaseMessagingService:



              public class MyFirebaseMessagingService extends FirebaseMessagingService {

              private static final String TAG = "MyFirebaseMsgService";

              @Override
              public void onMessageReceived(RemoteMessage remoteMessage) {

              String user_id = "0";
              String date = "0";
              String hal_id = "0";
              String M_view = "0";

              if (remoteMessage.getData().size() > 0) {
              Log.d(TAG, "Message data payload: " + remoteMessage.getData());
              user_id = remoteMessage.getData().get("user_id");
              date = remoteMessage.getData().get("date");
              cal_id = remoteMessage.getData().get("hal_id");
              M_view = remoteMessage.getData().get("M_view");
              }

              String click_action = remoteMessage.getNotification().getClickAction();

              //Calling method to generate notification
              sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
              }

              private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
              Intent intent = new Intent(click_action);
              intent.putExtra("user_id", user_id);
              intent.putExtra("date", date);
              intent.putExtra("hal_id", hal_id);
              intent.putExtra("M_view", M_view);

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

              Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
              NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
              notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
              .setContentTitle(messageTitle)
              .setContentText(messageBody)
              .setAutoCancel(true)
              .setSound(defaultSoundUri)
              .setContentIntent(pendingIntent);

              NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              notificationManager.notify(0, notificationBuilder.build());
              }}


              and in new NotificationReceive activity in onCreate or onResume add this



                  notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
              user_id_text = (TextView) findViewById(R.id.user_id_text);

              Intent intent_o = getIntent();
              String user_id = intent_o.getStringExtra("user_id");
              String date = intent_o.getStringExtra("date");
              String hal_id = intent_o.getStringExtra("hal_id");
              String M_view = intent_o.getStringExtra("M_view");

              notification_Y_N.setText(date);
              user_id_text.setText(hal_id);





              share|improve this answer
























              • I didn't notice you already added in an answer. 8mins late. Haha

                – AL.
                Oct 21 '16 at 21:28











              • Thanks for you answer AL. Did more research and finally came up with solution.

                – Vaidas
                Oct 22 '16 at 16:34











              • You're welcome. Do accept your answer as correct so that your post will be properly tagged. Cheers!

                – AL.
                Oct 22 '16 at 21:26













              • Where I can find the code that is used in video ?

                – Web.11
                Apr 1 '18 at 17:39











              • not sure about that. you should check with video maker since I just used this link as an example of YouTube video..

                – Vaidas
                Apr 1 '18 at 20:25














              21












              21








              21







              After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference



              https://www.youtube.com/watch?v=hi8IPLNq59o



              IN ADDITION to the video to add intents do in MyFirebaseMessagingService:



              public class MyFirebaseMessagingService extends FirebaseMessagingService {

              private static final String TAG = "MyFirebaseMsgService";

              @Override
              public void onMessageReceived(RemoteMessage remoteMessage) {

              String user_id = "0";
              String date = "0";
              String hal_id = "0";
              String M_view = "0";

              if (remoteMessage.getData().size() > 0) {
              Log.d(TAG, "Message data payload: " + remoteMessage.getData());
              user_id = remoteMessage.getData().get("user_id");
              date = remoteMessage.getData().get("date");
              cal_id = remoteMessage.getData().get("hal_id");
              M_view = remoteMessage.getData().get("M_view");
              }

              String click_action = remoteMessage.getNotification().getClickAction();

              //Calling method to generate notification
              sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
              }

              private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
              Intent intent = new Intent(click_action);
              intent.putExtra("user_id", user_id);
              intent.putExtra("date", date);
              intent.putExtra("hal_id", hal_id);
              intent.putExtra("M_view", M_view);

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

              Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
              NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
              notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
              .setContentTitle(messageTitle)
              .setContentText(messageBody)
              .setAutoCancel(true)
              .setSound(defaultSoundUri)
              .setContentIntent(pendingIntent);

              NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              notificationManager.notify(0, notificationBuilder.build());
              }}


              and in new NotificationReceive activity in onCreate or onResume add this



                  notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
              user_id_text = (TextView) findViewById(R.id.user_id_text);

              Intent intent_o = getIntent();
              String user_id = intent_o.getStringExtra("user_id");
              String date = intent_o.getStringExtra("date");
              String hal_id = intent_o.getStringExtra("hal_id");
              String M_view = intent_o.getStringExtra("M_view");

              notification_Y_N.setText(date);
              user_id_text.setText(hal_id);





              share|improve this answer













              After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference



              https://www.youtube.com/watch?v=hi8IPLNq59o



              IN ADDITION to the video to add intents do in MyFirebaseMessagingService:



              public class MyFirebaseMessagingService extends FirebaseMessagingService {

              private static final String TAG = "MyFirebaseMsgService";

              @Override
              public void onMessageReceived(RemoteMessage remoteMessage) {

              String user_id = "0";
              String date = "0";
              String hal_id = "0";
              String M_view = "0";

              if (remoteMessage.getData().size() > 0) {
              Log.d(TAG, "Message data payload: " + remoteMessage.getData());
              user_id = remoteMessage.getData().get("user_id");
              date = remoteMessage.getData().get("date");
              cal_id = remoteMessage.getData().get("hal_id");
              M_view = remoteMessage.getData().get("M_view");
              }

              String click_action = remoteMessage.getNotification().getClickAction();

              //Calling method to generate notification
              sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
              }

              private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
              Intent intent = new Intent(click_action);
              intent.putExtra("user_id", user_id);
              intent.putExtra("date", date);
              intent.putExtra("hal_id", hal_id);
              intent.putExtra("M_view", M_view);

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

              Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
              NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
              notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
              .setContentTitle(messageTitle)
              .setContentText(messageBody)
              .setAutoCancel(true)
              .setSound(defaultSoundUri)
              .setContentIntent(pendingIntent);

              NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              notificationManager.notify(0, notificationBuilder.build());
              }}


              and in new NotificationReceive activity in onCreate or onResume add this



                  notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
              user_id_text = (TextView) findViewById(R.id.user_id_text);

              Intent intent_o = getIntent();
              String user_id = intent_o.getStringExtra("user_id");
              String date = intent_o.getStringExtra("date");
              String hal_id = intent_o.getStringExtra("hal_id");
              String M_view = intent_o.getStringExtra("M_view");

              notification_Y_N.setText(date);
              user_id_text.setText(hal_id);






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Oct 21 '16 at 21:17









              VaidasVaidas

              5521614




              5521614













              • I didn't notice you already added in an answer. 8mins late. Haha

                – AL.
                Oct 21 '16 at 21:28











              • Thanks for you answer AL. Did more research and finally came up with solution.

                – Vaidas
                Oct 22 '16 at 16:34











              • You're welcome. Do accept your answer as correct so that your post will be properly tagged. Cheers!

                – AL.
                Oct 22 '16 at 21:26













              • Where I can find the code that is used in video ?

                – Web.11
                Apr 1 '18 at 17:39











              • not sure about that. you should check with video maker since I just used this link as an example of YouTube video..

                – Vaidas
                Apr 1 '18 at 20:25



















              • I didn't notice you already added in an answer. 8mins late. Haha

                – AL.
                Oct 21 '16 at 21:28











              • Thanks for you answer AL. Did more research and finally came up with solution.

                – Vaidas
                Oct 22 '16 at 16:34











              • You're welcome. Do accept your answer as correct so that your post will be properly tagged. Cheers!

                – AL.
                Oct 22 '16 at 21:26













              • Where I can find the code that is used in video ?

                – Web.11
                Apr 1 '18 at 17:39











              • not sure about that. you should check with video maker since I just used this link as an example of YouTube video..

                – Vaidas
                Apr 1 '18 at 20:25

















              I didn't notice you already added in an answer. 8mins late. Haha

              – AL.
              Oct 21 '16 at 21:28





              I didn't notice you already added in an answer. 8mins late. Haha

              – AL.
              Oct 21 '16 at 21:28













              Thanks for you answer AL. Did more research and finally came up with solution.

              – Vaidas
              Oct 22 '16 at 16:34





              Thanks for you answer AL. Did more research and finally came up with solution.

              – Vaidas
              Oct 22 '16 at 16:34













              You're welcome. Do accept your answer as correct so that your post will be properly tagged. Cheers!

              – AL.
              Oct 22 '16 at 21:26







              You're welcome. Do accept your answer as correct so that your post will be properly tagged. Cheers!

              – AL.
              Oct 22 '16 at 21:26















              Where I can find the code that is used in video ?

              – Web.11
              Apr 1 '18 at 17:39





              Where I can find the code that is used in video ?

              – Web.11
              Apr 1 '18 at 17:39













              not sure about that. you should check with video maker since I just used this link as an example of YouTube video..

              – Vaidas
              Apr 1 '18 at 20:25





              not sure about that. you should check with video maker since I just used this link as an example of YouTube video..

              – Vaidas
              Apr 1 '18 at 20:25











              1














              To invoke the onMessageReceived() method you will need to use another method to send notifications (like creating a Web API to send notifications). Then using it,




              remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived() method.




              When your app is in the background, data payload is delivered to the onMessageReceived method only if there is no notification payload.




              In case both payloads exist then system automatically handles the
              notification part (system tray) and your app gets the data payload in
              the extras of the intent of launcher Activity (after the user tap on
              the notification).




              For more info please refer to the following links:




              • Why is this happening? How to? How to handle push notifications?

              • Original answer by kws. Give him an upvote.






              share|improve this answer




























                1














                To invoke the onMessageReceived() method you will need to use another method to send notifications (like creating a Web API to send notifications). Then using it,




                remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived() method.




                When your app is in the background, data payload is delivered to the onMessageReceived method only if there is no notification payload.




                In case both payloads exist then system automatically handles the
                notification part (system tray) and your app gets the data payload in
                the extras of the intent of launcher Activity (after the user tap on
                the notification).




                For more info please refer to the following links:




                • Why is this happening? How to? How to handle push notifications?

                • Original answer by kws. Give him an upvote.






                share|improve this answer


























                  1












                  1








                  1







                  To invoke the onMessageReceived() method you will need to use another method to send notifications (like creating a Web API to send notifications). Then using it,




                  remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived() method.




                  When your app is in the background, data payload is delivered to the onMessageReceived method only if there is no notification payload.




                  In case both payloads exist then system automatically handles the
                  notification part (system tray) and your app gets the data payload in
                  the extras of the intent of launcher Activity (after the user tap on
                  the notification).




                  For more info please refer to the following links:




                  • Why is this happening? How to? How to handle push notifications?

                  • Original answer by kws. Give him an upvote.






                  share|improve this answer













                  To invoke the onMessageReceived() method you will need to use another method to send notifications (like creating a Web API to send notifications). Then using it,




                  remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived() method.




                  When your app is in the background, data payload is delivered to the onMessageReceived method only if there is no notification payload.




                  In case both payloads exist then system automatically handles the
                  notification part (system tray) and your app gets the data payload in
                  the extras of the intent of launcher Activity (after the user tap on
                  the notification).




                  For more info please refer to the following links:




                  • Why is this happening? How to? How to handle push notifications?

                  • Original answer by kws. Give him an upvote.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 7 '17 at 13:27









                  AshuAshu

                  95315




                  95315























                      0














                      You don't need to implement sendNotification and onMessageReceived yourself.



                      When sending:



                      $data = array
                      (
                      "user_id" => $res_id
                      //whatever fields you want to include
                      );

                      $msg = array
                      (
                      "body" => $body,
                      "title" => $title,
                      "data" => $data
                      // more fields
                      );


                      android side (on your MainACtivity:



                      private void handleIntent(Intent intent) {
                      String user_id= intent.getStringExtra("user_id");
                      if(user_id!= null)
                      Log.d(TAG, user_id);
                      }


                      and of course:



                      @Override
                      protected void onNewIntent(Intent intent) {
                      super.onNewIntent(intent);
                      handleIntent(intent);
                      }

                      @Override
                      public void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.activity_main);

                      handleIntent(getIntent());
                      }


                      whatever fields you put in data will be sent to your intent extra.






                      share|improve this answer




























                        0














                        You don't need to implement sendNotification and onMessageReceived yourself.



                        When sending:



                        $data = array
                        (
                        "user_id" => $res_id
                        //whatever fields you want to include
                        );

                        $msg = array
                        (
                        "body" => $body,
                        "title" => $title,
                        "data" => $data
                        // more fields
                        );


                        android side (on your MainACtivity:



                        private void handleIntent(Intent intent) {
                        String user_id= intent.getStringExtra("user_id");
                        if(user_id!= null)
                        Log.d(TAG, user_id);
                        }


                        and of course:



                        @Override
                        protected void onNewIntent(Intent intent) {
                        super.onNewIntent(intent);
                        handleIntent(intent);
                        }

                        @Override
                        public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);

                        handleIntent(getIntent());
                        }


                        whatever fields you put in data will be sent to your intent extra.






                        share|improve this answer


























                          0












                          0








                          0







                          You don't need to implement sendNotification and onMessageReceived yourself.



                          When sending:



                          $data = array
                          (
                          "user_id" => $res_id
                          //whatever fields you want to include
                          );

                          $msg = array
                          (
                          "body" => $body,
                          "title" => $title,
                          "data" => $data
                          // more fields
                          );


                          android side (on your MainACtivity:



                          private void handleIntent(Intent intent) {
                          String user_id= intent.getStringExtra("user_id");
                          if(user_id!= null)
                          Log.d(TAG, user_id);
                          }


                          and of course:



                          @Override
                          protected void onNewIntent(Intent intent) {
                          super.onNewIntent(intent);
                          handleIntent(intent);
                          }

                          @Override
                          public void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_main);

                          handleIntent(getIntent());
                          }


                          whatever fields you put in data will be sent to your intent extra.






                          share|improve this answer













                          You don't need to implement sendNotification and onMessageReceived yourself.



                          When sending:



                          $data = array
                          (
                          "user_id" => $res_id
                          //whatever fields you want to include
                          );

                          $msg = array
                          (
                          "body" => $body,
                          "title" => $title,
                          "data" => $data
                          // more fields
                          );


                          android side (on your MainACtivity:



                          private void handleIntent(Intent intent) {
                          String user_id= intent.getStringExtra("user_id");
                          if(user_id!= null)
                          Log.d(TAG, user_id);
                          }


                          and of course:



                          @Override
                          protected void onNewIntent(Intent intent) {
                          super.onNewIntent(intent);
                          handleIntent(intent);
                          }

                          @Override
                          public void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_main);

                          handleIntent(getIntent());
                          }


                          whatever fields you put in data will be sent to your intent extra.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered May 7 '18 at 16:21









                          Ohad CohenOhad Cohen

                          2,59912324




                          2,59912324






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40181654%2ffirebase-fcm-open-activity-and-pass-data-on-notification-click-android%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              'app-layout' is not a known element: how to share Component with different Modules

                              android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                              WPF add header to Image with URL pettitions [duplicate]