从广播接收器调用 getSupportFragmentManager() 时出错

Error calling getSupportFragmentManager() from a Broadcast receiver

我尝试调用调用 getSupportFragmentManager() 的方法,但我得到:

IllegalStateException: FragmentManager has not been attached to a host.

广播接收器触发,activity 中的方法目前在 UI 中触发,如下所示,但我收到错误:

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

我试图做的就是从服务调用 bottomSheet,我必须通过广播接收器来调用 bottomSheet,因为我无法从服务调用 getSupportFragmentManager!我怎样才能让 sheet 出现,由我的服务中的事件触发?

Fragment 是 UI 的一部分。 BroadcastReceiverService是背景成分,与UI没有任何关系。您甚至不能从 BroadcastReceiver 调用方法 getSupportFragmentManager()。这甚至不应该编译!

只有 Activity 个组件可以使用 UI。

从后台服务调用显示位于 UI 当前显示在 UI 中的 BottomSheet 的方法。我使用了 MutableLiveData。

我初始化了一个全局布尔值,在我的服务中;

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

当所需事件在我的服务中触发时,我将实时数据变量的值设置为 true。与

finished.setValue(true);

在 activity 中,我需要显示 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().
}
}
});

我希望这可以帮助任何遇到我情况的人。