在实际的Android开发中,我们开发的应用可能会需要申请root权限,但应该怎么样写这段代码呢?
这里提供一个申请root权限的类,方便大家使用~
Step1 在Android Studio中新建一个SystemManager.java
类

SystemManager.java
的内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package com.example.lolimay;
import java.io.DataOutputStream;
import android.app.Activity; import android.util.Log;
public class SystemManager extends Activity {
public static boolean RootCommand(String command) { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(command + "\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage()); return false; } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { } } Log.d("*** DEBUG ***", "Root SUC "); return true; } }
|
注意: 第一行的包名要改成自己的(学会变通)
Step2 在MainActivity.java
中添加两行代码
1 2
| String apkRoot="chmod 777 "+getPackageCodePath(); SystemManager.RootCommand(apkRoot);
|

大功告成!打开root后的手机或者root后的模拟器试试把~