公司想实现远程息屏亮屏。试了下PowerManager,对我这个广告屏来讲是没有效果的。
import android.content.Context;
import android.os.PowerManager;
public class ScreenStateHelper {
private PowerManager powerManager;
private WakeLock wakeLock;
public ScreenStateHelper(Context context) {
powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
}
public boolean isScreenOn() {
return powerManager.isInteractive();
}
public void acquireWakeLock() {
if (wakeLock != null) {
wakeLock.release();
}
wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
}
public void releaseWakeLock() {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
}
}
然后想着是把亮度调成0,结果只是变得很暗,还是能看见界面:
public static void setScreenDark(Context context) {
if (!Settings.System.canWrite(context)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(intent);
} else {
Settings.System.putInt(
context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
0
);
}
}
最后想着用adb命令试试:
adb shell input keyevent KEYCODE_POWER
发现是可以使用的,然后使用Runtime.getRuntime().exec("input keyevent KEYCODE_POWER"),发现死活没反应,设备也root了。后来发现需要su权限,然后就可以允许了,代码如下:
public static void executeADBCommands(boolean isRooted, String... commands) {
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec(isRooted ? "su" : "sh", null, null);
os = new DataOutputStream(process.getOutputStream());
for (String command : commands) {
if (command == null) continue;
os.write(command.getBytes());
os.writeBytes(System.getProperty("line.separator"));
os.flush();
}
os.writeBytes("exit" + System.getProperty("line.separator"));
os.flush();
int result = process.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (successResult != null) {
successResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
}
调用的时候:
CommonUtils.executeADBCommands(true, "input keyevent KEYCODE_POWER");
这样就能做到息屏亮屏了。