最近研究android内核-系统关键服务的启动解析,然而我也不知道研究wifi的作用,就当兴趣去做吧(其实是作业-_-)

系统原生WiFI功能大概有:启动WiFI服务,扫描WiFi信息(这个好像已经被封装到WiFiManager中了),显示WiFi,连接WiFi,关闭WiFi......

Android提供WifiManager.java对wifi进行管理

WifiInfo是专门用来表示连接的对象,可以查看当前已连接的wifi信息

WifiConfiguration是保存已配置过了wifi信息

ScanResult是存放扫描到了所有wifi的一些信息,如wifi名,信号强度,是否加锁。。。。

大体步骤:

Context.getSystemService(Context.WIFI_SERVICE)来获取WifiManager对象管理WIFI设备

WifiManager.startScan() 开始扫描

WifiManager.getScanResults() 获取扫描测试的结果

WifiManager.calculateSignalLevel(scanResult.get(i).level,4) 获取信号等级

scanResult.get(i).capabilities 获取wifi是否加锁

linkWifi.IsExsits(SSID) 获取wifi是否已保存配置信息

listView.setAdapter(adapter)显示wifi信息

监听事件处理

end

简单项目结构图

MScanWifi.java是我自己定义了一个Bean类只是定义了一些用到了wifi信息

package com.example.android_wifitest.base;

import android.net.wifi.ScanResult;

