1. 程式人生 > >Android利用root許可權開關機、休眠和喚醒

Android利用root許可權開關機、休眠和喚醒

    在android的裝置中如果我們想重啟手機或者關機或,一般是需要在原始碼的環境下編譯apk,並賦予其相應地系統許可權,而如果想喚醒裝置則需要wakelack。原始碼編譯APP還是比較麻煩的,不過由於android的核心屬於linux,那麼在獲取root許可權的android裝置商自然可以使用linux的開關機,喚醒休眠命令。

    (1)重啟裝置

	public void restart() {	  
		try {
			Process process = Runtime.getRuntime().exec("su");
			DataOutputStream out = new DataOutputStream(
					process.getOutputStream());
			out.writeBytes("reboot \n");
			out.writeBytes("exit\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
首先獲取root許可權,然後直接呼叫linux的reboot,android裝置會立即重啟。

    (2)休眠裝置

	public void hibernate(){
		try {
			Process process = Runtime.getRuntime().exec("su");
			DataOutputStream out = new DataOutputStream(
					process.getOutputStream());
			out.writeBytes("echo mem > /sys/power/state \n");
			out.writeBytes("exit\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    (3)喚醒裝置
	public void wakeup(){
		try {
			Process process = Runtime.getRuntime().exec("su");
			DataOutputStream out = new DataOutputStream(
					process.getOutputStream());
			out.writeBytes("echo on > /sys/power/state \n");
			out.writeBytes("exit\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		KeyguardManager keyguardManager = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
		KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("");
		keyguardLock.disableKeyguard();
	}
    (4)裝置關機
	private void shutdown() {
		try {
			Process process = Runtime.getRuntime().exec("su");
			DataOutputStream out = new DataOutputStream(
					process.getOutputStream());
			out.writeBytes("reboot -p\n");
			out.writeBytes("exit\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}