androidgoogle-castgoogle-cast-sdk

On Android, how to check the phone screen is casting?


I need to check if the Android phone my app runs on is using casting which is enabled outside of my app.

It seems CastSession or SessionManager can provide the session related to my app which is not helpful for me.

For example, I can start casting with an app called xx which will cast or mirror the entire screen of my phone. Now, I need to notify when I open my app that the phone's screen is casting/mirroring so I can prevent showing specific content on my app.


Solution

  • I checked it with the code below:

    val isCastingEnabledLiveData = MutableLiveData<Boolean>()
    
    fun isCastingEnabled(context: Context): Boolean {
        val mediaRouter = MediaRouter.getInstance(context)
        if (mediaRouter.routes.size <= 1) {
            isCastingEnabledLiveData.value = false
            return
        }
        val selector = MediaRouteSelector.Builder()
            .addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO)
            .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
            .build()
        mediaRouter.addCallback(selector, object : MediaRouter.Callback() {
            override fun onRouteChanged(router: MediaRouter?, route: MediaRouter.RouteInfo?) {
                super.onRouteChanged(router, route)
                isCastingEnabledLiveData.value = if (route != mediaRouter.defaultRoute) {
                    route?.connectionState != MediaRouter.RouteInfo.CONNECTION_STATE_DISCONNECTED
                } else false
            }
        })
    }