有时候我们写 Android APP,需要让它获取 ROOT 权限,那么如何让 APP 去向系统申请呢?下面提供一个方法,前提是系统是已经 ROOT 权限了,能够执行能 su 命令。如果不能,可以参考上一篇: 获取Android系统的ROOT权限 。
1. 首先编写一个 SystemManager 类。
01
|
package net.nowamagic.magicapp_v17;
|
02
|
03
|
import java.io.DataOutputStream;
|
04
|
05
|
import android.app.Activity;
|
06
|
import android.util.Log;
|
07
|
08
|
public class SystemManager extends Activity {
|
09
|
|
10
|
/**
|
11
|
* 应用程序运行命令获取 Root权限,设备必须已破解(获得ROOT权限)
|
12
|
* @param command 命令:String apkRoot="chmod 777 "+getPackageCodePath(); RootCommand(apkRoot);
|
13
|
* @return 应用程序是/否获取Root权限
|
14
|
*/
|
15
|
public static boolean RootCommand(String command)
|
16
|
{
|
17
|
Process process = null ;
|
18
|
DataOutputStream os = null ;
|
19
|
try
|
20
|
{
|
21
|
process = Runtime.getRuntime().exec( "su" );
|
22
|
os = new DataOutputStream(process.getOutputStream());
|
23
|
os.writeBytes(command + "\n" );
|
24
|
os.writeBytes( "exit\n" );
|
25
|
os.flush();
|
26
|
process.waitFor();
|
27
|
} catch (Exception e)
|
28
|
{
|
29
|
Log.d( "*** DEBUG ***" , "ROOT REE" + e.getMessage());
|
30
|
return false ;
|
31
|
} finally
|
32
|
{
|
33
|
try
|
34
|
{
|
35
|
if (os != null )
|
36
|
{
|
37
|
os.close();
|
38
|
}
|
39
|
process.destroy();
|
40
|
} catch (Exception e)
|
41
|
{
|
42
|
}
|
43
|
}
|
44
|
Log.d( "*** DEBUG ***" , "Root SUC " );
|
45
|
return true ;
|
46
|
}
|
47
|
|
48
|
}
|
2. 然后在 MainActivity 中加入这么两句:
01
|
public class MainActivity extends Activity
|
02
|
{
|
03
|
public void onCreate(Bundle savedInstanceState)
|
04
|
{
|
05
|
super .onCreate(savedInstanceState);
|
06
|
setContentView(R.layout.main);
|
07
|
String apkRoot= "chmod 777 " +getPackageCodePath();
|
08
|
SystemManager.RootCommand(apkRoot);
|
09
|
}
|
10
|
}
|
运行 APP,即可向系统申请 ROOT 权限了。
http://www.nowamagic.net/academy/detail/50282009