/**
* 执行命令并且输出结果
*/
fun execRootCmd(cmd: String): String? {
var result: String? = ""
var dos: DataOutputStream? = null
var dis: DataInputStream? = null
try {
val p = Runtime.getRuntime().exec("su") // 经过Root处理的android系统即有su命令
dos = DataOutputStream(p.outputStream)
dis = DataInputStream(p.inputStream)
Log.i(“zlz”, cmd)
dos.writeBytes("""
$cmd
""".trimIndent())
dos.flush()
dos.writeBytes("exit\n")
dos.flush()
var line: String? = null
while (dis.readLine().also { line = it } != null) {
Log.d("result", line)
result += line
}
p.waitFor()
} catch (e: java.lang.Exception) {
e.printStackTrace()
} finally {
if (dos != null) {
try {
dos.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
if (dis != null) {
try {
dis.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
return result
}
/**
* 执行命令但不关注结果输出
*/
fun execRootCmdSilent(cmd: String): Int {
var result = -1
var dos: DataOutputStream? = null
try {
val p = Runtime.getRuntime().exec("su")
dos = DataOutputStream(p.outputStream)
Log.e("zlz", cmd)
dos.writeBytes("""
$cmd
""".trimIndent())
dos.flush()
dos.writeBytes("exit\n")
dos.flush()
p.waitFor()
result = p.exitValue()
} catch (e: java.lang.Exception) {
e.printStackTrace()
} finally {
if (dos != null) {
try {
dos.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
return result
}
然后调用该方法:
不需要输入 adb shell ,直接输入命令就行
val commend = "input swipe 200 600 200 50 \n"
val result = execRootCmdSilent(commend)
完整代码
?
@SuppressLint("Wakelock", "InvalidWakeLockTag")
fun wakeUpAndUnlock(context: Context) {
// 获取电源管理器对象
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
// 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是调试用的Tag
val wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
or PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright")
// 点亮屏幕
wl.acquire()
// 释放
wl.release()
// 得到键盘锁管理器对象
val km = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
val kl = km.newKeyguardLock("unLock")
// 解锁
kl.disableKeyguard()
// val commend = "adb shell input keyevent 82 \n"
val commend = "input swipe 200 600 200 50 \n"
val result = execRootCmdSilent(commend)
}
|