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


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


BroadcastReceiver模块

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


[java] view plain copy
  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. if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){  

  16.                Intent bootActivityIntent=new Intent(context,mService1.class);//启动服务

  17.                bootActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  

  18.                writefile("0,0,0,0,0,0,0,0,0,0,0,0",ONPATH);  

  19.                context.startService(bootActivityIntent);  

  20.                 Toast.makeText(context, "Netcounter service has been lauched", Toast.LENGTH_LONG).show();  

  21.                 Api.applySavedIptablesRules(context, false);//应用防火墙规则

  22.                 Toast.makeText(context, "Wall rules have been lauched", Toast.LENGTH_LONG).show();  

  23.         }  

  24.    }  

  25. publicvoid writefile(String str,String path )  

  26.    {  

  27.       File file;  

  28. try {  

  29. //创建文件

  30.         file = new File(path);  

  31.          file.createNewFile();  


  32. //打开文件file的OutputStream

  33.          out = new FileOutputStream(file);  

  34.          String infoToWrite = str;  

  35. //将字符串转换成byte数组写入文件

  36.          out.write(infoToWrite.getBytes());  

  37. //关闭文件file的OutputStream

  38.          out.close();  




  39.       } catch (IOException e) {  

  40. //将出错信息打印到Logcat



  41.       }  


mService1模块

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


[java] view plain copy
  1. publicclass mService1 extends Service  

  2. {  



  3. private Handler objHandler = new Handler();  

  4. privateint intCounter=0;  

  5. privateint mHour;  

  6. privateint mMinute;  

  7. privateint mYear;  

  8. privateint mMonth;  

  9. privateint mDay;  

  10. private String mdate;  



  11. finalpublic String DEV_FILE = "/proc/self/net/dev";//系统流量文件

  12.    String[] ethdata={"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  

  13.    String[] gprsdata={"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  

  14.    String[] wifidata={"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  

  15.    String data="0,0,0,0,0,0,0,0,0,0,0,0";//对应on.txt里面的格式

  16. final String ETHLINE="  eth0";//以太网信息所在行

  17. final String GPRSLINE="rmnet0";  

  18. final String WIFILINE="tiwlan0";  


  19. final String TEXT_ENCODING = "UTF-8";  


  20. finalpublic String ONPATH = "/data/data/zy.dnh/on.txt";  

  21. finalpublic String LOGPATH = "/data/data/zy.dnh/log.txt";  


  22. private Runnable mTasks = new Runnable()  

  23.    {  


  24. publicvoid run()//运行该服务执行此函数

  25.        {  

  26.          refresh();  



  27.          intCounter++;  

  28. // DisplayToast("Counter:"+Integer.toString(intCounter));

  29.         objHandler.postDelayed(mTasks, 30000);//每3000毫秒执行一次

  30.       }  

  31.    };  


  32. @Override

  33. publicvoid onStart(Intent intent, int startId)  

  34.  {  

  35. // TODO Auto-generated method stub

  36. //writefile("0,0,0,0,0,0,0,0,0,0,0,0",ONPATH);//每次启动服务 初始化onpath


  37.    objHandler.postDelayed(mTasks, 0);  

  38. super.onStart(intent, startId);  

  39.  }  

  40. @Override

  41. publicvoid onCreate()  

  42.  {  

  43. // TODO Auto-generated method stub


  44. super.onCreate();  

  45.  }  


  46. @Override

  47. public IBinder onBind(Intent intent)  

  48.  {  

  49. // TODO Auto-generated method stub



  50. returnnull;  

  51.  }  

  52. @Override

  53. publicvoid onDestroy()  

  54.  {  

  55. // TODO Auto-generated method stub


  56. /*  */

  57.    objHandler.removeCallbacks(mTasks);  

  58. super.onDestroy();  

  59.  }    

  60. publicvoid DisplayToast(String str)  

  61.  {  

  62.    Toast.makeText(this,str,Toast.LENGTH_SHORT).show();  

  63.  }    

  64. publicvoid readdev()  

  65.  {  

  66.      FileReader fstream = null;  

  67. try {  

  68.          fstream = new FileReader(DEV_FILE);  


  69.          }  

  70. catch (FileNotFoundException e) {  

  71.            DisplayToast("Could not read " + DEV_FILE);  


  72.        }  

  73.       BufferedReader in = new BufferedReader(fstream, 500);  

  74.       String line;  

  75.       String[] segs;  

  76.       String[] netdata;  


  77. int count=0;  

  78. int k;  

  79. int j;  

  80. try {  

  81. while ((line = in.readLine()) != null) {  

  82.              segs = line.trim().split(":");  

  83. if(line.startsWith(ETHLINE))  

  84.                {  


  85.                  netdata=segs[1].trim().split(" ");  

  86. for(k=0,j=0;k<netdata.length;k++)  

  87.                  {  

  88. if(netdata[k].length()>0)  

  89.                     {  


  90.                          ethdata[j]=netdata[k];  

  91.                          j++;  

  92.                     }  

  93.                  }  

  94.              }  

  95. elseif(line.startsWith(GPRSLINE))  

  96.              {  


  97.                netdata=segs[1].trim().split(" ");  

  98. for(k=0,j=0;k<netdata.length;k++)  

  99.              {  

  100. if(netdata[k].length()>0)  

  101.                 {  


  102.                      gprsdata[j]=netdata[k];  

  103.                      j++;  

  104.                 }  

  105.              }  

  106.              }  

  107. elseif(line.startsWith(WIFILINE))  

  108.          {  


  109.            netdata=segs[1].trim().split(" ");  

  110. for(k=0,j=0;k<netdata.length;k++)  

  111.                {  

  112. if(netdata[k].length()>0)  

  113.                    {  


  114.                      wifidata[j]=netdata[k];  

  115.                      j++;  

  116.                    }  

  117.                }  

  118.          }  





  119.              count++;  

  120.          }  

  121.          fstream.close();  


  122.        }  

  123. catch (IOException e) {  

  124.          DisplayToast(e.toString());  

  125.        }  

  126.  }  

  127. public String getinfo(String path)  

  128.  {  

  129.    File file;  

  130.    String str="";  

  131.    FileInputStream in;  

  132. try{  

  133. //打开文件file的InputStream

  134.     file = new File(path);  

  135.       in = new FileInputStream(file);  

  136. //将文件内容全部读入到byte数组

  137. int length = (int)file.length();  

  138. byte[] temp = newbyte[length];  

  139.       in.read(temp, 0, length);  

  140. //将byte数组用UTF-8编码并存入display字符串中

  141.       str =  EncodingUtils.getString(temp,TEXT_ENCODING);  

  142. //关闭文件file的InputStream

  143.       in.close();  

  144.   }  

  145. catch (IOException e) {  


  146.      DisplayToast(e.toString());  


  147.   }  

  148. return str;  

  149.  }  

  150. publicvoid writefile(String str,String path )  

  151.  {  

  152.    File file;  

  153.    FileOutputStream out;  

  154. try {  

  155. //创建文件

  156.         file = new File(path);  

  157.           file.createNewFile();  

  158. //打开文件file的OutputStream

  159.           out = new FileOutputStream(file);  

  160.           String infoToWrite = str;  

  161. //将字符串转换成byte数组写入文件

  162.           out.write(infoToWrite.getBytes());  

  163. //关闭文件file的OutputStream

  164.           out.close();  

  165.       } catch (IOException e) {  

  166. //将出错信息打印到Logcat

  167.          DisplayToast(e.toString());  


  168.       }  

  169.  }  

  170. publicvoid refresh()  

  171.  {  



  172.      readdev();//读取本次开机之后直到当前系统的总流量


  173.       data=ethdata[0]+","+ethdata[1]+","+ethdata[8]+","+ethdata[9]+","

  174.           +gprsdata[0]+","+gprsdata[1]+","+gprsdata[8]+","+gprsdata[9]+","

  175.           +wifidata[0]+","+wifidata[1]+","+wifidata[8]+","+wifidata[9];  

  176.      String onstr=getinfo(ONPATH);//读取on.txt记录到onstr里

  177.       String ondata[]=onstr.split(",");//将onstr各项分离 放到ondata里

  178. //计算增量

  179. int [] delta=newint [12];  


  180.      delta[0]=Integer.parseInt(ethdata[0])-Integer.parseInt(ondata[0]);  

  181.      delta[1]=Integer.parseInt(ethdata[1])-Integer.parseInt(ondata[1]);  

  182.      delta[2]=Integer.parseInt(ethdata[8])-Integer.parseInt(ondata[2]);  

  183.      delta[3]=Integer.parseInt(ethdata[9])-Integer.parseInt(ondata[3]);  

  184.      delta[4]=Integer.parseInt(gprsdata[0])-Integer.parseInt(ondata[4]);  

  185.      delta[5]=Integer.parseInt(gprsdata[1])-Integer.parseInt(ondata[5]);  

  186.      delta[6]=Integer.parseInt(gprsdata[8])-Integer.parseInt(ondata[6]);  

  187.      delta[7]=Integer.parseInt(gprsdata[9])-Integer.parseInt(ondata[7]);  

  188.      delta[8]=Integer.parseInt(wifidata[0])-Integer.parseInt(ondata[8]);  

  189.      delta[9]=Integer.parseInt(wifidata[1])-Integer.parseInt(ondata[9]);  

  190.      delta[10]=Integer.parseInt(wifidata[8])-Integer.parseInt(ondata[10]);  

  191.      delta[11]=Integer.parseInt(wifidata[9])-Integer.parseInt(ondata[11]);  



  192. //读取log.txt

  193. //获取当前时间

  194. final Calendar c = Calendar.getInstance();  

  195.      mYear = c.get(Calendar.YEAR); //获取当前年份

  196.      mMonth = c.get(Calendar.MONTH)+1;//获取当前月份

  197.      mDay = c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码

  198.      mHour = c.get(Calendar.HOUR_OF_DAY);//获取当前的小时数

  199.      mMinute = c.get(Calendar.MINUTE);//获取当前的分钟数  

  200.      mdate=mYear+"-"+mMonth+"-"+mDay;  


  201.      String text=getinfo(LOGPATH);//将log.txt的内容读到text字符串中

  202.      String [] line=text.split("/n");  


  203.      String today=line[line.length-1];//获得今日已记录流量

  204.      String [] beToday=today.split(",");  

  205. //检查文件最后一行是否为今天的流量记录信息

  206. if(!beToday[0].equals(mdate))//

  207. //判断今日流量是否已经记录,如果今日流量没有记录

  208.      {  


  209.          text=text+mdate+",0,0,0,0,0,0,0,0,0,0,0,0/n";  

  210.          writefile(text,LOGPATH);  



  211.          line=text.split("/n");  

  212.          today=line[line.length-1];//获得今日已记录流量


  213.          beToday=today.split(",");  

  214.      }  

  215. int i;  

  216. //处理今日流量

  217. int [] newTodaydata=newint [12];//表示今日流量

  218.      String newtoday=mdate;  

  219. for(i=0;i<=11;i++)//更新今日流量

  220.      {  

  221.          newTodaydata[i]=Integer.parseInt(beToday[i+1])+delta[i];  

  222.          newtoday=newtoday+","+newTodaydata[i];  

  223.      }  

  224.      newtoday=newtoday+"/n";  



  225.      String [] beTotal=line[0].split(",");  

  226. int [] newTotaldata=newint [12];//表示总流量数值

  227. //更新第一行

  228.      String newtotal="total";  

  229. for(i=0;i<=11;i++)//更新今日流量和总流量

  230.      {    

  231.          newTotaldata[i]=Integer.parseInt(beTotal[i+1])+delta[i];//总流量数值+delta[i]更新

  232.          newtotal=newtotal+","+newTotaldata[i];  

  233.      }  

  234.      newtotal= newtotal+"/n";  

  235. //处理中间不变的部分

  236.      String before="";//before为之前的从第1行到昨天的流量记录


  237. for(i=1;i<=line.length-2;i++)  

  238.        before=before+line[i]+"/n";//代表中间不变的部分


  239.      String newlog=newtotal+before+newtoday;  

  240.      writefile(data,ONPATH);//更新流量记录

  241.      writefile(newlog,LOGPATH);//更新log*/




  242.  }  



  243. }  



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


[c-sharp] view plain copy
  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.                boolean wifi = false; // Wi-fi selected ?

  8.                final String itfs = prefs.getString(PREF_ITFS, ITF_3G);  

  9.                String itfFilter;  

  10. if (itfs.indexOf("|") != -1) {  

  11.                        itfFilter = ""; // Block all interfaces

  12.                        wifi = true;  

  13.                } elseif (itfs.indexOf(ITF_3G) != -1) {  

  14.                        itfFilter = "-o rmnet+";;  

  15. // Block all rmnet interfaces

  16.                } else {  

  17.                        itfFilter = "-o tiwlan+";;  

  18. // Block all tiwlan interfaces

  19.                        wifi = true;  

  20.                }  

  21.    final StringBuilder script = new StringBuilder();  

  22. try {  

  23. int code;  

  24.        script.append("iptables -F || exit/n");  

  25.         final String targetRule = (whitelist ? "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.                                        + itfFilter + " -m owner --uid-owner " + uid + " -j ACCEPT || exit/n");  

  31.              uid = android.os.Process.getUidForName("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.             script.append("iptables -A OUTPUT " + itfFilter  

  35.                                        + " -m owner --uid-owner " + uid + " -j " + targetRule + " || exit/n");  

  36.                        }  

  37. if (whitelist) {  

  38.                script.append("iptables -A OUTPUT " + itfFilter + " -j REJECT || exit/n");  

  39.                        }  

  40.                StringBuilder res = new StringBuilder();  

  41.             code = runScriptAsRoot(script.toString(), res);  

  42. if (showErrors && code != 0) {  

  43.              String msg = res.toString();  

  44.              Log.e("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.               alert(ctx, "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.        msg = msg.replace("/nTry `iptables -h' or 'iptables --help' for more information.", "");  

  52.       }  

  53. // Try `iptables -h' or 'iptables --help' for more information.

  54.          alert(ctx, "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.    }  


【转】http://blog.csdn.net/Zengyangtech/article/details/5638604