最近研究android內核-系統關鍵服務的啓動解析,然而我也不知道研究wifi的做用,就當興趣去作吧(實際上是做業-_-)java
系統原生WiFI功能大概有:啓動WiFI服務,掃描WiFi信息(這個好像已經被封裝到WiFiManager中了),顯示WiFi,鏈接WiFi,關閉WiFi......android
Android提供WifiManager.java對wifi進行管理git
WifiInfo是專門用來表示鏈接的對象,能夠查看當前已鏈接的wifi信息安全
WifiConfiguration是保存已配置過了wifi信息網絡
ScanResult是存放掃描到了全部wifi的一些信息,如wifi名,信號強度,是否加鎖。。。。app
大致步驟:ide
Context.getSystemService(Context.WIFI_SERVICE)來獲取WifiManager對象管理WIFI設備佈局
WifiManager.startScan() 開始掃描測試
WifiManager.getScanResults() 獲取掃描測試的結果ui
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是程序入口(有點累贅了)
1 package com.example.android_wifitest; 2 3 import android.os.Bundle; 4 import android.os.Handler; 5 import android.os.Message; 6 import android.util.Log; 7 8 import java.lang.ref.WeakReference; 9 import java.util.ArrayList; 10 import java.util.List; 11 12 import com.example.android_wifitest.base.CommonAdapter; 13 import com.example.android_wifitest.base.MScanWifi; 14 import com.example.android_wifitest.base.ViewHolder; 15 16 import android.app.Activity; 17 import android.app.AlertDialog; 18 import android.app.Service; 19 import android.content.BroadcastReceiver; 20 import android.content.Context; 21 import android.content.DialogInterface; 22 import android.content.Intent; 23 import android.content.IntentFilter; 24 import android.net.wifi.ScanResult; 25 import android.net.wifi.WifiConfiguration; 26 import android.net.wifi.WifiManager; 27 import android.view.LayoutInflater; 28 import android.view.Menu; 29 import android.view.View; 30 import android.widget.AdapterView; 31 import android.widget.AdapterView.OnItemClickListener; 32 import android.widget.CompoundButton; 33 import android.widget.EditText; 34 import android.widget.LinearLayout; 35 import android.widget.ListView; 36 import android.widget.Switch; 37 import android.widget.TextView; 38 import android.widget.CompoundButton.OnCheckedChangeListener; 39 40 public class MainActivity extends Activity { 41 public WifiManager mWifiManager; 42 public List<MScanWifi> mScanWifiList;//自定義類存放用到的wifi信息 43 public List<ScanResult> mWifiList;//存放系統掃描到了wifi信息 44 public List<WifiConfiguration> mWifiConfiguration;//wifi配置信息 45 public Context context = null; 46 public Scanner mScanner;//自定義handler類每隔10秒自動掃描wifi信息 47 public View view; 48 public TextView wifi_status_txt; 49 public Switch wifiSwitch; 50 public ListView listView; 51 private IntentFilter mFilter; 52 private LinkWifi linkWifi; 53 public LayoutInflater Inflater; 54 private LinearLayout layout; 55 56 @Override 57 protected void onCreate(Bundle savedInstanceState) { 58 super.onCreate(savedInstanceState); 59 setContentView(R.layout.activity_main); 60 context=this; 61 Inflater=LayoutInflater.from(context); 62 mWifiManager=(WifiManager) context.getSystemService(Service.WIFI_SERVICE); 63 mScanner = new Scanner(this); 64 linkWifi=new LinkWifi(context); 65 initView(); 66 initIntentFilter(); 67 registerListener(); 68 registerBroadcast(); 69 } 70 public void initIntentFilter() { 71 // TODO Auto-generated method stub 72 mFilter = new IntentFilter(); 73 mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 74 mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 75 } 76 @Override 77 protected void onResume() { 78 // TODO Auto-generated method stub 79 super.onResume(); 80 //用戶操做activity時更新UI 81 mScanner.forceScan(); 82 } 83 /*@Override 84 protected void onPause() { 85 // TODO Auto-generated method stub 86 super.onPause(); 87 //設備激進入休眠狀態時執行 88 unregisterBroadcast(); 89 }*/ 90 @Override 91 protected void onDestroy() { 92 super.onDestroy(); 93 context.unregisterReceiver(mReceiver); // 註銷此廣播接收器 94 } 95 public void initView() { 96 // TODO Auto-generated method stub 97 //得到要加載listview的佈局 98 layout=(LinearLayout) findViewById(R.id.ListView_LinearLayout); 99 //動態得到listview佈局 100 listView = (ListView) Inflater.inflate( 101 R.layout.my_listview, null).findViewById(R.id.mlistview); 102 wifi_status_txt=(TextView) findViewById(R.id.switch_txt); 103 wifiSwitch=(Switch)findViewById(R.id.switch_status); 104 layout.addView(listView); 105 } 106 public void registerListener() { 107 // TODO Auto-generated method stub 108 wifiSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { 109 110 @Override 111 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 112 // TODO Auto-generated method stub 113 if (buttonView.isChecked()){ 114 wifi_status_txt.setText("開啓"); 115 116 if (!mWifiManager.isWifiEnabled()) { // 當前wifi不可用 117 mWifiManager.setWifiEnabled(true); 118 } 119 mWifiManager.startScan(); 120 121 } 122 else{ 123 wifi_status_txt.setText("關閉"); 124 if (mWifiManager.isWifiEnabled()) { 125 mWifiManager.setWifiEnabled(false); 126 } 127 128 } 129 } 130 }); 131 //給item添加監聽事件 132 listView.setOnItemClickListener(new OnItemClickListener() { 133 134 @Override 135 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 136 // TODO Auto-generated method stub 137 // 本機已經配置過的wifi 138 final ScanResult wifi=mScanWifiList.get(position).scanResult; 139 final WifiConfiguration wifiConfig=linkWifi.IsExsits(wifi.SSID); 140 if(wifiConfig!= null){ 141 final int netID = wifiConfig.networkId; 142 String actionStr; 143 // 若是目前鏈接了此網絡 144 if (mWifiManager.getConnectionInfo().getNetworkId() == netID) { 145 actionStr = "斷開"; 146 } else { 147 actionStr = "鏈接"; 148 } 149 android.app.AlertDialog.Builder builder=new AlertDialog.Builder(context); 150 builder.setTitle("提示"); 151 builder.setMessage("請選擇你要進行的操做?"); 152 builder.setPositiveButton(actionStr, 153 new DialogInterface.OnClickListener() { 154 public void onClick(DialogInterface dialog, 155 int whichButton) { 156 157 if (mWifiManager.getConnectionInfo() 158 .getNetworkId() == netID) { 159 mWifiManager.disconnect(); 160 } else { 161 162 linkWifi.setMaxPriority(wifiConfig); 163 linkWifi.ConnectToNetID(wifiConfig.networkId); 164 } 165 166 } 167 }); 168 builder.setNeutralButton("忘記", 169 new DialogInterface.OnClickListener() { 170 public void onClick(DialogInterface dialog, 171 int whichButton) { 172 mWifiManager.removeNetwork(netID); 173 return; 174 } 175 }); 176 builder.setNegativeButton("取消", 177 new DialogInterface.OnClickListener() { 178 public void onClick(DialogInterface dialog, 179 int whichButton) { 180 return; 181 } 182 }); 183 builder.show(); 184 185 return; 186 187 } 188 if (mScanWifiList.get(position).getIsLock()) { 189 // 有密碼,提示輸入密碼進行鏈接 190 191 // final String encryption = capabilities; 192 193 LayoutInflater factory = LayoutInflater.from(context); 194 final View inputPwdView = factory.inflate(R.layout.dialog_inputpwd, 195 null); 196 new AlertDialog.Builder(context) 197 .setTitle("請輸入該無線的鏈接密碼") 198 .setMessage("無線SSID:" + wifi.SSID) 199 .setIcon(android.R.drawable.ic_dialog_info) 200 .setView(inputPwdView) 201 .setPositiveButton("肯定", 202 new DialogInterface.OnClickListener() { 203 public void onClick(DialogInterface dialog, 204 int which) { 205 EditText pwd = (EditText) inputPwdView 206 .findViewById(R.id.etPassWord); 207 String wifipwd = pwd.getText().toString(); 208 209 // 此處加入鏈接wifi代碼 210 int netID = linkWifi.CreateWifiInfo2( 211 wifi, wifipwd); 212 213 linkWifi.ConnectToNetID(netID); 214 } 215 }) 216 .setNegativeButton("取消", 217 new DialogInterface.OnClickListener() { 218 @Override 219 public void onClick(DialogInterface dialog, 220 int which) { 221 } 222 }).setCancelable(false).show(); 223 224 } else { 225 // 無密碼 226 new AlertDialog.Builder(context) 227 .setTitle("提示") 228 .setMessage("你選擇的wifi無密碼,可能不安全,肯定繼續鏈接?") 229 .setPositiveButton("肯定", 230 new DialogInterface.OnClickListener() { 231 public void onClick(DialogInterface dialog, 232 int whichButton) { 233 234 // 此處加入鏈接wifi代碼 235 int netID = linkWifi.CreateWifiInfo2( 236 wifi, ""); 237 238 linkWifi.ConnectToNetID(netID); 239 } 240 }) 241 .setNegativeButton("取消", 242 new DialogInterface.OnClickListener() { 243 public void onClick(DialogInterface dialog, 244 int whichButton) { 245 return; 246 } 247 }).show(); 248 249 } 250 251 } 252 253 }); 254 } 255 256 /** 257 * 獲取到自定義的ScanResult 258 **/ 259 public void initScanWifilist(){ 260 MScanWifi mScanwifi; 261 mScanWifiList=new ArrayList<MScanWifi>(); 262 for(int i=0; i<mWifiList.size();i++){ 263 int level=WifiManager.calculateSignalLevel(mWifiList.get(i).level,4); 264 String mwifiName=mWifiList.get(i).SSID; 265 boolean boolean1=false; 266 if(mWifiList.get(i).capabilities.contains("WEP")||mWifiList.get(i).capabilities.contains("PSK")|| 267 mWifiList.get(i).capabilities.contains("EAP")){ 268 boolean1=true; 269 }else{ 270 boolean1=false; 271 } 272 mScanwifi=new MScanWifi(mWifiList.get(i),mwifiName,level,boolean1); 273 if(linkWifi.IsExsits(mwifiName)!=null){ 274 mScanwifi.setIsExsit(true); 275 } 276 else {mScanwifi.setIsExsit(false); 277 } 278 mScanWifiList.add(mScanwifi); 279 } 280 }
281 public void registerBroadcast() { 282 context.registerReceiver(mReceiver, mFilter); 283 } 284 public void unregisterBroadcast(){ 285 context.unregisterReceiver(mReceiver); 286 } 287 288 /** 289 * 廣播接收,監聽網絡 290 */ 291 private BroadcastReceiver mReceiver = new BroadcastReceiver() { 292 293 @Override 294 public void onReceive(Context context, Intent intent) { 295 handleEvent(context, intent); 296 } 297 }; 298 public void handleEvent(Context context, Intent intent) { 299 // TODO Auto-generated method stub 300 final String action = intent.getAction(); 301 // wifi狀態發生改變。 302 if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) 303 { 304 /*int wifiState = intent.getIntExtra( 305 WifiManager.EXTRA_WIFI_STATE, 0);*/ 306 int wifiState=intent.getIntExtra( 307 WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN); 308 updateWifiStateChanged(wifiState); 309 } 310 else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { 311 updateWifiList(); 312 313 } 314 } 315 /** 316 * 更新WiFi列表UI 317 **/ 318 public void updateWifiList(){ 319 320 final int wifiState = mWifiManager.getWifiState(); 321 //獲取WiFi列表並顯示 322 switch (wifiState) { 323 case WifiManager.WIFI_STATE_ENABLED: 324 //wifi處於開啓狀態 325 initWifiData(); 326 listView.setAdapter(new CommonAdapter<MScanWifi>(context, 327 mScanWifiList,R.layout.listitems) { 328 @Override 329 public void convert(ViewHolder helper, MScanWifi item) { 330 // TODO Auto-generated method stub 331 helper.setText(R.id.tv1, item.getWifiName()); 332 //Log.i("1111111", item.getWifiName()+"是否開放"+item.getIsLock()); 333 if(item.getIsLock()){ 334 helper.setImageResource(R.id.img_wifi_level, R.drawable.wifi_signal_lock, item.getLevel()); 335 }else 336 {helper.setImageResource(R.id.img_wifi_level, R.drawable.wifi_signal_open, item.getLevel()); 337 } 338 if(item.getIsExsit()){ 339 TextView view=helper.getView(R.id.tv2); 340 view.setText("已保存"); 341 view.setVisibility(View.VISIBLE); 342 } 343 } 344 }); 345 break; 346 case WifiManager.WIFI_STATE_ENABLING: 347 listView.setAdapter(null); 348 break;//若是WiFi處於正在打開的狀態,則清除列表 349 } 350 } 351 /** 352 * 初始化wifi信息 353 * mWifiList和mWifiConfiguration 354 **/ 355 public void initWifiData() { 356 // TODO Auto-generated method stub 357 mWifiList=mWifiManager.getScanResults(); 358 mWifiConfiguration=mWifiManager.getConfiguredNetworks(); 359 initScanWifilist(); 360 } 361 private void updateWifiStateChanged(int state) { 362 switch (state) { 363 case WifiManager.WIFI_STATE_ENABLING://正在打開WiFi 364 wifiSwitch.setEnabled(false); 365 Log.i("aaaaaa", "正在打開WiFi"); 366 break; 367 case WifiManager.WIFI_STATE_ENABLED://WiFi已經打開 368 //setSwitchChecked(true); 369 wifiSwitch.setEnabled(true); 370 wifiSwitch.setChecked(true); 371 layout.removeAllViews(); 372 layout.addView(listView); 373 mScanner.resume(); 374 Log.i("aaaaaa", "WiFi已經打開"); 375 break; 376 case WifiManager.WIFI_STATE_DISABLING://正在關閉WiFi 377 wifiSwitch.setEnabled(false); 378 Log.i("aaaaaa", "正在關閉WiFi"); 379 break; 380 case WifiManager.WIFI_STATE_DISABLED://WiFi已經關閉 381 //setSwitchChecked(false); 382 wifiSwitch.setEnabled(true); 383 wifiSwitch.setChecked(false); 384 layout.removeAllViews(); 385 Log.i("aaaaaa", "WiFi已經關閉 "); 386 break; 387 default: 388 //setSwitchChecked(false); 389 wifiSwitch.setEnabled(true); 390 break; 391 } 392 mScanner.pause();//移除message通知 393 } 394 @Override 395 public boolean onCreateOptionsMenu(Menu menu) { 396 // Inflate the menu; this adds items to the action bar if it is present. 397 getMenuInflater().inflate(R.menu.main, menu); 398 return true; 399 } 400 /** 401 * 這個類使用startScan()方法開始掃描wifi 402 * WiFi掃描結束時系統會發送該廣播, 403 * 用戶能夠監聽該廣播經過調用WifiManager 404 * 的getScanResults方法來獲取到掃描結果 405 * @author zwh 406 * 407 */ 408 public static class Scanner extends Handler { 409 private final WeakReference<MainActivity> mActivity; 410 private int mRetry = 0; 411 public Scanner(MainActivity activity){ 412 mActivity = new WeakReference<MainActivity>(activity); 413 } 414 void resume(){ 415 if (!hasMessages(0)) { 416 sendEmptyMessage(0); 417 } 418 } 419 420 void forceScan() { 421 removeMessages(0); 422 sendEmptyMessage(0); 423 } 424 425 void pause() { 426 mRetry = 0; 427 removeMessages(0); 428 } 429 430 @Override 431 public void handleMessage(Message message) { 432 if (mActivity.get().mWifiManager.startScan()) { 433 mRetry = 0; 434 } else if (++mRetry >= 3) { 435 mRetry = 0; 436 return; 437 } 438 sendEmptyMessageDelayed(0, 10*1000);//10s後再次發送message 439 } 440 } 441 442 }
CommonAdapter.java和ViewHolder.java是關於ListView適配器部分
項目總結:
這裏不得不說下,我代碼可讀性真的太差了,一個MainActivity代碼那麼多,bug還有一大堆沒有處理,並且這個switch要限定個人這個apkminSdkVersion="14"手機版本至少14以上,還有彈出對話框其實能夠修改爲新建一個dialog類減小MainActivity代碼達到代碼複用。但這些不影響基本功能使用,學到了一些沒有接觸過了。如判別wifi是否加開放
item.getIsLock()
若是開放顯示無鎖的wifi信號強度不然相反
顯示不一樣wifi信號強度
如開關切換-樣式變化
動態加載xml佈局addView(),哦!還有一點改善之處,在非UI線程進行數據處理,當數據處理完後發送消息給ui線程進行數據顯示這個不知道可不能夠(紙上談兵)
缺點到處可見,不要介意歡迎提出寶貴意見
源碼下載wifiTest