0

我使用FireBase可以在我的应用程序中进行消息传递,并且我希望当用户收到消息时活动片段发生变化。我做了下面的代码,但我不知道为什么它会给我getFragmentManager上的错误,因为我没有活动上下文或类似的东西。如何在FirebaseMessagingService中启动提交片段

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

回答

1

您应该广播任何firebase消息更新和注册广播接收器处理您的活动中的更新(你应该做片段事务)。如果你的活动在前景这意味着幸运的是你的接收器是注册。如果你想添加的火力服务上下文的片段,您可以实现自己的android.app.Application.ActivityLifecycleCallbacks接口,像

public class ActivityLifeCycleHandler implements Application.ActivityLifecycleCallbacks { 
    Activity currentActivity; 
    @Override 
    public void onActivityResumed(Activity foregroundActivity) { 
     this.currentActivity = foregroundActivity; 
    } 
} 

,并从ActivityLifeCycleHandler类你的你的活动的参考。(要小心不要泄露活动)。我不会推荐这个解决方案。

此回调注册为您的应用实例和其回调(的onResume())由活动为应用程序中每个活动的生命周期方法(super.onResume())被触发。

1

getFragmentManager()Activity的方法,因此它不能在一个Service工作。

+0

我知道并说getFragmentManager是活动的一部分,但我怎么能绑定它 – AndroidDev

+0

这里可能有一个答案:http://stackoverflow.com/a/37322977/3527024 希望它有帮助。 – thenaoh

0

您无法在服务类别中获得对getFragmentManager()的引用 您可以使用广播来列出应用程序中任何其他位置的调用。