• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Method of toggling screen on/off programmatically?

Brachdev

Lurker
Feb 19, 2016
1
0
I’m looking for any suggestions on a good method to toggle a tablet’s screen on and off programmatically.

I’m working with a number of physically mounted tablets in a non-commercial setting. They are all connected continuously to AC power, rooted, and all are set to “stay wake, screen will never sleep while plugged in.” Half run Jelly Bean, the other Marshmallow.

On each tablet I have created/deployed a rudimentary listener using DataInputStreams.readUTF to receive commands send remotely via NetCat. Essentially the remote program instructs the tablets when to display/refresh specific webpages and to turn the screens on and off.

Disclaimer: I just started dabbling in Java/Android programming a few days ago. The only solution I could get to work is really crappy and sad. Currently my app calls a shell script that executes an input keyevent command. Below is an example of the ‘screen-on’ code. I use a similar method for ‘screen-off.’


# SCRIPT
root@otter:/sdcard/scripts # cat screenon.sh
#!/system/xbin/bash
ScrnOn=`dumpsys input_method | grep -c mScreenOn=true`
if [[ $ScrnOn -eq 0 ]]; then
input keyevent 26
fi


# APP CODE
public void turnOnScreen(){
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes("/sdcard/scripts/screenon.sh\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
}catch(IOException e){
}catch(InterruptedException e){
}
}


There must be a better way to do this directly in the app code. Any suggestions would be appreciated.
Thanks,
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones