首届 Google 暑期大学生博客分享大赛——2010 Andriod 篇


目前正在学安卓app开发,希望和大家一起成长,有这方面的高手也希望能一起创业,目前我们在做WiFi相关开发,我们的梦想是“上网不再昂贵”!欢迎你的加入!


BroadcastReceiver模块

用于监听开机信息 并初始化和启动服务


1. package zy.dnh;  
2. import java.io.File;  
3. import java.io.FileOutputStream;  
4. import java.io.IOException;  
5. import android.content.BroadcastReceiver;  
6. import android.content.Context;  
7. import android.content.Intent;  
8. import android.widget.Toast;  
9. publicclass getpowerinfo extends BroadcastReceiver{  
10.     FileOutputStream out;  
11. finalpublic String ONPATH = "/data/data/zy.dnh/on.txt";  
12. @Override
13. publicvoid onReceive(Context context, Intent intent) {  
14. // TODO Auto-generated method stub
15. 
16. if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){  
17. new Intent(context,mService1.class);//启动服务
18.                 bootActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
19. "0,0,0,0,0,0,0,0,0,0,0,0",ONPATH);  
20.                 context.startService(bootActivityIntent);  
21. "Netcounter service has been lauched", Toast.LENGTH_LONG).show();  
22. false);//应用防火墙规则
23. "Wall rules have been lauched", Toast.LENGTH_LONG).show();  
24.          }  
25.     }  
26. publicvoid writefile(String str,String path )  
27.     {  
28.        File file;  
29. try {  
30. //创建文件
31. new File(path);  
32.           file.createNewFile();  
33. 
34. //打开文件file的OutputStream
35. new FileOutputStream(file);  
36.           String infoToWrite = str;  
37. //将字符串转换成byte数组写入文件
38.           out.write(infoToWrite.getBytes());  
39. //关闭文件file的OutputStream
40.           out.close();  
41. 
42. 
43. 
44. catch (IOException e) {  
45. //将出错信息打印到Logcat
46. 
47. 
48.        }


mService1模块

后台服务,用于维护流量日志

1. publicclass mService1 extends Service  
2. {  
3. 
4. 
5. private Handler objHandler = new Handler();  
6. privateint intCounter=0;  
7. privateint mHour;   
8. privateint mMinute;   
9. privateint mYear;   
10. privateint mMonth;   
11. privateint mDay;  
12. private String mdate;  
13. 
14. 
15. finalpublic String DEV_FILE = "/proc/self/net/dev";//系统流量文件
16. "0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  
17. "0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  
18. "0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  
19. "0,0,0,0,0,0,0,0,0,0,0,0";//对应on.txt里面的格式
20. final String ETHLINE="  eth0";//以太网信息所在行
21. final String GPRSLINE="rmnet0";  
22. final String WIFILINE="tiwlan0";  
23. 
24. final String TEXT_ENCODING = "UTF-8";  
25. 
26. finalpublic String ONPATH = "/data/data/zy.dnh/on.txt";  
27. finalpublic String LOGPATH = "/data/data/zy.dnh/log.txt";  
28. 
29. private Runnable mTasks = new Runnable()   
30.     {  
31. 
32. publicvoid run()//运行该服务执行此函数
33.         {  
34.           refresh();  
35. 
36. 
37.           intCounter++;  
38. // DisplayToast("Counter:"+Integer.toString(intCounter));
39. 30000);//每3000毫秒执行一次
40.        }   
41.     };  
42. 
43. @Override
44. publicvoid onStart(Intent intent, int startId)  
45.   {  
46. // TODO Auto-generated method stub
47. //writefile("0,0,0,0,0,0,0,0,0,0,0,0",ONPATH);//每次启动服务 初始化onpath
48. 
49. 0);  
50. super.onStart(intent, startId);  
51.   }  
52. @Override
53. publicvoid onCreate()  
54.   {  
55. // TODO Auto-generated method stub
56. 
57. super.onCreate();  
58.   }  
59. 
60. @Override
61. public IBinder onBind(Intent intent)  
62.   {  
63. // TODO Auto-generated method stub
64. 
65. 
66. returnnull;  
67.   }  
68. @Override
69. publicvoid onDestroy()  
70.   {  
71. // TODO Auto-generated method stub
72. 
73. /*  */
74.     objHandler.removeCallbacks(mTasks);  
75. super.onDestroy();  
76.   }    
77. publicvoid DisplayToast(String str)  
78.   {  
79. this,str,Toast.LENGTH_SHORT).show();  
80.   }    
81. publicvoid readdev()  
82.   {  
83. null;  
84. try {  
85. new FileReader(DEV_FILE);  
86. 
87.           }   
88. catch (FileNotFoundException e) {  
89. "Could not read " + DEV_FILE);  
90. 
91.         }  
92. new BufferedReader(fstream, 500);  
93.        String line;  
94.        String[] segs;  
95.        String[] netdata;  
96. 
97. int count=0;  
98. int k;  
99. int j;  
100. try {  
101. while ((line = in.readLine()) != null) {  
102. ":");  
103. if(line.startsWith(ETHLINE))  
104.                 {  
105. 
106. 1].trim().split(" ");  
107. for(k=0,j=0;k<netdata.length;k++)  
108.                   {  
109. if(netdata[k].length()>0)   
110.                      {   
111. 
112.                           ethdata[j]=netdata[k];  
113.                           j++;  
114.                      }  
115.                   }  
116.               }  
117. elseif(line.startsWith(GPRSLINE))  
118.               {  
119. 
120. 1].trim().split(" ");  
121. for(k=0,j=0;k<netdata.length;k++)  
122.               {  
123. if(netdata[k].length()>0)   
124.                  {   
125. 
126.                       gprsdata[j]=netdata[k];  
127.                       j++;  
128.                  }  
129.               }  
130.               }  
131. elseif(line.startsWith(WIFILINE))  
132.           {  
133. 
134. 1].trim().split(" ");  
135. for(k=0,j=0;k<netdata.length;k++)  
136.                 {  
137. if(netdata[k].length()>0)   
138.                     {   
139. 
140.                       wifidata[j]=netdata[k];  
141.                       j++;  
142.                     }  
143.                 }  
144.           }  
145. 
146. 
147. 
148. 
149.               count++;  
150.           }  
151.           fstream.close();  
152. 
153.         }   
154. catch (IOException e) {  
155.           DisplayToast(e.toString());  
156.         }  
157.   }  
158. public String getinfo(String path)  
159.   {  
160.     File file;  
161. "";   
162.     FileInputStream in;  
163. try{  
164. //打开文件file的InputStream
165. new File(path);  
166. new FileInputStream(file);  
167. //将文件内容全部读入到byte数组
168. int length = (int)file.length();  
169. byte[] temp = newbyte[length];  
170. 0, length);  
171. //将byte数组用UTF-8编码并存入display字符串中
172.        str =  EncodingUtils.getString(temp,TEXT_ENCODING);  
173. //关闭文件file的InputStream
174.        in.close();  
175.    }  
176. catch (IOException e) {  
177. 
178.       DisplayToast(e.toString());  
179. 
180.    }  
181. return str;  
182.   }  
183. publicvoid writefile(String str,String path )  
184.   {  
185.     File file;  
186.     FileOutputStream out;  
187. try {  
188. //创建文件
189. new File(path);  
190.            file.createNewFile();  
191. //打开文件file的OutputStream
192. new FileOutputStream(file);  
193.            String infoToWrite = str;  
194. //将字符串转换成byte数组写入文件
195.            out.write(infoToWrite.getBytes());  
196. //关闭文件file的OutputStream
197.            out.close();   
198. catch (IOException e) {  
199. //将出错信息打印到Logcat
200.           DisplayToast(e.toString());  
201. 
202.        }  
203.   }  
204. publicvoid refresh()  
205.   {  
206. 
207. 
208. //读取本次开机之后直到当前系统的总流量
209. 
210. 0]+","+ethdata[1]+","+ethdata[8]+","+ethdata[9]+","
211. 0]+","+gprsdata[1]+","+gprsdata[8]+","+gprsdata[9]+","
212. 0]+","+wifidata[1]+","+wifidata[8]+","+wifidata[9];  
213. //读取on.txt记录到onstr里
214. ",");//将onstr各项分离 放到ondata里
215. //计算增量
216. int [] delta=newint [12];  
217. 
218. 0]=Integer.parseInt(ethdata[0])-Integer.parseInt(ondata[0]);  
219. 1]=Integer.parseInt(ethdata[1])-Integer.parseInt(ondata[1]);  
220. 2]=Integer.parseInt(ethdata[8])-Integer.parseInt(ondata[2]);  
221. 3]=Integer.parseInt(ethdata[9])-Integer.parseInt(ondata[3]);  
222. 4]=Integer.parseInt(gprsdata[0])-Integer.parseInt(ondata[4]);  
223. 5]=Integer.parseInt(gprsdata[1])-Integer.parseInt(ondata[5]);  
224. 6]=Integer.parseInt(gprsdata[8])-Integer.parseInt(ondata[6]);  
225. 7]=Integer.parseInt(gprsdata[9])-Integer.parseInt(ondata[7]);  
226. 8]=Integer.parseInt(wifidata[0])-Integer.parseInt(ondata[8]);  
227. 9]=Integer.parseInt(wifidata[1])-Integer.parseInt(ondata[9]);  
228. 10]=Integer.parseInt(wifidata[8])-Integer.parseInt(ondata[10]);  
229. 11]=Integer.parseInt(wifidata[9])-Integer.parseInt(ondata[11]);  
230. 
231. 
232. //读取log.txt
233. //获取当前时间
234. final Calendar c = Calendar.getInstance();   
235. //获取当前年份 
236. 1;//获取当前月份 
237. //获取当前月份的日期号码 
238. //获取当前的小时数 
239. //获取当前的分钟数   
240. "-"+mMonth+"-"+mDay;  
241. 
242. //将log.txt的内容读到text字符串中
243. "/n");   
244. 
245. 1];//获得今日已记录流量
246. ",");   
247. //检查文件最后一行是否为今天的流量记录信息
248. if(!beToday[0].equals(mdate))//
249. //判断今日流量是否已经记录,如果今日流量没有记录
250.       {  
251. 
252. ",0,0,0,0,0,0,0,0,0,0,0,0/n";  
253.           writefile(text,LOGPATH);  
254. 
255. 
256. "/n");  
257. 1];//获得今日已记录流量
258. 
259. ",");   
260.       }  
261. int i;  
262. //处理今日流量
263. int [] newTodaydata=newint [12];//表示今日流量
264.       String newtoday=mdate;  
265. for(i=0;i<=11;i++)//更新今日流量
266.       {  
267. 1])+delta[i];  
268. ","+newTodaydata[i];  
269.       }  
270. "/n";  
271. 
272. 
273. 0].split(",");  
274. int [] newTotaldata=newint [12];//表示总流量数值
275. //更新第一行
276. "total";  
277. for(i=0;i<=11;i++)//更新今日流量和总流量
278.       {    
279. 1])+delta[i];//总流量数值+delta[i]更新
280. ","+newTotaldata[i];  
281.       }  
282. "/n";  
283. //处理中间不变的部分
284. "";//before为之前的从第1行到昨天的流量记录
285. 
286. for(i=1;i<=line.length-2;i++)  
287. "/n";//代表中间不变的部分
288. 
289.       String newlog=newtotal+before+newtoday;  
290. //更新流量记录
291. //更新log*/
292. 
293. 
294. 
295.   }  
296. 
297. 
298. }



