Android代码中运行shell命令
16lz
2022-03-09
/** * 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 mtk平台默认输入法
- Android(安卓)framework修改----关屏动画效果
- Android官方命令深入分析之Device Monitor
- 【Android】Android(安卓)9.0 隐藏虚拟按键跟状态栏,除去google
- Android命令行测试BT,WIFI,Sensor工作状态
- 修改android桌面图标默认大小
- Android(安卓)Studio 配置SVN 及 代码管理
- Android中density如何设置
- Android执行shell命令