0

我正在构建一个应用程序,它必须具有超级用户权限才能在 /data 目录中写入修改数据库文件的内容。我写了一些代码来获得 root 访问权限,但它在日志中给了我不能“获得 root 访问权限或被用户拒绝”

我的代码是

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(canRunRootCommands())
            Toast.makeText(this, "Can Run Root Commands", Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

     public static boolean canRunRootCommands()
       {
          boolean retval = false;
          Process suProcess;

          try
          {
             suProcess = Runtime.getRuntime().exec("su");

             DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
             DataInputStream osRes = new DataInputStream(suProcess.getInputStream());

             if (null != os && null != osRes)
             {
                // Getting the id of the current user to check if this is root
                os.writeBytes("id\n");
                os.flush();

                String currUid = osRes.readLine();
                boolean exitSu = false;
                if (null == currUid)
                {
                   retval = false;
                   exitSu = false;
                   Log.d("ROOT", "Can't get root access or denied by user");
                }
                else if (true == currUid.contains("uid=0"))
                {
                   retval = true;
                   exitSu = true;
                   Log.d("ROOT", "Root access granted");
                }
                else
                {
                   retval = false;
                   exitSu = true;
                   Log.d("ROOT", "Root access rejected: " + currUid);
                }

                if (exitSu)
                {
                   os.writeBytes("exit\n");
                   os.flush();
                }
             }
          }
          catch (Exception e)
          {
             // Can't get root !
             // Probably broken pipe exception on trying to write to output stream (os) after su failed, meaning that the device is not rooted

             retval = false;
             Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());
          }

          return retval;
       }

如何获得对a的root访问权限,以便我可以更新数据库文件?

4

2 回答 2

0

使用该RootTools库,它使root更容易,您不需要使用Process和使用大量代码。

于 2015-09-06T00:28:27.380 回答
-1

除非设备已植根,否则在正常情况下无法获得根。您不能强制您的应用程序在非根条件之外拥有根。请研究根的含义。

于 2015-09-06T00:33:26.927 回答