给root用户访问android应用程序

时间:2013-02-26 10:24:24

标签: android

我正在构建一个应用程序,它必须获取超级用户权限才能在/ 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;
       }

如何获取root权限以便我可以更新数据库文件??

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

除非设备已植根,否则Root无法在正常条件下实现。您不能强制您的应用程序在非根条件之外使用root。请研究根本意味着什么。