public class MScanWifi {
private int level;//wifi信号强度
private String WifiName;
//保存一个引用,在wifi连接时候用到
public ScanResult scanResult;
private boolean isLock;//是否是锁定
private boolean isExsit;//是否是保存过的wifi
public MScanWifi(){ }
public MScanWifi(ScanResult scanResult,String WifiName,int level,Boolean isLock){
this.WifiName=WifiName;
this.level=level;
this.isLock=isLock;
this.scanResult=scanResult;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getWifiName() {
return WifiName;
}
public void setWifiName(String wifiName) {
WifiName = wifiName;
}
public Boolean getIsLock() {
return isLock;
}
public void setIsLock(boolean isLock) {
this.isLock = isLock;
}
public boolean getIsExsit() {
return isExsit;
}
public void setIsExsit(boolean isExsit) {
this.isExsit = isExsit;
} }

LinkWifi.java这个封装了一些常用方法(这个类从其他人代码中copy)

package com.example.android_wifitest;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List; import android.app.Service;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log; public class LinkWifi {
private WifiManager wifiManager;
private Context context;
/** 定义几种加密方式,一种是WEP,一种是WPA/WPA2,还有没有密码的情况 */
public enum WifiCipherType {
WIFI_CIPHER_WEP, WIFI_CIPHER_WPA_EAP, WIFI_CIPHER_WPA_PSK, WIFI_CIPHER_WPA2_PSK, WIFI_CIPHER_NOPASS
}
public LinkWifi(Context context) {
this.context = context;
wifiManager = (WifiManager) context
.getSystemService(Service.WIFI_SERVICE);
}
public boolean ConnectToNetID(int netID) {
System.out.println("ConnectToNetID netID=" + netID);
return wifiManager.enableNetwork(netID, true);
}
public int CreateWifiInfo2(ScanResult wifiinfo, String pwd) {
WifiCipherType type; if (wifiinfo.capabilities.contains("WPA2-PSK")) {
// WPA-PSK加密
type = WifiCipherType.WIFI_CIPHER_WPA2_PSK;
} else if (wifiinfo.capabilities.contains("WPA-PSK")) {
// WPA-PSK加密
type = WifiCipherType.WIFI_CIPHER_WPA_PSK;
} else if (wifiinfo.capabilities.contains("WPA-EAP")) {
// WPA-EAP加密
type = WifiCipherType.WIFI_CIPHER_WPA_EAP;
} else if (wifiinfo.capabilities.contains("WEP")) {
// WEP加密
type = WifiCipherType.WIFI_CIPHER_WEP;
} else {
// 无密码
type = WifiCipherType.WIFI_CIPHER_NOPASS;
} WifiConfiguration config = CreateWifiInfo(wifiinfo.SSID,
wifiinfo.BSSID, pwd, type);
if (config != null) {
return wifiManager.addNetwork(config);
} else {
return -1;
}
}
/** 配置一个连接 */
public WifiConfiguration CreateWifiInfo(String SSID, String BSSID,
String password, WifiCipherType type) { int priority; WifiConfiguration config = this.IsExsits(SSID);
if (config != null) {
// Log.w("Wmt", "####之前配置过这个网络,删掉它");
// wifiManager.removeNetwork(config.networkId); // 如果之前配置过这个网络,删掉它 // 本机之前配置过此wifi热点,调整优先级后,直接返回
return setMaxPriority(config);
} config = new WifiConfiguration();
/* 清除之前的连接信息 */
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
config.status = WifiConfiguration.Status.ENABLED;
// config.BSSID = BSSID;
// config.hiddenSSID = true; priority = getMaxPriority() + 1;
if (priority > 99999) {
priority = shiftPriorityAndSave();
} config.priority = priority; // 2147483647;
/* 各种加密方式判断 */
if (type == WifiCipherType.WIFI_CIPHER_NOPASS) {
Log.w("Wmt", "没有密码");
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
} else if (type == WifiCipherType.WIFI_CIPHER_WEP) {
Log.w("Wmt", "WEP加密,密码" + password);
config.preSharedKey = "\"" + 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;
} else if (type == WifiCipherType.WIFI_CIPHER_WPA_EAP) {
Log.w("Wmt", "WPA_EAP加密,密码" + password); config.preSharedKey = "\"" + password + "\"";
config.hiddenSSID = true;
config.status = WifiConfiguration.Status.ENABLED;
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN
| WifiConfiguration.Protocol.WPA); } else if (type == WifiCipherType.WIFI_CIPHER_WPA_PSK) {
Log.w("Wmt", "WPA加密,密码" + password); config.preSharedKey = "\"" + password + "\"";
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN
| WifiConfiguration.Protocol.WPA); } else if (type == WifiCipherType.WIFI_CIPHER_WPA2_PSK) {
Log.w("Wmt", "WPA2-PSK加密,密码=======" + password); config.preSharedKey = "\"" + password + "\"";
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); } else {
return null;
} return config;
}
/** 查看以前是否也配置过这个网络 */
public WifiConfiguration IsExsits(String SSID) {
List<WifiConfiguration> existingConfigs = wifiManager
.getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.toString().equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
public WifiConfiguration setMaxPriority(WifiConfiguration config) {
int priority = getMaxPriority() + 1;
if (priority > 99999) {
priority = shiftPriorityAndSave();
} config.priority = priority; // 2147483647;
System.out.println("priority=" + priority); wifiManager.updateNetwork(config); // 本机之前配置过此wifi热点,直接返回
return config;
}
private int getMaxPriority() {
List<WifiConfiguration> localList = this.wifiManager
.getConfiguredNetworks();
int i = 0;
Iterator<WifiConfiguration> localIterator = localList.iterator();
while (true) {
if (!localIterator.hasNext())
return i;
WifiConfiguration localWifiConfiguration = (WifiConfiguration) localIterator
.next();
if (localWifiConfiguration.priority <= i)
continue;
i = localWifiConfiguration.priority;
}
} private int shiftPriorityAndSave() {
List<WifiConfiguration> localList = this.wifiManager
.getConfiguredNetworks();
sortByPriority(localList);
int i = localList.size();
for (int j = 0;; ++j) {
if (j >= i) {
this.wifiManager.saveConfiguration();
return i;
}
WifiConfiguration localWifiConfiguration = (WifiConfiguration) localList
.get(j);
localWifiConfiguration.priority = j;
this.wifiManager.updateNetwork(localWifiConfiguration);
}
} private void sortByPriority(List<WifiConfiguration> paramList) {
Collections.sort(paramList, new WifiManagerCompare());
} class WifiManagerCompare implements Comparator<WifiConfiguration> {
public int compare(WifiConfiguration paramWifiConfiguration1,
WifiConfiguration paramWifiConfiguration2) {
return paramWifiConfiguration1.priority
- paramWifiConfiguration2.priority;
}
}
}

上主代码之前先上xml布局

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#cccccc"
>
<TextView
android:id="@+id/switch_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="关"
/>
<!--wifi开关按钮-->
<Switch
android:id="@+id/switch_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="OFF"
android:textOn="ON"
android:thumb="@drawable/thumb_selector"
android:track="@drawable/track_selector" /> </LinearLayout>
<LinearLayout
android:id="@+id/ListView_LinearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#000000"
>
</LinearLayout> </LinearLayout>

<LinearLayout android:id="@+id/ListView_LinearLayout"。。。这个是为了加载listview准备了

