Android 执行Adb shell 命令大多需要root权限,Android自带的Runtime. getRuntime().exec()容易出错,在网上找到了一个执行adb shell命令的类

代码如下:

/**检查手机是否存在root权限,发送一些消息*/
package com.dx.superbar.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import android.content.Context;

public class RootContext
{
private static RootContext instance = null;
private static Object mLock = new Object();
String mShell;
OutputStream o;
Process p;

private RootContext(String cmd) throws Exception
{
this.mShell = cmd;
init();
}

public static RootContext getInstance()
{
if (instance != null)
{
return instance;
}
synchronized (mLock)
{
try
{
instance = new RootContext("su");
}
catch (Exception e)
{
while (true)
try
{
instance = new RootContext("/system/xbin/su");
}
catch (Exception e2)
{
try
{
instance = new RootContext("/system/bin/su");
}
catch (Exception e3)
{
e3.printStackTrace();
}
}
}
return instance;
}
}

private void init() throws Exception
{
if ((this.p != null) && (this.o != null))
{
this.o.flush();
this.o.close();
this.p.destroy();
}
this.p = Runtime.getRuntime().exec(this.mShell);
this.o = this.p.getOutputStream();
system("LD_LIBRARY_PATH=/vendor/lib:/system/lib ");
}

private void system(String cmd)
{
try
{
this.o.write((cmd + "\n").getBytes("ASCII"));
return;
}
catch (Exception e)
{
while (true)
try
{
init();
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
}

public void runCommand(String cmd)
{
system(cmd);
}

/**
* 判断是否已经root了
* */
public static boolean hasRootAccess(Context ctx)
{
final StringBuilder res = new StringBuilder();
try
{
if (runCommandAsRoot(ctx, "exit 0", res) == 0)
return true;
}
catch (Exception e)
{
}
return false;
}

/**
* 以root的权限运行命令
* */
public static int runCommandAsRoot(Context ctx, String script,
StringBuilder res)
{
final File file = new File(ctx.getCacheDir(), "secopt.sh");
final ScriptRunner runner = new ScriptRunner(file, script, res);
runner.start();
try
{
runner.join(40000);
if (runner.isAlive())
{
runner.interrupt();
runner.join(150);
runner.destroy();
runner.join(50);
}
}
catch (InterruptedException ex)
{
}
return runner.exitcode;
}

private static final class ScriptRunner extends Thread
{
private final File file;
private final String script;
private final StringBuilder res;
public int exitcode = -1;
private Process exec;

public ScriptRunner(File file, String script, StringBuilder res)
{
this.file = file;
this.script = script;
this.res = res;
}

@Override
public void run()
{
try
{
file.createNewFile();
final String abspath = file.getAbsolutePath();
Runtime.getRuntime().exec("chmod 777 " + abspath).waitFor();
final OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(file));
if (new File("/system/bin/sh").exists())
{
out.write("#!/system/bin/sh\n");
}
out.write(script);
if (!script.endsWith("\n"))
out.write("\n");
out.write("exit\n");
out.flush();
out.close();

exec = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(
exec.getOutputStream());
os.writeBytes(abspath);
os.flush();
os.close();

InputStreamReader r = new InputStreamReader(
exec.getInputStream());
final char buf[] = new char[1024];
int read = 0;
while ((read = r.read(buf)) != -1)
{
if (res != null)
res.append(buf, 0, read);
}

r = new InputStreamReader(exec.getErrorStream());
read = 0;
while ((read = r.read(buf)) != -1)
{
if (res != null)
res.append(buf, 0, read);
}

if (exec != null)
this.exitcode = exec.waitFor();
}
catch (InterruptedException ex)
{
if (res != null)
res.append("\nOperation timed-out");
}
catch (Exception ex)
{
if (res != null)
res.append("\n" + ex);
}
finally
{
destroy();
}
}

public synchronized void destroy()
{
if (exec != null)
exec.destroy();
exec = null;
}
}
}

Android 执行 adb shell 命令的更多相关文章

  1. Android 通过adb shell命令查看内存,CPU,启动时间,电量等信息

