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, 不然打印结果是不会出来的
  • 相关阅读:
    在 IdentityServer4 中创建客户端
    IdentityServer4 快速上手
    GraphQL Part IV: 浏览器内的 IDE
    GraphQL Part VII: 实现数据变更
    GraphQL Part VIII: 使用一对多查询
    GraphQL Part VI: 使用 Postgres 和 EF Core 持久化数据
    GraphQL Part V: 字段,参数和变量
    GraphQL Part III: 依赖注入
    GraphQL Part II: 中间件
    GraphQL Part I: hello, world.
  • 原文地址:https://www.cnblogs.com/mengdao/p/14544660.html
Copyright © 2011-2022 走看看