android:thumb="@drawable/thumb_selector" thumb属性指的是:switch上面滑动的滑块

android:track="@drawable/track_selector"  track是滑道德背景图片显示

上面的两个资源文件

thumb_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/press" />
<item android:state_pressed="false" android:drawable="@drawable/switch_enable"/>
</selector>

track_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/switch_track_default"/>
<item android:state_checked="false" android:drawable="@drawable/switch_check_on"/>
</selector>

my_listview.xml这是为了实现动态加载XML布局使用

<?xml version="1.0" encoding="utf-8"?>

  <ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mlistview"
android:divider="#cccccc"
android:dividerHeight="1dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

listitems.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#666666"
android:orientation="horizontal" > <ImageView
android:id="@+id/img_wifi_level"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:contentDescription="@string/hello_world"
android:layout_marginLeft="20dp"
android:src="@drawable/wifi_signal" />
<LinearLayout
android:layout_toRightOf="@id/img_wifi_level"
android:layout_height="30dp"
android:layout_width="wrap_content"
android:layout_marginLeft="20dp"
android:orientation="vertical" >
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textSize="12sp"
android:textStyle="bold"
android:text="11111"
/>
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textSize="12sp"
android:visibility="gone"
android:text="11111"
/>
</LinearLayout>
</RelativeLayout>

dialog_inputpwd.xml弹出对话框显示的Content

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" > <LinearLayout
android:id="@+id/dialognum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" > <TextView
android:id="@+id/tvPassWord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="密码:"
android:textColor="#19B2CC" /> <EditText
android:id="@+id/etPassWord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="200dip"
android:password="true" />
</LinearLayout> </RelativeLayout>

MainActivity.java是程序入口(有点累赘了)

 package com.example.android_wifitest;

 import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log; import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List; import com.example.android_wifitest.base.CommonAdapter;
