I have an app that can stream local media content to a Chromecast receiver. This mostly works, except that when the device is asleep and not on external power the
CommonsWare had the right of it in his comment. I was testing on a device running Android 7.1.2, and Doze mode was causing the network to drop after about 5 minutes of inactivity and irrespective of the wake lock(s) my app was holding.
The fix was to add the following permission in the manifest:
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
And then to update my onRouteSelected()
callback implementation to request that Doze mode be disabled if/when a ChromeCast route is selected:
if (Build.VERSION.SDK_INT >= 23) {
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (! pm.isIgnoringBatteryOptimizations(packageName)) {
//reguest that Doze mode be disabled
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
context.startActivity(intent);
}
}
As long as the user selects 'Yes' when prompted, the app's wake locks are respected and the ChromeCast session stays alive even when the device is not charging.