Android繼承了Linux權限嚴格的優點,那麼大家知道android如何實現運行底層linux外部命令嗎?下文學習啦小編就分享了android實現運行底層linux外部命令的方法,希望對大家有所幫助。
android實現運行底層linux外部命令方法
android的底層實際是Linux內核,當然在shell環境下可以運行linux命令,尤其是經過root處理的android系統,基本上可以通過調用linux命令完全控制手機,下面的RootCmd.java代碼就是實現運行linux外部命令。
package my.android.code;
import android.os.Environment;
import dalvik.annotation.Signature;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
public final class RootCmd
{
//執行linux命令並且輸出結果
protected static Vector execRootCmd(String paramString)
{
Vector localVector = new Vector();
try
{
Process localProcess = Runtime.getRuntime().exec("su ");//經過Root處理的android系統即有su命令
OutputStream localOutputStream = localProcess.getOutputStream();
DataOutputStream localDataOutputStream = new DataOutputStream(localOutputStream);
InputStream localInputStream = localProcess.getInputStream();
DataInputStream localDataInputStream = new DataInputStream(localInputStream);
String str1 = String.valueOf(paramString);
String str2 = str1 + "\n";
localDataOutputStream.writeBytes(str2);
localDataOutputStream.flush();
String str3 = localDataInputStream.readLine();
localVector.add(str3);
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localProcess.waitFor();
return localVector;
}
catch (Exception localException)
{
localException.printStackTrace();
}
}
//執行linux命令但不關注結果輸出
protected static int execRootCmdSilent(String paramString)
{
try
{
Process localProcess = Runtime.getRuntime().exec("su");
Object localObject = localProcess.getOutputStream();
DataOutputStream localDataOutputStream = new DataOutputStream((OutputStream)localObject);
String str = String.valueOf(paramString);
localObject = str + "\n";
localDataOutputStream.writeBytes((String)localObject);
localDataOutputStream.flush();
localDataOutputStream.writeBytes("exit\n");
localDataOutputStream.flush();
localProcess.waitFor();
localObject = localProcess.exitValue();
return localObject;
}
catch (Exception localException)
{
localException.printStackTrace();
}
}
//判斷機器Android是否已經root,即是否獲取root權限
protected static boolean haveRoot()
{
int i = execRootCmdSilent("echo test"); //通過執行測試命令來檢測
if (i != -1) return true;
retrun false;
}
}