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