Android代码中运行shell命令
16lz
2021-01-23
/** * Android shell 命令执行器,支持无限个命令串型执行(需要有root权限!!) * *
* HOW TO USE? * Example:修改开机启动动画。把/sdcard/Download目录下的bootanimation.zip文件拷贝到 * /system/media目录下并修改bootanimation.zip的权限为777。 *
*
* int result = new ShellCommandExecutor() * .addCommand("mount -o remount,rw /system") * .addCommand("cp /sdcard/Download/bootanimation.zip /system/media") * .addCommand("cd /system/media") * .addCommand("chmod 777 bootanimation.zip") * .execute(); * * * @author AveryZhong. */public class ShellCommandExecutor { private static final String TAG = "ShellCommandExecutor"; private StringBuilder mCommands; public ShellCommandExecutor() { mCommands = new StringBuilder(); } public int execute() { return execute(mCommands.toString()); } public ShellCommandExecutor addCommand(String cmd) { if (TextUtils.isEmpty(cmd)) { throw new IllegalArgumentException("command can not be null."); } mCommands.append(cmd); mCommands.append("\n"); return this; } private static int execute(String command) { int result = -1; DataOutputStream dos = null; try { Process p = Runtime.getRuntime().exec("su"); dos = new DataOutputStream(p.getOutputStream()); Log.i(TAG, command); dos.writeBytes(command + "\n"); dos.flush(); dos.writeBytes("exit\n"); dos.flush(); p.waitFor(); result = p.exitValue(); } catch (Exception e) { e.printStackTrace(); } finally { if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }}
更多相关文章
- Android命令行测试BT,WIFI,Sensor工作状态
- Android官方命令深入分析之Device Monitor
- Android pm命令详解
- android permission 访问权限大全
- android1.6新增SD卡写权限WRITE_EXTERNAL_STORAGE
- Android 的一些命令(补充中..)
- Android 程序执行Linux命令的解决方法及注意事项
- android系统权限SET_PREFERRED_APPLICATIONS怎么获取