    Android 通过adb shell命令查看内存,CPU,启动时间,电量等信息   by:授客 QQ:1033553122 1.  查看内存信息 1)查看所有内存信息 命令: dumpsys mem ...

  2. Android 常用adb shell 命令

    原文地址http://blog.csdn.net/rain_butterfly/article/details/40894807 调试Android程序有时需要adb shell 命令,adb全称An ...

  3. Android 常用adb shell 命令(转)

    调试Android程序有时需要adb shell 命令,adb全称Android Debug Bridge ,就是起到调试桥的作用. 通过adb我们可以在Eclipse中通过DDMS来调试Androi ...

  4. 【Android】-- adb shell 命令探索

    ADB是什么,做android开发的没有不知道的. window下执行cmd,输入adb help就会打印adb都可以做的事情,包含 adb push ..adb pull .. adb device ...

  5. Android 通过adb shell命令查看内存,CPU,启动时间,电量等信息

    1.  查看内存信息 1)查看所有内存信息 命令: dumpsys meminfo 例: C:\Users\laiyu>adb shell shell@android:/ $ dumpsys m ...

  6. Android:adb shell 命令详解

    安卓系统是基于Linux系统开发,也就支持常见的Linux的命令,这些命令都保存在手机“/system/bin”的目录下,通过adb shell 便可以调用这些命令. 进入“/system/bin”该 ...

  7. Android自动化----adb shell,appium,uiautomator2

    1.区别 1,adb shell脚本的方式 不但可以在有电脑的情况下使用,通过数据线连接电脑然后adb shell命令,而且还可以打包成app,在手机的终端使用adb shell命令. 2,appiu ...

  8. 【原创】Android开发之ADB及ADB SHELl命令的应用

    adb的全称为Android Debug Bridge,就是起到调试桥的作用.通过adb我们可以在Eclipse中方面通过DDMS来调试Android程序,说白了就是debug工具.adb的工作方式比 ...

  9. Android成长记(1)-----android环境搭建与adb shell 命令

    整理一下学习android一步一步存下来的自己总结或是从网上摘抄的比较不错的文档,电脑要上交了,最舍不得的就是自己积累的这么点东西了,所以决定发布到黎梓小站,以供大家一起学习以及自己日后忘记了也有地方 ...

随机推荐

  1. FreeRTOS--堆内存管理

    因为项目需要,最近开始学习FreeRTOS,一开始有些紧张,因为两个星期之前对于FreeRTOS的熟悉度几乎为零,经过对FreeRTOS官网的例子程序的摸索,和项目中问题的解决,遇到了很多熟悉的身影, ...

  2. eclipse中将本地项目上传到svn库

    转载文章:http://blog.csdn.net/singit/article/details/48972197

  3. page 简单易懂 分页

    基础分页功能 <?php class Page{  //$count是用户设定的值      public $a;    function pages($count,$page_num,$url ...

  4. PHP扩展代码结构详解

    PHP扩展代码结构详解: 这个是继:使用ext_skel和phpize构建php5扩展  内容 (拆分出来) Zend_API:深入_PHP_内核:http://cn2.php.net/manual/ ...

  5. hicoder1142 三分求极值

    在直角坐标系中有一条抛物线y=ax^2+bx+c和一个点P(x,y),求点P到抛物线的最短距离d. 我们代入公式,有: $d = min(\sqrt{(X - x)^2+(aX^2+bX+c-y)^2 ...

  6. 自己动手写http服务器——线程池(一)

    创建一个线程池,每有一个连接对象就将它添加到工作队列中,线程池中的线程通过竞争来取得任务并执行它(它是通过信号量实现的). //filename threadpool.h #ifndef THREAD ...

  7. JaveScript变量的简介及其变量的简单使用(JS知识点归纳一)

    变量简介 "变量是一个容器" 为什么要有变量? 程序的执行过程中,会使用到许多的数据(用户输入的内容,动态效果的运动数据等),当这些数据需要重复在多个地方使用的时候,就需要一个容器 ...

  8. JavaScript面向对象编程(9)高速构建继承关系之整合原型链

    前面我们铺垫了非常多细节.是为了让大家更加明晰prototype的使用细节: 如今能够将前面的知识整合起来,写一个函数用于高速构建基于原型链的继承关系了: function extend(Child, ...

  9. 学习vi和vim编辑器(5):越过基础的藩篱

    本章将对之前学习的编辑命令如" c "." d "." y "等命令进行总结,并学习一些新的知识:其它进入vi的方法,利用缓冲区来存储拖曳或 ...

  10. python的unittest測试框架的扩展浅谈

    非常多时候測试框架须要依据測试数据来自己主动生成測试用例脚本,比方接口測试,通过不同參数构建组合去请求接口,然后验证返回结果.假设这样能通过配置excel数据来驱动測试.而不用去写一大堆的測试用例脚本 ...