一、首先写一个WifiManage.java主要获取手机内的wifi名和密码
1.wifi密码一般存储在/data/misc/wifi/wpa_supplicant.conf.想要访问该文件,需要root权限,所以首先我们得获取手机的root权限。
2.获取终端信息输入输出流:用DataOutputStream和DataInputStream.
3.往终端输入命令
4.通过dataInputStream获取命令执行结果,并以UTF-8的编码转换成字符串.
5.使用正则表达式过滤出wifi的用户名和密码。
主要的一些代码:
public List<WifiInfo> WifiRead() {
List<WifiInfo> wifiInfos=new ArrayList<WifiInfo>();
//获取手机root权限
Process process = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
StringBuffer wifiConf = new StringBuffer();
try{
//获取手机root权限
process = Runtime.getRuntime().exec("su");
//获得终端信息输入输出流
dataOutputStream = new DataOutputStream(process.getOutputStream());
dataInputStream = new DataInputStream(process.getInputStream());
//往终端输入命令
dataOutputStream
.writeBytes("cat /data/misc/wifi/*.conf\n");
dataOutputStream.writeBytes("exit\n");
dataOutputStream.flush();
//通过dataInputStream获取命令执行结果,并以UTF-8的编码转换成字符串。
InputStreamReader inputStreamReader = new InputStreamReader(
dataInputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
wifiConf.append(line);
}
bufferedReader.close();
inputStreamReader.close();
process.waitFor();
} catch (Exception e) {
throw e;
} finally {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (dataInputStream != null) {
dataInputStream.close();
}
process.destroy();
} catch (Exception e) {
throw e;
}
}
//使用正则表达式过滤出wifi的用户名和密码。
Pattern network = Pattern.compile("network=\\{([^\\}]+)\\}", Pattern.DOTALL);
Matcher networkMatcher = network.matcher(wifiConf.toString() );
while (networkMatcher.find() ) {
String networkBlock = networkMatcher.group();
Pattern ssid = Pattern.compile("ssid=\"([^\"]+)\"");
Matcher ssidMatcher = ssid.matcher(networkBlock);
if (ssidMatcher.find() ) {
WifiInfo wifiInfo=new WifiInfo();
wifiInfo.Ssid=ssidMatcher.group(1);
Pattern psk = Pattern.compile("psk=\"([^\"]+)\"");
Matcher pskMatcher = psk.matcher(networkBlock);
if (pskMatcher.find() ) {
wifiInfo.Password=pskMatcher.group(1);
} else {
wifiInfo.Password="无密码";
}
wifiInfos.add(wifiInfo);
}
}
return wifiInfos;
}
}
二、建一个WifiInfo类来存放WIFIManage获取的wifi名和密码
三、在主界面将WifiInfo显示出来
共同学习,写下你的评论
评论加载中...
作者其他优质文章