我使用FireBase可以在我的应用程序中发送消息,我希望当用户收到消息时活动片段发生变化。我为此做了以下代码,但我不知道为什么它在getFragmentManager上给我错误,因为我没有活动上下文或类似的东西。
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());
}
}
答案 0 :(得分:1)
getFragmentManager()
是Activity
的方法,因此无法在Service
中使用。
答案 1 :(得分:1)
您应该广播任何firebase消息更新并注册处理您的活动中的更新(您应该在哪里进行片段交易)的广播接收器。如果您的活动位于前景中,那么幸运的是您的接收器已注册。如果要在firebase服务上下文中添加片段,可以实现自己的 android.app.Application.ActivityLifecycleCallbacks 接口,例如
public class ActivityLifeCycleHandler implements Application.ActivityLifecycleCallbacks {
Activity currentActivity;
@Override
public void onActivityResumed(Activity foregroundActivity) {
this.currentActivity = foregroundActivity;
}
}
从您的ActivityLifeCycleHandler类中获取您的活动引用。(注意不要泄漏活动)。我不推荐这种解决方案。
此回调已为您的应用程序实例注册,其回调( onResume())由 Activity 生命周期方法触发( super.onResume() )适用于您应用中的每项活动。
答案 2 :(得分:0)
您无法在服务类中获得对getFragmentManager()
的引用
在应用程序的任何其他位置,您可以使用广播来列出呼叫。