To use the root permission in an Android Application, the device that runs the program must have the root permission.
public static boolean runRootCommand(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(TAG, "the device is not rooted, error message: " + e.getMessage()); return false; } finally { try { if (os != null) { os.close(); } if(process != null) { process.destroy(); } } catch (Exception e) { e.printStackTrace(); } } return true; }
If the device has the root permission, the user will be prompted to authorize when the program executes the su command,
To write a small program, you need to obtain the root permission. After searching for it online for a long time, we found that this method is feasible,The device must have been cracked! Able to execute the su command.
1. Create a method: the code is as follows:
Package CN. ycmoon. utility; import Java. io. dataoutputstream; import android. app. activity; import android. util. log; public class systemmanager extends activity {/*** the application program run command to obtain the root permission. The device must have cracked (get the root permission) * @ Param command: string apkroot = "chmod 777" + getpackagecodepath (); rootcommand (apkroot); * @ return application Yes/No get root permission */public static Boolean rootcommand (string command) {Process = NULL; dataout Putstream OS = NULL; try {process = runtime.getruntime(cmd.exe C ("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 ;}}
2. In the mainactivity method of the application: 2. In the mainactivity method of the application:
public class MainActivity extends Activity{ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String apkRoot="chmod 777 "+getPackageCodePath(); SystemManager.RootCommand(apkRoot); }}
In this way, when the application is running, the message dialog box "the application has obtained the root permission" appears"