应用iptable规则模块,通过运行iptable脚本来实现iptable规则的应用


1. privatestatic boolean applyIptablesRulesImpl(Context ctx, List<Integer> uids, boolean showErrors) {  
2. if (ctx == null) {  
3. returnfalse;  
4.                 }  
5.                 final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, 0);  
6.                 final boolean whitelist = prefs.getString(PREF_MODE, MODE_WHITELIST).equals(MODE_WHITELIST);  
7. false; // Wi-fi selected ?
8.                 final String itfs = prefs.getString(PREF_ITFS, ITF_3G);  
9.                 String itfFilter;  
10. if (itfs.indexOf("|") != -1) {  
11. ""; // Block all interfaces
12. true;  
13. elseif (itfs.indexOf(ITF_3G) != -1) {  
14. "-o rmnet+";;   
15. // Block all rmnet interfaces
16. else {  
17. "-o tiwlan+";;  
18. // Block all tiwlan interfaces
19. true;  
20.                 }  
21. new StringBuilder();  
22. try {  
23. int code;  
24. "iptables -F || exit/n");  
25. "ACCEPT" : "REJECT");  
26. if (whitelist && wifi) {  
27. // When "white listing" Wi-fi, we need ensure that the dhcp and wifi users are allowed
28. int uid = android.os.Process.getUidForName("dhcp");  
29. if (uid != -1) script.append("iptables -A OUTPUT "
30. " -m owner --uid-owner " + uid + " -j ACCEPT || exit/n");  
31. "wifi");  
32. if (uid != -1) script.append("iptables -A OUTPUT " + itfFilter + " -m owner --uid-owner " + uid + " -j ACCEPT || exit/n"); }  
33. for (Integer uid : uids) {  
34. "iptables -A OUTPUT " + itfFilter   
35. " -m owner --uid-owner " + uid + " -j " + targetRule + " || exit/n");  
36.                         }  
37. if (whitelist) {  
38. "iptables -A OUTPUT " + itfFilter + " -j REJECT || exit/n");  
39.                         }  
40. new StringBuilder();  
41.              code = runScriptAsRoot(script.toString(), res);  
42. if (showErrors && code != 0) {  
43.               String msg = res.toString();  
44. "DroidWall", msg);  
45. // Search for common error messages
46. if (msg.indexOf("Couldn't find match `owner'") != -1 || msg.indexOf("no chain/target match") != -1) {  
47. "Error applying iptables rules./nExit code: " + code + "/n/n" +"It seems your Linux kernel was not compiled with the netfilter /"owner/" module enabled, which is required for Droid Wall to work properly./n/n" +"You should check if there is an updated version of your Android ROM compiled with this kernel module.");  
48. else {  
49. // Remove unnecessary help message from output
50. if (msg.indexOf("/nTry `iptables -h' or 'iptables --help' for more information.") != -1) {  
51. "/nTry `iptables -h' or 'iptables --help' for more information.", "");  
52.        }  
53. // Try `iptables -h' or 'iptables --help' for more information.
54. "Error applying iptables rules. Exit code: " + code + "/n/n" + msg.trim());  
55.            }  
56. else {  
57. returntrue;  
58.         }  
59. catch (Exception e) {  
60. if (showErrors) alert(ctx, "error refreshing iptables: " + e);  
61.                 }  
62. returnfalse;  
63.     }

【转】


转载于:https://blog.51cto.com/8857113/1409051