【问题标题】:Error calling getSupportFragmentManager() from a Broadcast receiver从广播接收器调用 getSupportFragmentManager() 时出错
【发布时间】:2021-01-06 21:54:46
【问题描述】:

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

IllegalStateException: FragmentManager has not been attached to a host.

广播接收器触发并且当前在 UI 中的活动中的方法触发如下,但我收到错误:

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

我要做的就是从服务中调用bottomSheet,我必须通过广播接收器来做,因为我无法从服务中调用getSupportFragmentManager!如何让工作表出现,由我的服务中的事件触发?

【问题讨论】:

    标签: java android broadcastreceiver bottom-sheet fragmentmanager


    【解决方案1】:

    Fragments 是 UI 的一部分。 BroadcastReceiverService 是后台组件,与 UI 没有任何关系。你甚至不能从BroadcastReceiver 调用方法getSupportFragmentManager()。这甚至不应该编译!

    只有 Activity 组件可以使用 UI。

    【讨论】:

    • 谢谢,那么我怎么能从我的服务中触发的事件中调用这个BottomSheet来显示呢?我们是说这是不可能的吗?是否没有策略可以从服务触发 UI 上的某些内容?
    • 我已经解决了这个问题,使用 MutableLivedata 我在 UI 的活动中观察到,如果布尔值为真,我会调用显示 BottomSheet 的方法。
    【解决方案2】:

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

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

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

    我希望这可以帮助我的情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多