[Code block] Android code executes ADB instructions

In some cases, such as modifying the Ethernet IP address, modifying the system time, etc., it is much more convenient to use the ADB command to execute directly. The disadvantage is that sometimes Root permissions are required. But if you are doing industrial equipment development, you have no problem if you have the authority (for example, me).

public String execRootCmd(String cmd) {
    
    
	StringBuilder result = new StringBuilder();
	BufferedReader bufferedReader = null;
	DataOutputStream dos = null;
	String receive;

	try {
    
    
		Process p = Runtime.getRuntime().exec("su");// 经过Root处理的android系统即有su命令
		bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
		dos = new DataOutputStream(p.getOutputStream());
		dos.writeBytes(cmd + "\n");
		dos.flush();
		dos.writeBytes("exit\n");
		dos.flush();

		while ((receive = bufferedReader.readLine()) != null) {
    
    
			result.append("\n").append(receive);
		}

		p.waitFor();
	} catch (Exception e) {
    
    
		e.printStackTrace();
	} finally {
    
    
		if (dos != null) {
    
    
			try {
    
    
				dos.close();
			} catch (IOException e) {
    
    
				e.printStackTrace();
			}
		}
		if (bufferedReader != null) {
    
    
			try {
    
    
				bufferedReader.close();
			} catch (IOException e) {
    
    
				e.printStackTrace();
			}
		}
	}
	
	return result.toString();
}

Also attach personal ADB commands commonly used

Guess you like

Origin blog.csdn.net/qq_36881363/article/details/105429435