当前位置: 首页 > 编程笔记 >

Android 开发中使用Linux Shell实例详解

杨飞飙
2023-03-14
本文向大家介绍Android 开发中使用Linux Shell实例详解,包括了Android 开发中使用Linux Shell实例详解的使用技巧和注意事项,需要的朋友参考一下

Android 开发中使用Linux Shell实例详解

引言

Android系统是基于Linux内核运行的,而做为一名Linux粉,不在Android上面运行一下Linux Shell怎么行呢?

最近发现了一个很好的Android Shell工具代码,在这里分享一下。

Shell核心代码

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * ShellUtils
 * <ul>
 * <strong>Check root</strong>
 * <li>{@link ShellUtils#checkRootPermission()}</li>
 * </ul>
 * <ul>
 * <strong>Execte command</strong>
 * <li>{@link ShellUtils#execCommand(String, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String, boolean, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(List, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(List, boolean, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String[], boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String[], boolean, boolean)}</li>
 * </ul>
 */
public class ShellUtils {

  public static final String COMMAND_SU    = "su";
  public static final String COMMAND_SH    = "sh";
  public static final String COMMAND_EXIT   = "exit\n";
  public static final String COMMAND_LINE_END = "\n";

  private ShellUtils() {
    throw new AssertionError();
  }

  /**
   * check whether has root permission
   * 
   * @return
   */
  public static boolean checkRootPermission() {
    return execCommand("echo root", true, false).result == 0;
  }

  /**
   * execute shell command, default return result msg
   * 
   * @param command command
   * @param isRoot whether need to run with root
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(String command, boolean isRoot) {
    return execCommand(new String[] {command}, isRoot, true);
  }

  /**
   * execute shell commands, default return result msg
   * 
   * @param commands command list
   * @param isRoot whether need to run with root
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(List<String> commands, boolean isRoot) {
    return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, true);
  }

  /**
   * execute shell commands, default return result msg
   * 
   * @param commands command array
   * @param isRoot whether need to run with root
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(String[] commands, boolean isRoot) {
    return execCommand(commands, isRoot, true);
  }

  /**
   * execute shell command
   * 
   * @param command command
   * @param isRoot whether need to run with root
   * @param isNeedResultMsg whether need result msg
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) {
    return execCommand(new String[] {command}, isRoot, isNeedResultMsg);
  }

  /**
   * execute shell commands
   * 
   * @param commands command list
   * @param isRoot whether need to run with root
   * @param isNeedResultMsg whether need result msg
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(List<String> commands, boolean isRoot, boolean isNeedResultMsg) {
    return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, isNeedResultMsg);
  }

  /**
   * execute shell commands
   * 
   * @param commands command array
   * @param isRoot whether need to run with root
   * @param isNeedResultMsg whether need result msg
   * @return <ul>
   *     <li>if isNeedResultMsg is false, {@link CommandResult#successMsg} is null and
   *     {@link CommandResult#errorMsg} is null.</li>
   *     <li>if {@link CommandResult#result} is -1, there maybe some excepiton.</li>
   *     </ul>
   */
  public static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
    int result = -1;
    if (commands == null || commands.length == 0) {
      return new CommandResult(result, null, null);
    }

    Process process = null;
    BufferedReader successResult = null;
    BufferedReader errorResult = null;
    StringBuilder successMsg = null;
    StringBuilder errorMsg = null;

    DataOutputStream os = null;
    try {
      process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
      os = new DataOutputStream(process.getOutputStream());
      for (String command : commands) {
        if (command == null) {
          continue;
        }

        // donnot use os.writeBytes(commmand), avoid chinese charset error
        os.write(command.getBytes());
        os.writeBytes(COMMAND_LINE_END);
        os.flush();
      }
      os.writeBytes(COMMAND_EXIT);
      os.flush();

      result = process.waitFor();
      // get command result
      if (isNeedResultMsg) {
        successMsg = new StringBuilder();
        errorMsg = new StringBuilder();
        successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
        errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String s;
        while ((s = successResult.readLine()) != null) {
          successMsg.append(s);
        }
        while ((s = errorResult.readLine()) != null) {
          errorMsg.append(s);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (os != null) {
          os.close();
        }
        if (successResult != null) {
          successResult.close();
        }
        if (errorResult != null) {
          errorResult.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

      if (process != null) {
        process.destroy();
      }
    }
    return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null
        : errorMsg.toString());
  }

  /**
   * result of command
   * <ul>
   * <li>{@link CommandResult#result} means result of command, 0 means normal, else means error, same to excute in
   * linux shell</li>
   * <li>{@link CommandResult#successMsg} means success message of command result</li>
   * <li>{@link CommandResult#errorMsg} means error message of command result</li>
   * </ul>
   */
  public static class CommandResult {

    /** result of command **/
    public int  result;
    /** success message of command result **/
    public String successMsg;
    /** error message of command result **/
    public String errorMsg;

    public CommandResult(int result) {
      this.result = result;
    }

    public CommandResult(int result, String successMsg, String errorMsg) {
      this.result = result;
      this.successMsg = successMsg;
      this.errorMsg = errorMsg;
    }
  }
}

ShellUtils代码引用自:Trinea

小实例

是否root

public Boolean isRooted(){
  CommandResult cmdResult = ShellUtils.execCommand("su", true);
  if (cmdResult.errorMsg.equals("Permission denied") || cmdResult.result != 0) {

    return false;
  }else{
    return true;
  }
}

复制文件

String[] commands = new String[] { "mount -o rw,remount /system", "cp /mnt/sdcard/xx.apk /system/app/" };

public boolean copyFile(String[] cmdText){
  CommandResult cmdResult = ShellUtils.execCommand(cmdText, true);
  if (cmdResult.errorMsg.equals("Permission denied") || cmdResult.result != 0) {
    return false;
  }else{
    return true;
  }
}

我暂时就举这两个例子,只要你会Shell,什么操作都是可以的。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

 类似资料:
  • 本文向大家介绍Android 开发中Volley详解及实例,包括了Android 开发中Volley详解及实例的使用技巧和注意事项,需要的朋友参考一下 Android 开发中Volley详解及实例 最近在做项目的时候,各种get和post。简直要疯了,我这种啥都不了解的,不知道咋办了,然后百度看了下,可以用volley进行网络请求与获取,下面就介绍下volley的用法。 volley有三种方式:J

  • 本文向大家介绍Android开发之TabActivity用法实例详解,包括了Android开发之TabActivity用法实例详解的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Android开发之TabActivity用法。分享给大家供大家参考,具体如下: 一.简介 TabActivity继承自Activity,目的是让同一界面容纳更多的内容。TabActivity实现标签页的功能,通过

  • 本文向大家介绍Android样式的开发:layer-list实例详解,包括了Android样式的开发:layer-list实例详解的使用技巧和注意事项,需要的朋友参考一下 上图Tab的背景效果,和带阴影的圆角矩形,是怎么实现的呢?大部分的人会让美工切图,用点九图做背景。但是,如果只提供一张图,会怎么样呢?比如,中间的Tab背景红色底线的像素高度为4px,那么,在mdpi设备上显示会符合预期,在hd

  • 本文向大家介绍详解Android开发中ContentObserver类的使用,包括了详解Android开发中ContentObserver类的使用的使用技巧和注意事项,需要的朋友参考一下 ContentObserver——内容观察者,目的是观察(捕捉)特定Uri引起的数据库的变化,继而做一些相应的处理,它类似于 数据库技术中的触发器(Trigger),当ContentObserver所观察的Uri

  • 本文向大家介绍Android Kotlin开发实例(Hello World!)及语法详解,包括了Android Kotlin开发实例(Hello World!)及语法详解的使用技巧和注意事项,需要的朋友参考一下 Android Kotlin开发实例及语法详解 前言 Kotlin是一种在 Java虚拟机上执行的静态型别编程语言,它主要是由俄罗斯圣彼得堡的JetBrains开发团队所发展出来的编程语言

  • 本文向大家介绍Android开发之splash界面下详解及实例,包括了Android开发之splash界面下详解及实例的使用技巧和注意事项,需要的朋友参考一下 现在刚下载的很多APP应用第一次打开都会在进入主界面之前有导航页,用来展示公司logo,或者推广自身这款APP。先上效果图: 首先解释一下:支持进入首页只能往右滑动,中间可以左右滑动,最后一张只能向前滑动,点击立即体验会进入主界面,点击跳过