android如何實(shí)現(xiàn)運(yùn)行底層linux外部命令
android如何實(shí)現(xiàn)運(yùn)行底層linux外部命令
Android繼承了Linux權(quán)限嚴(yán)格的優(yōu)點(diǎn),那么大家知道android如何實(shí)現(xiàn)運(yùn)行底層linux外部命令嗎?下文學(xué)習(xí)啦小編就分享了android實(shí)現(xiàn)運(yùn)行底層linux外部命令的方法,希望對(duì)大家有所幫助。
android實(shí)現(xiàn)運(yùn)行底層linux外部命令方法
android的底層實(shí)際是Linux內(nèi)核,當(dāng)然在shell環(huán)境下可以運(yùn)行l(wèi)inux命令,尤其是經(jīng)過root處理的android系統(tǒng),基本上可以通過調(diào)用linux命令完全控制手機(jī),下面的RootCmd.java代碼就是實(shí)現(xiàn)運(yùn)行l(wèi)inux外部命令。
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
{
//執(zhí)行l(wèi)inux命令并且輸出結(jié)果
protected static Vector execRootCmd(String paramString)
{
Vector localVector = new Vector();
try
{
Process localProcess = Runtime.getRuntime().exec("su ");//經(jīng)過Root處理的android系統(tǒng)即有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();
}
}
//執(zhí)行l(wèi)inux命令但不關(guān)注結(jié)果輸出
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();
}
}
//判斷機(jī)器Android是否已經(jīng)root,即是否獲取root權(quán)限
protected static boolean haveRoot()
{
int i = execRootCmdSilent("echo test"); //通過執(zhí)行測(cè)試命令來檢測(cè)
if (i != -1) return true;
retrun false;
}
}
android如何實(shí)現(xiàn)運(yùn)行底層linux外部命令相關(guān)文章: