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

前端 未结 2 935
深忆病人
深忆病人 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 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);
            }
        }
    }
    

提交回复
热议问题