Reputation: 21237
Pretty simple situation. Adding a Chromecast
button to the toolbar
. When the app is first launched, the button does not appear. When I background the app and then bring it to the foreground again, the button appears. And yes, there is a castable device on the same wifi network.
MyFragment.kt
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.toolbar_menu, menu)
CastButtonFactory
.setUpMediaRouteButton(context?.applicationContext, menu, R.id.media_route_menu_item)
return super.onCreateOptionsMenu(menu, inflater)
}
toolbar_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/media_route_menu_item"
android:title="@string/media_route_menu_title"
app:actionProviderClass="androidx.mediarouter.app.MediaRouteActionProvider"
app:showAsAction="always" />
</menu>
Seems like that should do it. I have the CastOptionsProvider
class setup with the correct receiver id. This is a debug build, so there is no proguard.
Note that the button does eventually appear, but only after I background/foreground the app. I can wait for 10 minutes and nothing happens. But if I background/foreground, the button is visible immediately.
EDIT:
Big thanks to @fllo for the answer. There is a little more in his suggestion than was ultimately required, so I wanted to clarify for others.
The code that I posted was fine. All I was missing was simply to initialize the CastContext in onCreate() of the Activity
. Makes perfect sense if I had just thought about it.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
CastContext.getSharedInstance(this)
}
So that's it. Easy solution. Hope it helps someone.
Upvotes: 6
Views: 1150
Reputation: 11988
You need to make sure the Cast SDK is initialized before your Fragment instance is created.
Moving the Cast SDK initialisation code (CastButtonFactory with setUpMediaRouteButton(), CastStateListener and IntroductoryOverlay) into the parent Activity will work as expected. Then, maybe just hide by default the MenuItem and show it from your Fragment should do the trick.
According to the documentation, the MediaRouteButton should be in a FragmentActivity. My guess is the callbacks are not called from a Fragment, then, its visibility doesn't change dynamically. So you will need to cast it from the Activity and passing down to the Fragment when receiving an update. Not very elegant but it should work.
Upvotes: 2