how to display message of push notification from firebase cloud messaging on textview android

前端 未结 2 934
深忆病人
深忆病人 2021-01-21 11:16

I have implemented firebase cloud messaging in my app. I have been receiving messages sent from server in my device as a push notification but I have not been able to display th

相关标签:
2条回答
  • 2021-01-21 11:46
    private void handleNotification(String message) {
            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
    
                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                notificationUtils.playNotificationSound();
            }else{
                // If the app is in background, firebase itself handles the notification
            }
        }
    
    0 讨论(0)
  • 2021-01-21 12:10

    You can send a Broadcast message.

    In your service:

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
          Bundle bundle = new Bundle();
          bundle.putString("msgBody", remoteMessage.getNotification().getBody());
    
          Intent new_intent = new Intent();
          new_intent.setAction("ACTION_STRING_ACTIVITY");
          new_intent.putExtra("msg", bundle);
    
          sendBroadcast(new_intent);
    
          //other code
        }
    

    In your activity:

    public class MainActivity extends AppCompatActivity {
    
        private BroadcastReceiver activityReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                TextView textview = (TextView) findViewById(R.id.textview);
                Bundle bundle = intent.getBundleExtra("msg");
                textview.setText(bundle.getString("msgBody"));
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity);
    
            if (activityReceiver != null) {
               IntentFilter intentFilter = new  IntentFilter("ACTION_STRING_ACTIVITY");
               registerReceiver(activityReceiver, intentFilter);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题