Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediaRouteButton is not active in Fragment

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.

like image 629
Alex D. Avatar asked Nov 15 '18 11:11

Alex D.


Video Answer


1 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.

like image 126
l33t Avatar answered Sep 29 '22 02:09

l33t