root权限

引用:http://www.pocketdigi.com/20110719/408.html

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.pocketdigi;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.os.Bundle;
 
public class RootActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DataInputStream stream;
        if(isRooted()){
        try {
			stream = Terminal("ping -c 2 www.pocketdigi.com");
			//其实ping并不需要root权限 ,这里是ping 2次后才停止,所以启动后需要一点时间才会有显示
			//你可以自己换成需要root权限的命令试试
			String temp;
			while((temp=stream.readLine())!=null){
				System.out.println(temp);
				//循环输出返回值
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        }
    }
    public DataInputStream Terminal(String command) throws Exception
    {
        Process process = Runtime.getRuntime().exec("su");
        //执行到这,Superuser会跳出来,选择是否允许获取最高权限
        OutputStream outstream = process.getOutputStream();
        DataOutputStream DOPS = new DataOutputStream(outstream);
        InputStream instream = process.getInputStream();
        DataInputStream DIPS = new DataInputStream(instream);
        String temp = command + "\n";
        //加回车
        DOPS.writeBytes(temp);
        //执行
        DOPS.flush();
        //刷新,确保都发送到outputstream
        DOPS.writeBytes("exit\n");
        //退出
        DOPS.flush();
        process.waitFor();
        return DIPS;
    }
    public boolean isRooted() {
    	//检测是否ROOT过
    	DataInputStream stream;
        boolean flag=false;
		try {
			stream = Terminal("ls /data/");
			//目录哪都行,不一定要需要ROOT权限的
			if(stream.readLine()!=null)flag=true;
			//根据是否有返回来判断是否有root权限
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
 
		}
 
    	return flag;
    }
 
 
}
posted @ 2011-09-26 14:01  镇水古月  阅读(205)  评论(0编辑  收藏  举报