zoukankan      html  css  js  c++  java
  • Android代码执行adb shell命令

    好久没写随笔了,几乎忘记了这个技术点,今天特地记录下:

    前提:有系统root权限

    方法一:

    new Thread(new Runnable() {
    @Override
    public void run() {
    String content = "";
    BufferedReader reader = null;
    InputStream is = null;
    try {
    java.lang.Process process = Runtime.getRuntime().exec("adb shell ps | grep NAG");
    is = process.getInputStream();
    reader = new BufferedReader(new InputStreamReader(is));
    StringBuffer output = new StringBuffer();
    int read;
    char[] buffer = new char[4096];
    while ((read = reader.read(buffer)) > 0) {
    output.append(buffer, 0, read);
    }
    content = output.toString();
    VoiceLog.logInfo(TAG, "checkNagNew content " + content);
    } catch (Exception e) {
    e.printStackTrace();
    VoiceLog.logInfo(TAG, "read logcat process failed. message: " + e.getMessage());
    } finally {
    if (null != is) {
    try {
    is.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    if (reader != null) {
    try {
    reader.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }).start();


    方法二:
    new Thread(new Runnable() {
    @Override
    public void run() {
    FileOutputStream os = null;
    Process p = null;
    try {
    p = Runtime.getRuntime().exec("adb shell ps | grep NAG");
    InputStream is = p.getInputStream();
    os = new FileOutputStream("/sdcard/00.log");
    int len = 0;
    byte[] buf = new byte[1024];
    while ((-1 != (len = is.read(buf)))) {
    os.write(buf, 0, len);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }finally {
    try {
    os.flush();
    os.close();
    }catch (Exception e){
    e.printStackTrace();
    }

    }
    }
    }).start();

    PS: 命令要加adb shell, 不然打印结果是不会出来的
  • 相关阅读:
    面试题 31: 求子数组的最大和
    [面试] 结构体占用空间的问题,内存对齐~! 真的懂了,cpu取加快速度,省空间来考虑。
    [计算机] 32768~32767 计算机中的 1 表示
    C#跨线程调用窗体控件
    合并字节数组
    将汉字转化为2位大写的16进制Unicode
    关公与子龙两大杀手
    早年的J2EE笔记
    给小组新成员的一份信
    c++虚函数详解
  • 原文地址:https://www.cnblogs.com/mengdao/p/14544660.html
Copyright © 2011-2022 走看看