import com.example.android_wifitest.base.MScanWifi;
import com.example.android_wifitest.base.ViewHolder; import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener; public class MainActivity extends Activity {
public WifiManager mWifiManager;
public List<MScanWifi> mScanWifiList;//自定义类存放用到的wifi信息
public List<ScanResult> mWifiList;//存放系统扫描到了wifi信息
public List<WifiConfiguration> mWifiConfiguration;//wifi配置信息
public Context context = null;
public Scanner mScanner;//自定义handler类每隔10秒自动扫描wifi信息
public View view;
public TextView wifi_status_txt;
public Switch wifiSwitch;
public ListView listView;
private IntentFilter mFilter;
private LinkWifi linkWifi;
public LayoutInflater Inflater;
private LinearLayout layout; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
Inflater=LayoutInflater.from(context);
mWifiManager=(WifiManager) context.getSystemService(Service.WIFI_SERVICE);
mScanner = new Scanner(this);
linkWifi=new LinkWifi(context);
initView();
initIntentFilter();
registerListener();
registerBroadcast();
}
public void initIntentFilter() {
// TODO Auto-generated method stub
mFilter = new IntentFilter();
mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//用户操作activity时更新UI
mScanner.forceScan();
}
/*@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//设备激进入休眠状态时执行
unregisterBroadcast();
}*/
@Override
protected void onDestroy() {
super.onDestroy();
context.unregisterReceiver(mReceiver); // 注销此广播接收器
}
public void initView() {
// TODO Auto-generated method stub
//获得要加载listview的布局
layout=(LinearLayout) findViewById(R.id.ListView_LinearLayout);
//动态获得listview布局
listView = (ListView) Inflater.inflate(
R.layout.my_listview, null).findViewById(R.id.mlistview);
wifi_status_txt=(TextView) findViewById(R.id.switch_txt);
wifiSwitch=(Switch)findViewById(R.id.switch_status);
layout.addView(listView);
}
public void registerListener() {
// TODO Auto-generated method stub
wifiSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()){
wifi_status_txt.setText("开启"); if (!mWifiManager.isWifiEnabled()) { // 当前wifi不可用
mWifiManager.setWifiEnabled(true);
}
mWifiManager.startScan(); }
else{
wifi_status_txt.setText("关闭");
if (mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
} }
}
});
//给item添加监听事件
listView.setOnItemClickListener(new OnItemClickListener() { @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
// 本机已经配置过的wifi
final ScanResult wifi=mScanWifiList.get(position).scanResult;
final WifiConfiguration wifiConfig=linkWifi.IsExsits(wifi.SSID);
if(wifiConfig!= null){
final int netID = wifiConfig.networkId;
String actionStr;
// 如果目前连接了此网络
if (mWifiManager.getConnectionInfo().getNetworkId() == netID) {
actionStr = "断开";
} else {
actionStr = "连接";
}
android.app.AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle("提示");
builder.setMessage("请选择你要进行的操作?");
builder.setPositiveButton(actionStr,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) { if (mWifiManager.getConnectionInfo()
.getNetworkId() == netID) {
mWifiManager.disconnect();
} else { linkWifi.setMaxPriority(wifiConfig);
linkWifi.ConnectToNetID(wifiConfig.networkId);
} }
});
builder.setNeutralButton("忘记",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
mWifiManager.removeNetwork(netID);
return;
}
});
builder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
return;
}
});
builder.show(); return; }
if (mScanWifiList.get(position).getIsLock()) {
// 有密码,提示输入密码进行连接 // final String encryption = capabilities; LayoutInflater factory = LayoutInflater.from(context);
final View inputPwdView = factory.inflate(R.layout.dialog_inputpwd,
null);
new AlertDialog.Builder(context)
.setTitle("请输入该无线的连接密码")
.setMessage("无线SSID:" + wifi.SSID)
.setIcon(android.R.drawable.ic_dialog_info)
.setView(inputPwdView)
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
EditText pwd = (EditText) inputPwdView
.findViewById(R.id.etPassWord);
String wifipwd = pwd.getText().toString(); // 此处加入连接wifi代码
int netID = linkWifi.CreateWifiInfo2(
wifi, wifipwd); linkWifi.ConnectToNetID(netID);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
}).setCancelable(false).show(); } else {
// 无密码
new AlertDialog.Builder(context)
.setTitle("提示")
.setMessage("你选择的wifi无密码,可能不安全,确定继续连接?")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) { // 此处加入连接wifi代码
int netID = linkWifi.CreateWifiInfo2(
wifi, ""); linkWifi.ConnectToNetID(netID);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
return;
}
}).show(); } } });
} /**
* 获取到自定义的ScanResult
**/
public void initScanWifilist(){
MScanWifi mScanwifi;
mScanWifiList=new ArrayList<MScanWifi>();
for(int i=0; i<mWifiList.size();i++){
int level=WifiManager.calculateSignalLevel(mWifiList.get(i).level,4);
String mwifiName=mWifiList.get(i).SSID;
boolean boolean1=false;
if(mWifiList.get(i).capabilities.contains("WEP")||mWifiList.get(i).capabilities.contains("PSK")||
mWifiList.get(i).capabilities.contains("EAP")){
boolean1=true;
}else{
boolean1=false;
}
mScanwifi=new MScanWifi(mWifiList.get(i),mwifiName,level,boolean1);
if(linkWifi.IsExsits(mwifiName)!=null){
mScanwifi.setIsExsit(true);
}
else {mScanwifi.setIsExsit(false);
}
mScanWifiList.add(mScanwifi);
}
} public void registerBroadcast() {
context.registerReceiver(mReceiver, mFilter);
}
public void unregisterBroadcast(){
context.unregisterReceiver(mReceiver);
} /**
* 广播接收,监听网络
*/
private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override
public void onReceive(Context context, Intent intent) {
handleEvent(context, intent);
}
};
public void handleEvent(Context context, Intent intent) {
// TODO Auto-generated method stub
final String action = intent.getAction();
// wifi状态发生改变。
if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
{
/*int wifiState = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE, 0);*/
int wifiState=intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
updateWifiStateChanged(wifiState);
}
else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
updateWifiList(); }
}
/**
* 更新WiFi列表UI
**/
public void updateWifiList(){ final int wifiState = mWifiManager.getWifiState();
//获取WiFi列表并显示
switch (wifiState) {
case WifiManager.WIFI_STATE_ENABLED:
//wifi处于开启状态
initWifiData();
listView.setAdapter(new CommonAdapter<MScanWifi>(context,
mScanWifiList,R.layout.listitems) {
@Override
public void convert(ViewHolder helper, MScanWifi item) {
// TODO Auto-generated method stub
helper.setText(R.id.tv1, item.getWifiName());
//Log.i("1111111", item.getWifiName()+"是否开放"+item.getIsLock());
if(item.getIsLock()){
helper.setImageResource(R.id.img_wifi_level, R.drawable.wifi_signal_lock, item.getLevel());
}else
{helper.setImageResource(R.id.img_wifi_level, R.drawable.wifi_signal_open, item.getLevel());
}
if(item.getIsExsit()){
TextView view=helper.getView(R.id.tv2);
view.setText("已保存");
view.setVisibility(View.VISIBLE);
}
}
});
break;
case WifiManager.WIFI_STATE_ENABLING:
listView.setAdapter(null);
break;//如果WiFi处于正在打开的状态,则清除列表
}
}
/**
* 初始化wifi信息
* mWifiList和mWifiConfiguration
**/
public void initWifiData() {
// TODO Auto-generated method stub
mWifiList=mWifiManager.getScanResults();
mWifiConfiguration=mWifiManager.getConfiguredNetworks();
initScanWifilist();
}
private void updateWifiStateChanged(int state) {
switch (state) {
case WifiManager.WIFI_STATE_ENABLING://正在打开WiFi
wifiSwitch.setEnabled(false);
Log.i("aaaaaa", "正在打开WiFi");
break;
case WifiManager.WIFI_STATE_ENABLED://WiFi已经打开
//setSwitchChecked(true);
wifiSwitch.setEnabled(true);
wifiSwitch.setChecked(true);
layout.removeAllViews();
layout.addView(listView);
mScanner.resume();
Log.i("aaaaaa", "WiFi已经打开");
break;
case WifiManager.WIFI_STATE_DISABLING://正在关闭WiFi
wifiSwitch.setEnabled(false);
Log.i("aaaaaa", "正在关闭WiFi");
break;
case WifiManager.WIFI_STATE_DISABLED://WiFi已经关闭
//setSwitchChecked(false);
wifiSwitch.setEnabled(true);
wifiSwitch.setChecked(false);
layout.removeAllViews();
Log.i("aaaaaa", "WiFi已经关闭 ");
break;
default:
//setSwitchChecked(false);
wifiSwitch.setEnabled(true);
break;
}
mScanner.pause();//移除message通知
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 这个类使用startScan()方法开始扫描wifi
* WiFi扫描结束时系统会发送该广播,
* 用户可以监听该广播通过调用WifiManager
* 的getScanResults方法来获取到扫描结果
* @author zwh
*
*/
public static class Scanner extends Handler {
private final WeakReference<MainActivity> mActivity;
private int mRetry = 0;
public Scanner(MainActivity activity){
mActivity = new WeakReference<MainActivity>(activity);
}
void resume(){
if (!hasMessages(0)) {
sendEmptyMessage(0);
}
} void forceScan() {
removeMessages(0);
sendEmptyMessage(0);
} void pause() {
mRetry = 0;
removeMessages(0);
} @Override
public void handleMessage(Message message) {
if (mActivity.get().mWifiManager.startScan()) {
mRetry = 0;
} else if (++mRetry >= 3) {
mRetry = 0;
return;
}
sendEmptyMessageDelayed(0, 10*1000);//10s后再次发送message
}
} }

