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.