android如何实现运行底层linux外部命令
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;
}
}
android如何实现运行底层linux外部命令相关文章: