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()的引用 您可以使用廣播來列出應用程序中任何其他位置的調用。