CommonAdapter.java和ViewHolder.java是关于ListView适配器部分

项目总结:

  这里不得不说下,我代码可读性真的太差了,一个MainActivity代码那么多,bug还有一大堆没有处理,而且这个switch要限定我的这个apkminSdkVersion="14"手机版本至少14以上,还有弹出对话框其实可以修改成新建一个dialog类减少MainActivity代码达到代码复用。但这些不影响基本功能使用,学到了一些没有接触过了。如判别wifi是否加开放

item.getIsLock()
如果开放显示无锁的wifi信号强度否则相反

显示不同wifi信号强度

如开关切换-样式变化

动态加载xml布局addView(),哦!还有一点改善之处,在非UI线程进行数据处理,当数据处理完后发送消息给ui线程进行数据显示这个不知道可不可以(纸上谈兵)

缺点处处可见,不要介意欢迎提出宝贵意见

源码下载wifiTest

android学习-仿Wifi模块实现的更多相关文章

  1. Android WIFI模块分析

    一:什么是WIFI WIFI是一种无线连接技术.可用于手机.电脑.PDA等终端. WIFI技术产生的目的是改善基于IEEE802.11标准的无线网络产品之间的互通性,也就是说WIFI是基于802.11 ...

  2. 九、Android学习第八天——广播机制与WIFI网络操作(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 九.Android学习第八天——广播机制与WIFI网络操作 今天熟悉了An ...

  3. Android开发—智能家居系列】(二):用手机对WIFI模块进行配置

    在实际开发中,我开发的这款APP是用来连接温控器,并对温控器进行控制的.有图为证,哈哈. 上一篇文章[Android开发—智能家居系列](一):智能家居原理的文末总结中写到: 手机APP控制智能温控器 ...

  4. android 基于wifi模块通信开发

    这篇文章主要是我写完手机与wifi模块通信后所用来总结编写过程的文章,下面,我分几点来说一下编写的大概流程. 一.拉出按钮控件并设置它的点击事件 二.设置wifi权限 三.打开和关闭wifi 四.扫描 ...

  5. 【Android开发—智能家居系列】(三):手机连接WIFI模块

    版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] 概述 实现连接WIFI的功能会用到一个工具类,源码可以点击链接下载.网上这些类似的工具类里的代码差不多是一样的.连接无线网主要有 ...

  6. Android 学习资料收集

    收集整理这份资料灵感来自于 trip_to_iOS, 征得同意引用了该资料的开头描述 收集整理这份资料主要帮助初学者学习 Android 开发, 希望能快速帮助到他们快速入门, 找到适合自己学习资料, ...

  7. Android 学习笔记之网络通信基础+WebView....

    PS:加快学习进度...下周一完成Android网络通信...然后正式进入实战... 学习内容: 1.Android中Http基础... 2.Android中的Socket基础... 3.Androi ...

  8. Android学习——第一个NDK程序

    在前面的学习中,我们已经讲解了关于NDK编程的环境搭建流程,简单的使用我们也通过官网本身自带的例子进行说明了.可是相信大家一定还存在这么的一个疑惑:“如果我要自己利用NDK编写一个Android应用, ...

  9. 十一、Android学习第十天——项目开始(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 十一.Android学习第十天——项目开始 Android知识点的学习告一 ...

随机推荐

  1. hibernate 一对一 one to one的两种配置方式

    hibernate中one-to-one两种配置方式 标签: hibernateHibernateone-to-one 2013-02-19 17:44 11445人阅读 评论(1) 收藏 举报  分 ...

  2. Dwz(J-UI)框架--入门

    http://www.cnblogs.com/chenyongsai/p/4933982.html Dwz(J-UI)框架--入门 一.了解 概述:是中国人自己开发的基于jQuery实现的Ajax R ...

  3. Java Spring 后端项目搭建

    参考了几位同行的Blogs和StackOverflow上的许多问答,搭建了此后端项目,替换原来的node.js后端,和前一篇中搭建的Vue Web App项目配合使用,后端准备只提供服务,不包含后端装 ...

  4. Get User CustomNotificationAddresses

    select pv.StringValue, * from tbl_Identity    i left join tbl_PropertyValue pv on pv.ArtifactId=conv ...

  5. SQL Server 统计信息(Statistics)-概念,原理,应用,维护

    前言:统计信息作为sql server优化器生成执行计划的重要参考,需要数据库开发人员,数据库管理员对其有一定的理解,从而合理高效的应用,管理. 第一部分 概念 统计信息(statistics):描述 ...

  6. 记录.NET Core部署到Linux之发布项目到Linux(2)

    1.选择文件夹发布项目到本地,通过Xftp上传文件到/home/wwwroot下:下面具体介绍下 2.通过Xftp直接拖拽压缩包到linux下,通过命令cd /home/wwwroot目录下;然后输入 ...

  7. 创建自己的Code Snippet(代码模板)

    一.名词解释 Code Snippet,代码模板,是一种快速生成代码的快捷方式,使用它可以有效地提高编程效率. 编程中可以使用Visual Studio提供的预先设置好的Code Snippet,也可 ...

  8. /bin/sh: cc: 未找到命令

    redis 4安装出现 /bin/sh  cc:  未找到命令 解决: yum -y install gcc automake autoconf libtool make

  9. uwp ListView列表滑动特效

    在看过一篇文章 WPF自定义控件之列表滑动特效 PowerListBox  http://www.cnblogs.com/ShenNan/p/4993374.html#3619585 实现了滑动的特效 ...

  10. Day 62 Django第三天

    2.GET请求能够被cache,GET请求能够被保存在浏览器的浏览历史里面(密码等重要数据GET提交,别人查看历史记录,就可以直接看到这些私密数据)POST不进行缓存. 3.GET参数是带在URL后面 ...