主要介紹Android或Java應用中如何以預設使用者或root使用者執行Shell指令,ShellUtils的API介紹、使用及使用場景(如靜默安裝和解除安裝、修改hosts檔案、拷貝檔案)。使用純Java實作,是以對Java程式同樣适用。
1、API介紹
Java
1
public CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg)
其中commands表示依次執行的shell指令數組
isRoot表示是否以su使用者執行(需要手機已經root)
isNeedResultMsg表示是否存儲指令執行成功及失敗後的資訊。
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* result of command
*
* @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2013-5-16
*/
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.successMsg = successMsg;
this.errorMsg = errorMsg;
CommandResult 為傳回的資料結構,如下其中result表示執行的結果,根據linux指令執行規則,0表示成功,其他為相應錯誤碼。
successMsg存儲執行成功後的輸出資訊,errorMsg存儲執行失敗後的輸出資訊。
如果isNeedResultMsg為false,successMsg和errorMsg會始終為空,而result依然為正常結果。
其他接口,Shell指令支援執行String(單個指令), List(多個指令),String[](多個指令)
2、使用
(1)引入公共庫
(2) 調用上面介紹的execCommand函數,
注意有些指令可能運作時間較長,是以最好線上程中執行execCommand
3、使用場景
以目前自己的幾個場景舉下例子
(1) 靜默安裝和解除安裝
(2) 擷取系統設定->存儲->首選安裝位置
原理是執行指令:pm get-install-location
(3) Android修改hosts檔案
原理是執行指令:
mount -o rw,remount /system
echo “127.0.0.1 localhost” > /etc/hosts
echo “185.31.17.184 github.global.ssl.fastly.net” >> /etc/hosts
chmod 644 /etc/hosts
代碼如下:
List<String> commnandList = new ArrayList<String>();
commnandList.add("mount -o rw,remount /system");
commnandList.add("echo \"127.0.0.1 localhost\" > /etc/hosts");
commnandList.add("echo \"185.31.17.184 github.global.ssl.fastly.net\" >> /etc/hosts");
commnandList.add("chmod 644 /etc/hosts");
CommandResult result = ShellUtils.execCommand(commnandList, true);
用echo指令改hosts檔案很牛逼哦,不用重新開機可以直接生效的哦。
(4) 拷貝檔案
cp /mnt/sdcard/xx.apk /system/app/
String[] commands = new String[] { "mount -o rw,remount /system", "cp /mnt/sdcard/xx.apk /system/app/" };
CommandResult result = ShellUtils.execCommand(commands, true);
注意一般拷貝檔案是不需要root的,上面用root是因為需要拷貝到/system/app/下面