MediaRouteButton is not active in Fragment

Viewed 1201

I use button for starting chromecast android.support.v7.app.MediaRouteButton in my app in activities xml and fragments xml with videoplayer.

For initializing cast button I use the next code:

private void setupChromeCast() {
        try {
            CastButtonFactory.setUpMediaRouteButton(getActivity(), castButton);
            castContext = CastContext.getSharedInstance(getActivity());
            castSession = castContext.getSessionManager().getCurrentCastSession();
            onCastStateChanged(castContext.getCastState());
            castSessionManager = new CastSessionManager(this);
            isChromeCastAvailable = true;
        } catch (Exception e) {
            isChromeCastAvailable = false;
        }
    }

And it works fine in activities. I mean, when chromecast device is near, my MediaRouteButton becomes active and I can press it. But when this Button is on Fragment, it does not become active. And callback

   @Override
    public void onCastStateChanged(int state) 

doesnt call. So, how to fix this bug? And there is one interesting moment: when I`m in fragment, button is not active, but when I hide my app into background, and then open into foreground, my mediaroutebutton becomes active. Its so strange.

2 Answers

In your activity, initialize Cast:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CastContext.getSharedInstance(this);
}

Then in your fragment you can get hold of the Cast context:

@Override
public void onResume() {
    super.onResume();

    CastContext cc = CastContext.getSharedInstance();
    cc.addCastStateListener(this);
    cc.getSessionManager().addSessionManagerListener(
        this, CastSession.class);
}

Verified with Cast version 18.1.0.

Taken from example docs:

"In order to integrate Google Cast functionality, the Activities need to inherit from either the AppCompatActivity or its parent the FragmentActivity. This limitation exists since we would need to add the MediaRouteButton (provided in the MediaRouter support library) as an MediaRouteActionProvider and this will only work if the activity is inheriting from the above-mentioned classes."

Are you sure you have inherited FragmentActivity or AppCompatActivity? If you ever got it to work let me know, I want it to work this way too.

Related