I used FireBase could messaging in my application and I want when the user receive message the activity fragment change. I did the following code for that but i don't know why it give me error on getFragmentManager that it because i don't have activity context or something like that.
public class googleFirebaseMessageService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
switch (remoteMessage.getData().get("message"))
{
case "invoices_ready":
SharedPreferences preferences=getSharedPreferences("invoices_ready",MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("pr_id",remoteMessage.getData().get("pr_id").toString());
editor.commit();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.root_menu_fragment, new _step4_FragmentDrugInfo());
transaction.addToBackStack("mapView");
transaction.commit();
showNotification(remoteMessage.getData().get("message"));
break;
}
}
private void showNotification(String messageBody) {
Intent intent = new Intent( this , splash.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Android Tutorial Point FCM Tutorial")
.setContentText(messageBody)
.setAutoCancel( true )
.setSound(notificationSoundURI)
.setContentIntent(resultIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotificationBuilder.build());
}
}
getFragmentManager()
is a method ofActivity
, therefore it can't work in aService
.you can't get a reference to
getFragmentManager()
in the service class How erver you can use a broadcast to listne the calls, anywhere else in the application.You should broadcast any firebase message updates and register broadcast receiver that handles that updates(where you should do fragment transactions) in your activity. If your activity is in the foreground that means luckily your receiver is registered. If you want to add the fragment in firebase service context, you can implement your own android.app.Application.ActivityLifecycleCallbacks interface, like
And get your activity's reference from ActivityLifeCycleHandler class of yours.(be careful not to leak the activity) . I wouldn't recommend this solution thought.
This callback is registered for your application instance and its callbacks(onResume()) are triggered by Activity life-cycle methods(super.onResume()) for every activity in your application.