Android 设备节点操作
1. 获取root权限操作节点
public boolean execSuCmd(String cmd){ if(isRoot()){ Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(cmd + "\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { Log.e(TAG, "ROOT REE" + e.getMessage()); return false; } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { } } Log.d(TAG, "Root SUC "); return true; }else{ return false; } } public void smdtGetSystemLogcat(String folderPath){ } public int smdtSetControl(int type, int values){ return 0; } /** * 判断手机是否ROOT */ private static boolean isRoot() { boolean root = false; try { if ((!new File("/system/bin/su").exists()) && (!new File("/system/xbin/su").exists())) { root = false; } else { root = true; } } catch (Exception e) { Log.e(TAG, "isRoot " + e.getMessage()); } return root; } private static String execRootCmd(String cmd) { String result = ""; DataOutputStream dos = null; DataInputStream dis = null; try { Process p = Runtime.getRuntime().exec("su");// 经过Root处理的android系统即有su命令 dos = new DataOutputStream(p.getOutputStream()); dis = new DataInputStream(p.getInputStream()); Log.d(TAG, cmd); dos.writeBytes(cmd + "\n"); dos.flush(); dos.writeBytes("exit\n"); dos.flush(); String line = null; while ((line = dis.readLine()) != null) { Log.d(TAG,"result="+line); result += line; } p.waitFor(); } catch (Exception e) { e.printStackTrace(); } finally { if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } if (dis != null) { try { dis.close(); } catch (IOException e) { e.printStackTrace(); } } } Log.d(TAG,result); return result; }
2. IO 操作的 读方法
/** * 获取节点 */ private static String getString(String path) { String prop = "waiting";// 默认值 try { BufferedReader reader = new BufferedReader(new FileReader(path)); prop = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return prop; }
写方法
private static final String WAKE_PATH = "/sys/class/demo/wake"; ...... try { BufferedWriter bufWriter = null; bufWriter = new BufferedWriter(new FileWriter(WAKE_PATH)); bufWriter.write("1"); // 写操作 bufWriter.close(); Toast.makeText(getApplicationContext(), "功能已激活",Toast.LENGTH_SHORT).show(); Log.d(TAG,"功能已激活 angle " + getString(ANGLE_PATH)); } catch (IOException e) { e.printStackTrace(); Log.e(TAG,"can't write the " + WAKE_PATH); }