1. 程式人生 > >Android Java執行Shell命令

Android Java執行Shell命令

2、使用

(2) 呼叫上面介紹的execCommand函式,

注意有些命令可能執行時間較長,所以最好線上程中執行execCommand

3、使用場景

以目前自己的幾個場景舉下例子

(1) 靜默安裝和解除安裝

這個很多朋友已經用過了Android root許可權靜默安裝或解除安裝應用,原理是執行命令:pm install apkFilePath及pm uninstall packageName

(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

程式碼如下:

Java
123456List<String>commnandList=newArrayList<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) 拷貝檔案

原理是執行命令:

mount -o rw,remount /system

cp /mnt/sdcard/xx.apk /system/app/

程式碼如下:

Java
1 2 String[]commands=newString[]{"mount -o rw,remount /system","cp /mnt/sdcard/xx.apk /system/app/"}; CommandResult result=ShellUtils.execCommand(commands,true);

注意一般拷貝檔案是不需要root的,上面用root是因為需要拷貝到/system/app/下面