Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 程式如何判斷手機是否已取得 Root 權限

編輯:關於 Android 程式設計

有些功能非得要 root 才能動,例如自動安裝、系統層級的檔案操作等等。既然功能依賴 root,那在呼叫之前就得先確認環境是否具備條件,否則只會拿到一堆例外。以下整理幾種實務上常見的判斷思路。

方法一:多重條件輪流檢查

/**
* @author Kevin Kowalewski
*
*/
public class Root {

private static String LOG_TAG = Root.class.getName();

public boolean isDeviceRooted() {
if (checkRootMethod1()){return true;}
if (checkRootMethod2()){return true;}
if (checkRootMethoD3()){return true;}
return false;
}

public boolean checkRootMethod1(){
String buildTags = android.os.Build.TAGS;

if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}

public boolean checkRootMethod2(){
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
} catch (Exception e) { }

return false;
}

public boolean checkRootMethod3() {
if (new ExecShell().executeCommand(SHELL_CMD.check_su_binary) != null){
return true;
}else{
return false;
}
}
}
/**
* @author Kevin Kowalewski
*
*/
public class ExecShell {

private static String LOG_TAG = ExecShell.class.getName();

public static enum SHELL_CMD {
check_su_binary(new String[] {"/system/xbin/which","su"}),
;

String[] command;

SHELL_CMD(String[] command){
this.command = command;
}
}

public ArrayList<String> executeCommand(SHELL_CMD shellCmd){
String line = null;
ArrayList<String> fullResponse = new ArrayList<String>();
Process localProcess = null;

try {
localProcess = Runtime.getRuntime().exec(shellCmd.command);
} catch (Exception e) {
return null;
//e.printStackTrace();
}

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));

try {
while ((line = in.readLine()) != null) {
Log.d(LOG_TAG, "--> Line received: " + line);
fullResponse.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}

Log.d(LOG_TAG, "--> Full response was: " + fullResponse);

return fullResponse;
}

}

三個判斷點各有所長:Build.TAGS 裡是否帶有 test-keys、系統目錄下是否存在 Superuser.apk、以及執行 which su 能不能找到 su 二進位檔。任一個成立就視為已 root。這份範例出自 Stack Overflow,向原作者致敬。

方法二:借助 RootTools 這類現成函式庫

開源專案 RootTools 把這些細節都包好了:

RootTools.isRootAvailable() 用來判斷環境是否已 root;RootTools.isAccessGiven() 則更进一步,回傳 true 代表手機已 root,而且你的 App 也確實拿到了授權。

String commandToExecute = "su";
executeShellCommand(commandToExecute);
private boolean executeShellCommand(String command){
Process process = null;
try{
process = Runtime.getRuntime().exec(command);
return true;
} catch (Exception e) {
return false;
} finally{
if(process != null){
try{
process.destroy();
}catch (Exception e) {
}
}
}
}

最後提醒一個實務上的坑:有回覆指出,直接 exec("su") 這種探測方式在某些機型上會帶來嚴重的效能副作用——每啟動一次就多留一個僵死行程佔著記憶體,手機會越用越慢。若只是要判斷環境,建議優先採用讀取 Build 標籤或查檔案這類不產生行程的做法,並把結果快取起來,別在每次呼叫功能時都重跑一遍。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved