簡體   English   中英

如何檢查我的應用程序是否已被授予 root 訪問權限?

[英]How to check if my app has been granted root access?

我一直在嘗試很多東西,但我仍然找不到正確的方法來檢查我的應用程序是否具有 root 訪問權限。 這是我嘗試過的:

private boolean isRootGranted() {
    Process p;
    BufferedReader reader = null;
    String line;

    try {
        p = Runtime.getRuntime().exec("su");
        reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while( (line = reader.readLine()) != null) {
            System.out.println(line);
        }

        int result;
        try {
            result = p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
            Toast.makeText(this, "You need to grant root access", Toast.LENGTH_SHORT).show();
            return false;
        }

        if(result != 0) {
            Toast.makeText(this, "You need to grant root access", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(this, "Your device is not rooted", Toast.LENGTH_SHORT).show();
        return false;
    } finally {
        try {
            if(reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果設備沒有 root 或 root 被拒絕,則上面的代碼可以完美運行。 但是,每次授予 root 權限時,它都會卡在 while 循環中。 如果我刪除 while 循環,它就會卡在p.waitFor()

編輯我發現su命令不會產生任何輸出。 但我不知道如果沒有輸出/錯誤產生,為什么它仍然停留在 waitFor() 上。

要檢查您的應用程序是否具有超級用戶權限,您只需嘗試訪問根目錄即可。 我是這樣解決這個問題的:
以下方法檢查是否可以列出根目錄的文件。 如果 shell 命令 ( cd / && ls ) 返回空字符串,則您的應用程序沒有 root 訪問權限並且該方法返回false

public boolean hasRootAccess() {
        try {
            java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(new String[]{"/system/bin/su","-c","cd / && ls"}).getInputStream()).useDelimiter("\\A");
            return !(s.hasNext() ? s.next() : "").equals("");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM