Search code examples
javaandroidbroadcastreceiverbottom-sheetfragmentmanager

Error calling getSupportFragmentManager() from a Broadcast receiver


I try to call a method that calls getSupportFragmentManager() however i get:

IllegalStateException: FragmentManager has not been attached to a host.

The broadcast receiver fires and the method which is in the activity which is currently in the UI fires as below but i get the error:

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

All i am attempting to do is call the bottomSheet from a service which i have to do via a broadcast receiver as i cant call getSupportFragmentManager from the service! How can i get the sheet to appear, triggered by an event in my service?


Solution

  • To Call the method which displays my BottomSheet which is situated in the Activity that is currently displayed in the UI from a background service. I used MutableLiveData.

    I initialised a global Boolean finished, in my service;

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

    When the required event triggers in my Service i set the value of the live data variable to true. with

    finished.setValue(true);
    

    In the activity i need to display the BottomSheet i am observing this variable via:

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

    I hope this can help anyone in my situation.