android (linux)很多命令需要root权限才能执行,比如说查看系统目录文件等,如果我们的程序需要用到查看此类文件或执行系统命令,就必须先获取Root权限。
1. import java.io.DataInputStream;
2. import java.io.DataOutputStream;
3. import java.io.InputStream;
4. import java.io.OutputStream;
5. import android.app.Activity;
6. import android.os.Bundle;
7.
8. public class RootActivity extends Activity {
9.
10. @Override
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.main);
14. DataInputStream stream;
15. if(isRooted()){
16. try {
17. stream = Terminal("ping -c 2 www.pocketdigi.com");
18. //其实ping并不需要root权限 ,这里是ping 2次后才停止,所以启动后需要一点时间才会有显示
19. //你可以自己换成需要root权限的命令试试
20. String temp;
21. while((temp=stream.readLine())!=null){
22. System.out.println(temp);
23. //循环输出返回值
24. }
25. } catch (Exception e1) {
26. // TODO Auto-generated catch block
27. e1.printStackTrace();
28. }
29. }
30. }
31. public DataInputStream Terminal(String command) throws Exception
32. {
33. Process process = Runtime.getRuntime().exec("su");
34. //执行到这,Superuser会跳出来,选择是否允许获取最高权限
35. OutputStream outstream = process.getOutputStream();
36. DataOutputStream DOPS = new DataOutputStream(outstream);
37. InputStream instream = process.getInputStream();
38. DataInputStream DIPS = new DataInputStream(instream);
39. String temp = command + "\n";
40. //加回车
41. DOPS.writeBytes(temp);
42. //执行
43. DOPS.flush();
44. //刷新,确保都发送到outputstream
45. DOPS.writeBytes("exit\n");
46. //退出
47. DOPS.flush();
48. process.waitFor();
49. return DIPS;
50. }
51. public boolean isRooted() {
52. //检测是否ROOT过
53. DataInputStream stream;
54. boolean flag=false;
55. try {
56. stream = Terminal("ls /data/");
57. //目录哪都行,不一定要需要ROOT权限的
58. if(stream.readLine()!=null)flag=true;
59. //根据是否有返回来判断是否有root权限
60. } catch (Exception e1) {
61. // TODO Auto-generated catch block
62. e1.printStackTrace();
63.
64. }
65.
66. return flag;
67. }
68.
69.
70. }
标签:temp,stream,DOPS,DataInputStream,import,Android,权限,ROOT
From: https://blog.51cto.com/u_548275/6237778