Android Screen Activation and Wake Lock Management
Activating the Display via PowerManager
1. Manifest Permission
Declare the necessary permission in the AndroidManifest file to allow the application to control the screen state.
<uses-permission android:name="android.permission.WAKE_LOCK" />2. WakeLock Initialization
Retrieve the PowerManager system service and create a WakeLock instance specifying the desired screen state flags.
private PowerManager powerManager;
private WakeLock screenWakeLock;
private void initializeScreenWake(Context appContext) {
if (appContext == null) return;
powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
screenWakeLock = powerManager.newWakeLock(
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.FULL_WAKE_LOCK |
PowerManager.ON_AFTER_RELEASE,
"MyApp:ScreenActivationTag"
);
}3. Acquiring and Releasing the Lock
Invoke the acquire method to turn the screen on, passing a timeout to prevent indefinite locking. Always ensure that acquire and release operations are executed in pairs to avoid battery drain.
// Force the screen to turn on
screenWakeLock.acquire(2000L);
// Relinquish control when no longer needed
if (screenWakeLock.isHeld()) {
screenWakeLock.release();
}Maintaining Persistent Screen Illumination
1. Layout XML Attribute
The simplest approach requires no code adjustments. Apply the following attribute directly to any view element within your layout XML.
android:keepScreenOn="true"2. Window Flags Configuration
Alternatively, set the window flags programmatically before setting the content view. This method avoids requiring the WAKE_LOCK permission and will not prompt the user during installation.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);Simulating Touch Events via Shell Commands
If the application process remains active, dispatching a simulated tap event can wake the display. This technique relies on executing shell instructions.
public class InputEventSimulator {
public void triggerTapByRatio(Context context, float percentX, float percentY) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point displaySize = new Point();
windowManager.getDefaultDisplay().getSize(displaySize);
int coordinateX = (int) (displaySize.x * percentX);
int coordinateY = (int) (displaySize.y * percentY);
executeShellTap(coordinateX, coordinateY);
}
public void triggerTapAtPosition(int posX, int posY) {
executeShellTap(posX, posY);
}
private void executeShellTap(final int targetX, final int targetY) {
new Thread(() -> {
try {
Thread.sleep(150);
Runtime.getRuntime().exec(new String[]{"input", "tap", String.valueOf(targetX), String.valueOf(targetY)});
} catch (Exception err) {
err.printStackTrace();
}
}).start();
}
}Implementation Example
private InputEventSimulator eventSimulator = new InputEventSimulator();
// Trigger a tap at absolute coordinates
eventSimulator.triggerTapAtPosition(840, 580);