Home > Back-end >  On Android, how to check the phone screen is casting?
On Android, how to check the phone screen is casting?

Time:01-20

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.

CodePudding user response:

I checked it with the code below:

fun isCastingEnabled(context: Context): Boolean {
    val mediaRouter = MediaRouter.getInstance(context)
    return mediaRouter.selectedRoute == mediaRouter.defaultRoute
}

CodePudding user response:

you can check whether the phone screen is casting or not by using the MediaRouter class.

Here is an example of how you could check if the phone screen is casting:

MediaRouter mediaRouter = (MediaRouter) 
getSystemService(Context.MEDIA_ROUTER_SERVICE);
MediaRouter.RouteInfo route = mediaRouter.getSelectedRoute();
if(route.isDefault()){
// Screen is not casting
} else {
// Screen is casting
}

This code uses the getSelectedRoute() method of the MediaRouter class to get the currently selected route. If the returned RouteInfo object is the default route, then the screen is not casting, otherwise it is.

Please note that this code uses the getSystemService(Context.MEDIA_ROUTER_SERVICE) method to get an instance of the MediaRouter class, so it should be called from an Activity or Service context.

Additionally, you could also use MediaRouter.Callback and MediaRouter.addCallback to set a callback to monitor the state of the casting, so you could get the updates on the casting state change as well.

  • Related