8

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.

Alex D.
  • 1,424
  • 15
  • 40
  • 2
    Did you ever discover the issue? I am also putting the button in the fragment and I would rather not move it to the activity. – cepiolot Dec 12 '19 at 01:15
  • Did you solve this? I'm experiencing this very problem with Cast `18.1.0`. When fragment is resumed the button becomes active... strange indeed! – l33t Jul 16 '20 at 00:22
  • Same issue in cast-framework:21.3.0 – DJphy Aug 12 '23 at 17:43

2 Answers2

4

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.

l33t
  • 18,692
  • 16
  • 103
  • 180
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.