Keeping your mobile screen active (iOS and Android)

There are times when you need to force your app to stay active. (For example, a routing app or something where its supposed to be hands free. You don’t want your user to have to keep tapping it to keep it from sleeping.) Its easy to do this in both Android and iOS.

For Android, insert this little bit of code in each Activity’s onResume() function that you want to prevent from sleeping:

	@Override
	public void onResume() {
		super.onResume();
		// stop screen from sleeping
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

Android will re-enable sleep timeouts whenever you exit the app, so you don’t have to worry about turning it back on.

For iOS, its almost as simple, except you only have to do it once for your entire app. You enable it when your application becomes active, and disable it when it enters the background. Insert this bit of code in your app delegate:

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // stop screen from sleeping
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // let screen sleep
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

That’s it!