簡體   English   中英

從廣播接收器調用 getSupportFragmentManager() 時出錯

[英]Error calling getSupportFragmentManager() from a Broadcast receiver

我嘗試調用一個調用 getSupportFragmentManager() 的方法,但是我得到:

IllegalStateException: FragmentManager has not been attached to a host.

廣播接收器觸發並且當前在 UI 中的活動中的方法觸發如下,但我收到錯誤:

BottomSheet bottomSheet = new BottomSheet();
bottomSheet.show(getSupportFragmentManager(), "bottomButtons");

我要做的就是從服務中調用bottomSheet,我必須通過廣播接收器來做,因為我不能從服務中調用getSupportFragmentManager,我怎樣才能讓工作表出現? 由我的服務中的事件觸發?

Fragment是 UI 的一部分。 BroadcastReceiverService是后台組件,與 UI 沒有任何關系。 您甚至不能從BroadcastReceiver調用方法getSupportFragmentManager() 這甚至不應該編譯!

只有Activity組件可以處理 UI。

從后台服務調用顯示我的 BottomSheet 的方法,該方法位於當前顯示在 UI 中的 Activity 中。 我使用了 MutableLiveData。

我初始化了一個全局 Boolean 完成,在我的服務中;

public static MutableLiveData<Boolean> finished = new MutableLiveData<Boolean>();

當在我的服務中觸發所需的事件時,我將實時數據變量的值設置為 true。

finished.setValue(true);

在活動中,我需要顯示 BottomSheet,我通過以下方式觀察此變量:

finished.observe(this, new Observer<Boolean>(){

@Override
public void onChanged(Boolean aBoolean){
if(aBoolean){
//I call my Method here which displays my Bottom Sheet, this is the method that contains the getSupportFragmentManager().
}
}
});

我希望這可以幫助我遇到這種情況的任何人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM