Determine if running on a rooted device

后端 未结 24 2521
無奈伤痛
無奈伤痛 2020-11-22 06:43

My app has a certain piece of functionality that will only work on a device where root is available. Rather than having this feature fail when it is used (and then show an a

24条回答
  •  时光取名叫无心
    2020-11-22 06:55

    You can do this by following code :

    boolean root;
        String[] su_paths = {"/system/app/Superuser.apk",  "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su","/sbin/su",
                         "/data/local/su", "/su/bin/su","/system/bin/failsafe/su"};
                for (String path : su_paths)
                    if (new File(path).exists()) 
                           root = true;
        
    

    This solution will work in maximum cases.

    Alternate solution (not advisable to use it due to memory usage)

    boolean rooted=true;
            try {
                  Process process = Runtime.getRuntime().exec("su"); 
                  Toast.makeText(getApplicationContext(), "Device is rooted", Toast.LENGTH_SHORT).show();                
                } 
                catch(IOException e){
                  rooted=false;
                  Toast.makeText(getApplicationContext(), "Device is not rooted", Toast.LENGTH_SHORT).show();
                  e.printStackTrace();
                }
    

    If device is rooted then "su" command will be executed otherwise it will throw an exception, through that we can determine whether device is rooted or not. You can also check this library RootBeer.

提交回复
热议问题