且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android应用程序获取ROOT权限的方法(android中如何通过代码检测是否有root权限?)

更新时间:2022-01-22 04:31:37

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        doSU();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        doSU();
    }

    private void doSU() {
        try {
            Process process = Runtime.getRuntime().exec("su");// (这里执行是系统已经开放了root权限,而不是说通过执行这句来获得root权限)
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
//            os.writeBytes("ifconfig eth0 192.168.18.122\n");
            os.writeBytes("exit\n");
            os.flush();
            /*
             * //如果已经root,但是用户选择拒绝授权,e.getMessage() = write failed: EPIPE (Broken pipe)  
 //如果没有root,,e.getMessage()= Error running exec(). Command: [su] Working Directory: null Environment: null  
             */
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @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;
    }

}