Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android連接Wifi詳細源碼

Android連接Wifi詳細源碼

編輯:關於Android編程

因項目需求,做一個有關wifi的Demo,現已經上傳到GitHub 上面地址:https://github.com/git-xuhao/WifiDemo

源碼片段

package woyou.wifidemo.ui.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import woyou.wifidemo.R; import woyou.wifidemo.ui.adapter.MyListViewAdapter; import woyou.wifidemo.ui.api.OnNetworkChangeListener; import woyou.wifidemo.ui.component.MyListView; import woyou.wifidemo.ui.dialog.WifiConnDialog; import woyou.wifidemo.ui.dialog.WifiStatusDialog; import woyou.wifidemo.utils.WifiAdminUtils; /** * Created by Xiho on 2016/2/2. */ public class MainActivity extends ActionBarActivity { protected static final String TAG = "MainActivity"; private static final int REFRESH_CONN = 100; // Wifi管理類 private WifiAdminUtils mWifiAdmin; // 掃描結果列表 private List list = new ArrayList(); // 顯示列表 private MyListView listView; private MyListViewAdapter mAdapter; //下標 private int mPosition; private WifiReceiver mReceiver; private OnNetworkChangeListener mOnNetworkChangeListener = new OnNetworkChangeListener() { @Override public void onNetWorkDisConnect() { getWifiListInfo(); mAdapter.setDatas(list); mAdapter.notifyDataSetChanged(); } @Override public void onNetWorkConnect() { getWifiListInfo(); mAdapter.setDatas(list); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } mAdapter.notifyDataSetChanged(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); initView(); setListener(); refreshWifiStatusOnTime(); } /** * 初始化數據 */ private void initData() { mWifiAdmin = new WifiAdminUtils(MainActivity.this); // 獲得Wifi列表信息 getWifiListInfo(); } /** * 初始化View */ private void initView() { listView = (MyListView) findViewById(R.id.freelook_listview); mAdapter = new MyListViewAdapter(this, list); listView.setAdapter(mAdapter); //檢查當前wifi狀態 int wifiState = mWifiAdmin.checkState(); //WIFI_STATE_DISABLED WIFI網卡不可用 //WIFI_STATE_DISABLING WIFI網卡正在關閉 //WIFI_STATE_ENABLED WIFI網卡狀態未知 if (wifiState == WifiManager.WIFI_STATE_DISABLED || wifiState == WifiManager.WIFI_STATE_DISABLING || wifiState == WifiManager.WIFI_STATE_UNKNOWN) { } else { } } private void registerReceiver() { mReceiver = new WifiReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mReceiver, filter); } private void setListener() { // 設置刷新監聽 listView.setonRefreshListener(new MyListView.OnRefreshListener() { @Override public void onRefresh() { new AsyncTask() { protected Void doInBackground(Void... params) { try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } getWifiListInfo(); return null; } @Override protected void onPostExecute(Void result) { mAdapter.setDatas(list); mAdapter.notifyDataSetChanged(); listView.onRefreshComplete(); } }.execute(); } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterViewparent, View view, int pos, long id) { mPosition = pos - 1; ScanResult scanResult = list.get(mPosition); String desc = ""; String descOri = scanResult.capabilities; if (descOri.toUpperCase().contains("WPA-PSK")) { desc = "WPA"; } if (descOri.toUpperCase().contains("WPA2-PSK")) { desc = "WPA2"; } if (descOri.toUpperCase().contains("WPA-PSK") && descOri.toUpperCase().contains("WPA2-PSK")) { desc = "WPA/WPA2"; } if (desc.equals("")) { isConnectSelf(scanResult); return; } isConnect(scanResult); } /** * 有密碼驗證連接 * @param scanResult */ private void isConnect(ScanResult scanResult) { if (mWifiAdmin.isConnect(scanResult)) { // 已連接,顯示連接狀態對話框 WifiStatusDialog mStatusDialog = new WifiStatusDialog( MainActivity.this, R.style.defaultDialogStyle, scanResult, mOnNetworkChangeListener); mStatusDialog.show(); } else { // 未連接顯示連接輸入對話框 WifiConnDialog mDialog = new WifiConnDialog( MainActivity.this, R.style.defaultDialogStyle, listView, mPosition, mAdapter, scanResult, list, mOnNetworkChangeListener); mDialog.show(); } } /** * 無密碼直連 * @param scanResult */ private void isConnectSelf(ScanResult scanResult) { if (mWifiAdmin.isConnect(scanResult)) { // 已連接,顯示連接狀態對話框 WifiStatusDialog mStatusDialog = new WifiStatusDialog( MainActivity.this, R.style.defaultDialogStyle, scanResult, mOnNetworkChangeListener); mStatusDialog.show(); } else { boolean iswifi = mWifiAdmin.connectSpecificAP(scanResult); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (iswifi) { Toast.makeText(MainActivity.this, "連接成功!",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "連接失敗!", Toast.LENGTH_SHORT).show(); } } } }); } /** * 得到wifi的列表信息 */ private void getWifiListInfo() { Log.d(TAG, "getWifiListInfo"); mWifiAdmin.startScan(); List tmpList = mWifiAdmin.getWifiList(); if (tmpList == null) { list.clear(); } else { list = tmpList; } } private Handler mHandler = new MyHandler(this); protected boolean isUpdate = true; @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } private static class MyHandler extends Handler { private WeakReference reference; public MyHandler(MainActivity activity) { this.reference = new WeakReference(activity); } @Override public void handleMessage(Message msg) { MainActivity activity = reference.get(); switch (msg.what) { case REFRESH_CONN: activity.getWifiListInfo(); activity.mAdapter.setDatas(activity.list); activity.mAdapter.notifyDataSetChanged(); break; default: break; } super.handleMessage(msg); } } /** * 定時刷新Wifi列表信息 * * @author Xiho */ private void refreshWifiStatusOnTime() { new Thread() { public void run() { while (isUpdate) { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } mHandler.sendEmptyMessage(REFRESH_CONN); } } }.start(); } @Override protected void onResume() { super.onResume(); registerReceiver(); } @Override protected void onDestroy() { super.onDestroy(); isUpdate = false; unregisterReceiver(); } /** * 取消廣播 */ private void unregisterReceiver() { if (mReceiver != null) { unregisterReceiver(mReceiver); } } private class WifiReceiver extends BroadcastReceiver { protected static final String TAG = "MainActivity"; //記錄網絡斷開的狀態 private boolean isDisConnected = false; //記錄正在連接的狀態 private boolean isConnecting = false; @Override public void onReceive(Context context, Intent intent) { final String action=intent.getAction(); if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {// wifi連接上與否 Log.d(TAG, "網絡已經改變"); NetworkInfo info = intent .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) { if (!isDisConnected) { Log.d(TAG, "wifi已經斷開"); isDisConnected = true; } } else if (info.getState().equals(NetworkInfo.State.CONNECTING)) { if (!isConnecting) { Log.d(TAG, "正在連接..."); isConnecting = true; } } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) { WifiManager wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); Log.d(TAG, "連接到網絡:" + wifiInfo.getBSSID()); } } else if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 0); switch (error) { case WifiManager.ERROR_AUTHENTICATING: Log.d(TAG, "密碼認證錯誤Code為:" + error); Toast.makeText(getApplicationContext(), "wifi密碼認證錯誤!", Toast.LENGTH_SHORT).show(); break; default: break; } } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0); Log.e("H3c", "wifiState" + wifiState); switch (wifiState) { case WifiManager.WIFI_STATE_ENABLING: Log.d(TAG, "wifi正在啟用"); break; case WifiManager.WIFI_STATE_ENABLED: Log.d(TAG, "Wi-Fi已啟用。"); mWifiAdmin.startScan(); break; } } } } }

源碼截圖

 

\

 

 

\

 

掃描Wifi列表的主頁面

 

\

 

連接wifi的對話框

 

\

 

查看已連接wifi狀態信息

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved