以前总是在没有网用的时候想去蹭网,但是总是也不破解不了密码,在学了开发以后我一直就想看看这个手机的无线网络连接究竟是咋连的了,今天研究了下终于让我是对他有了一定的了解;
说到底其实还是通过android里边的manger来进行管理,wifi使用的是WifiManager,通过这个管理器你可以获取你想要获取的基本上所有东西了:还是直接看代码吧
package com.example.wifidemo;
import java.util.List;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
public class WifiAdmin {
//定义一个WifiManager对象
private WifiManager mWifiManager;
//定义一个WifiInfo对象
private WifiInfo mWifiInfo;
//扫描出的网络连接列表
private List<ScanResult> mWifiList;
//网络连接列表
private List<WifiConfiguration> mWifiConfigurations;
WifiLock mWifiLock;
public WifiAdmin(Context context){
//取得WifiManager对象
mWifiManager=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//取得WifiInfo对象
mWifiInfo=mWifiManager.getConnectionInfo();
}
//打开wifi
public void openWifi(){
if(!mWifiManager.isWifiEnabled()){
mWifiManager.setWifiEnabled(true);
}
}
//关闭wifi
public void closeWifi(){
if(!mWifiManager.isWifiEnabled()){
mWifiManager.setWifiEnabled(false);
}
}
// 检查当前wifi状态
public int checkState() {
return mWifiManager.getWifiState();
}
//锁定wifiLock
public void acquireWifiLock(){
mWifiLock.acquire();
}
//解锁wifiLock
public void releaseWifiLock(){
//判断是否锁定
if(mWifiLock.isHeld()){
mWifiLock.acquire();
}
}
//创建一个wifiLock
public void createWifiLock(){
mWifiLock=mWifiManager.createWifiLock("test");
}
//得到配置好的网络
public List<WifiConfiguration> getConfiguration(){
return mWifiConfigurations;
}
//指定配置好的网络进行连接
public void connetionConfiguration(int index){
if(index>mWifiConfigurations.size()){
return ;
}
//连接配置好指定ID的网络
mWifiManager.enableNetwork(mWifiConfigurations.get(index).networkId, true);
}
public void startScan(){
mWifiManager.startScan();
//得到扫描结果
mWifiList=mWifiManager.getScanResults();
//得到配置好的网络连接
mWifiConfigurations=mWifiManager.getConfiguredNetworks();
}
//得到网络列表
public List<ScanResult> getWifiList(){
return mWifiList;
}
//查看扫描结果
public StringBuffer lookUpScan(){
StringBuffer sb=new StringBuffer();
for(int i=0;i<mWifiList.size();i++){
sb.append("Index_" + new Integer(i + 1).toString() + ":");
// 将ScanResult信息转换成一个字符串包
// 其中把包括:BSSID、SSID、capabilities、frequency、level
sb.append((mWifiList.get(i)).toString()).append("\n");
}
return sb;
}
public String getMacAddress(){
return (mWifiInfo==null)?"NULL":mWifiInfo.getMacAddress();
}
public String getBSSID(){
return (mWifiInfo==null)?"NULL":mWifiInfo.getBSSID();
}
public int getIpAddress(){
return (mWifiInfo==null)?0:mWifiInfo.getIpAddress();
}
//得到连接的ID
public int getNetWordId(){
return (mWifiInfo==null)?0:mWifiInfo.getNetworkId();
}
//得到wifiInfo的所有信息
public WifiInfo getWifiInfo(){
return (WifiInfo) ((mWifiInfo==null)?"NULL":mWifiInfo);
}
//添加一个网络并连接
public void addNetWork(WifiConfiguration configuration){
int wcgId=mWifiManager.addNetwork(configuration);
mWifiManager.enableNetwork(wcgId, true);
mWifiManager.reconnect();
}
//断开指定ID的网络
public void disConnectionWifi(int netId){
mWifiManager.disableNetwork(netId);
mWifiManager.disconnect();
}
public WifiConfiguration createWifiInfo(String SSID, String Password,
int Type) {
if (SSID == null || Password == null || SSID.equals("")) {
return null;
}
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
WifiConfiguration tempConfig = isExsits(SSID, mWifiManager);
if (tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
}
if (Type == 1) // WIFICIPHER_NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (Type == 2) // WIFICIPHER_WEP
{
config.hiddenSSID = true;
config.wepKeys[0] = "\"" + Password + "\"";
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (Type == 3) // WIFICIPHER_WPA
{
config.preSharedKey = "\"" + Password + "\"";
config.hiddenSSID = true;
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
// config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}
return config;
}
private static WifiConfiguration isExsits(String SSID,
WifiManager wifiManager) {
List<WifiConfiguration> existingConfigs = wifiManager
.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
}
有了这些东西,那就好办了,看下activity的代码,只是展示与无线网络的连接,简单的写了下,只是为了学习:
package com.example.wifidemo;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.wifidemo.XListView.IXListViewListener;
public class MainActivity extends ActionBarActivity {
private XListView mXListView;
private MyAdapter myAdapter;
private List<ScanResult> wifis = new ArrayList<ScanResult>();
private List<WifiConfiguration> configurations = new ArrayList<WifiConfiguration>();
private Button mButton, mButton1;
private WifiAdmin mWifiAdmin;
private Dialog mDialog;
private EditText password;
private Handler handler = new Handler();;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWifiAdmin = new WifiAdmin(this);
initView();
}
private void initDialog(final String SSID, final int Type) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = getLayoutInflater().from(this).inflate(R.layout.dialog,
null);
password = (EditText) view.findViewById(R.id.editText);
builder.setView(view);
builder.setTitle("wifi连接");
builder.setPositiveButton("确定",
new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if (password.getText().toString() != null
&& !"".equals(password.getText().toString())) {
mWifiAdmin.addNetWork(mWifiAdmin.createWifiInfo(
SSID, password.getText().toString(), Type));
} else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "没有输入密码",
Toast.LENGTH_SHORT).show();
mDialog.show();
}
});
}
}
});
builder.setNegativeButton("取消",
new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
mDialog.dismiss();
}
});
mDialog = builder.create();
mDialog.show();
}
private void initView() {
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mWifiAdmin.startScan();
wifis = mWifiAdmin.getWifiList();
configurations = mWifiAdmin.getConfiguration();
if (wifis != null && wifis.size() > 0) {
myAdapter.Refresh(wifis);
}
}
});
mButton1 = (Button) findViewById(R.id.button1);
mButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mWifiAdmin.openWifi();
mButton1.setText("關閉");
}
});
mXListView = (XListView) findViewById(R.id.xListView);
myAdapter = new MyAdapter(wifis, this);
mXListView.setAdapter(myAdapter);
mXListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ScanResult scanResult = wifis.get(position - 1);
Log.i("ssid", mWifiAdmin.getWifiInfo().getSSID().toString()
.replaceAll("\"", ""));
if (!scanResult.SSID.contains(mWifiAdmin.getWifiInfo()
.getSSID().toString().replaceAll("\"", ""))) {
if (scanResult.capabilities.contains("WPA-PSK")) {
initDialog(scanResult.SSID, 3);
} else if (scanResult.capabilities.contains("WEP")) {
initDialog(scanResult.SSID, 2);
} else {
Toast.makeText(MainActivity.this, "沒有密碼", 1000).show();
mWifiAdmin.addNetWork(mWifiAdmin.createWifiInfo(
scanResult.SSID, "", 1));
}
} else {
Toast.makeText(MainActivity.this, "已连接", 1000).show();
}
}
});
mXListView.setXListViewListener(new IXListViewListener() {
@Override
public void onRefresh() {
myAdapter.Refresh(mWifiAdmin.getWifiList());
mXListView.stopRefresh();
}
@Override
public void onLoadMore() {
}
});
}
class MyAdapter extends BaseAdapter {
private List<ScanResult> lists;
private Context context;
public MyAdapter(List<ScanResult> list, Context context) {
this.context = context;
this.lists = list;
}
public void Refresh(List<ScanResult> list) {
this.lists = list;
notifyDataSetChanged();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return lists.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return lists.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(
R.layout.item, null);
}
TextView textView = (TextView) convertView
.findViewById(R.id.textView);
textView.setText(lists.get(position).SSID + " frequency"
+ lists.get(position).frequency + "/n");
return convertView;
}
}
}
代码没有什么难度,基本上看看就会,对了使用wifi还要有四个权限,记得加啊
<!-- 以下是使用wifi访问网络所需的权限 -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
Demo下载地址:http://download.csdn.net/detail/u012808234/8574127