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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With