1. 程式人生 > >Android6.0 連線指定的wifi

Android6.0 連線指定的wifi

android6.0之後 wifi機制有了變化,如果連線的wifi沒有網路,那麼系統會自動切換Wi-Fi。這個可能對我們wifi方面的開發有影響,比如,我們要求連線wifi的本身就是不能訪問外網的,僅僅是為了兩個裝置之間的通訊,這個時候,我們就需要一點小處理。
開發wifi方面的就必須要掌握WifiManager這個類,所有對android的wifi操作都是通過這個類,這裡為了方便使用,封裝了一下WifiManager這個類。

package com.lake.wifiutilsdemo;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import
android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.text.TextUtils; import android.util.Log; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; /** * Created by lake on 2017/10/17. * [email protected] */ public class WifiAutoConnectManager {
private static final String TAG = WifiAutoConnectManager.class .getSimpleName(); public static WifiManager wifiManager = null; private static WifiAutoConnectManager mWifiAutoConnectManager; // 定義幾種加密方式,一種是WEP,一種是WPA,還有沒有密碼的情況 public enum WifiCipherType { WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID } // 建構函式
private WifiAutoConnectManager(WifiManager wifiManager) { this.wifiManager = wifiManager; } public static WifiAutoConnectManager newInstance(WifiManager wifiManager) { if (mWifiAutoConnectManager == null) { mWifiAutoConnectManager = new WifiAutoConnectManager(wifiManager); } return mWifiAutoConnectManager; } // 檢視以前是否也配置過這個網路 public WifiConfiguration isExsits(String SSID) { List<WifiConfiguration> existingConfigs = wifiManager .getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\"" + SSID + "\"")) { return existingConfig; } } return null; } /** * 建立wifi配置檔案 * * @param SSID * @param Password * @param Type * @return */ public WifiConfiguration createWifiInfo(String SSID, String Password, WifiCipherType Type) { WifiConfiguration config = new WifiConfiguration(); config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); config.SSID = "\"" + SSID + "\""; // config.SSID = SSID; // nopass if (Type == WifiCipherType.WIFICIPHER_NOPASS) { // config.wepKeys[0] = ""; config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); // config.wepTxKeyIndex = 0; } else if (Type == WifiCipherType.WIFICIPHER_WEP) {// wep if (!TextUtils.isEmpty(Password)) { if (isHexWepKey(Password)) { config.wepKeys[0] = Password; } else { config.wepKeys[0] = "\"" + Password + "\""; } } config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.wepTxKeyIndex = 0; } else if (Type == WifiCipherType.WIFICIPHER_WPA) {// wpa config.preSharedKey = "\"" + Password + "\""; config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 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); config.status = WifiConfiguration.Status.ENABLED; } return config; } // 開啟wifi功能 public boolean openWifi() { boolean bRet = true; if (!wifiManager.isWifiEnabled()) { bRet = wifiManager.setWifiEnabled(true); } return bRet; } // 關閉WIFI private void closeWifi() { if (wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(false); } } private static boolean isHexWepKey(String wepKey) { final int len = wepKey.length(); // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) if (len != 10 && len != 26 && len != 58) { return false; } return isHex(wepKey); } private static boolean isHex(String key) { for (int i = key.length() - 1; i >= 0; i--) { final char c = key.charAt(i); if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { return false; } } return true; } /** * 根據給定的ssid訊號量和總級別,判斷當前訊號量,在什麼級別 * * @param rssi * @param numLevels * @return */ public static int getSignalNumsLevel(int rssi, int numLevels) { if (wifiManager == null) { return -1; } return WifiManager.calculateSignalLevel(rssi, numLevels); } /** * 獲取ssid的加密方式 */ public static WifiCipherType getCipherType(String ssid) { if (wifiManager == null) { return null; } List<ScanResult> list = wifiManager.getScanResults(); for (ScanResult scResult : list) { if (!TextUtils.isEmpty(scResult.SSID) && scResult.SSID.equals(ssid)) { String capabilities = scResult.capabilities; if (!TextUtils.isEmpty(capabilities)) { if (capabilities.contains("WPA") || capabilities.contains("wpa")) { Log.e("wifidemo", "wpa"); return WifiCipherType.WIFICIPHER_WPA; } else if (capabilities.contains("WEP") || capabilities.contains("wep")) { Log.e("wifidemo", "wep"); return WifiCipherType.WIFICIPHER_WEP; } else { Log.e("wifidemo", "no"); return WifiCipherType.WIFICIPHER_NOPASS; } } } } return WifiCipherType.WIFICIPHER_INVALID; } /** * 獲取 bssid 接入點的地址 * @return */ public static String getBSSID() { if (wifiManager == null) { return null; } WifiInfo info = wifiManager.getConnectionInfo(); Log.e("wifidemo", "getBSSID" + info.getBSSID()); if (info == null) { return null; } return info.getBSSID(); } /** * 獲取閘道器地址 * * @return */ public static String getGateway() { if (wifiManager == null) { return ""; } InetAddress inetAddress = NetworkUtils.intToInetAddress(wifiManager.getDhcpInfo().gateway); if (inetAddress == null) { return ""; } return inetAddress.getHostAddress(); } /** * 獲取ip地址 * @return */ public static String getIpAddress(){ if (wifiManager == null) { return ""; } InetAddress inetAddress = NetworkUtils.intToInetAddress(wifiManager.getConnectionInfo().getIpAddress()); if (inetAddress == null) { return ""; } return inetAddress.getHostAddress(); } /** * 獲取mac地址 * @return */ public static String getMacAddress(){ if (wifiManager == null) { return ""; } return wifiManager.getConnectionInfo().getMacAddress(); } /** * 獲取wifi名稱 * * @return */ public static String getSSID() { if (wifiManager == null) { return null; } WifiInfo info = wifiManager.getConnectionInfo(); String ssid = info.getSSID(); if (ssid != null) { ssid = ssid.substring(1, ssid.length() - 1); } return ssid; } /** * 掃描WIFI AP */ public static boolean startStan() { if (wifiManager == null) { return false; } return wifiManager.startScan(); } /** * 獲取所有WIFI AP */ public static List<ScanResult> getScanResults() { List<ScanResult> srList = wifiManager.getScanResults(); if (srList == null) { srList = new ArrayList<ScanResult>(); } return srList; } } NetworkUtils類: package com.lake.wifiutilsdemo; import java.net.InetAddress; import java.net.UnknownHostException; public class NetworkUtils { /** * Convert a IPv4 address from an integer to an InetAddress. * * @param hostAddress * an int corresponding to the IPv4 address in network byte order */ public static InetAddress intToInetAddress(int hostAddress) { byte[] addressBytes = { (byte) (0xff & hostAddress), (byte) (0xff & (hostAddress >> 8)), (byte) (0xff & (hostAddress >> 16)), (byte) (0xff & (hostAddress >> 24)) }; try { return InetAddress.getByAddress(addressBytes); } catch (UnknownHostException e) { throw new AssertionError(); } } /** * Convert a IPv4 address from an InetAddress to an integer * * @param inetAddr * is an InetAddress corresponding to the IPv4 address * @return the IP address as an integer in network byte order */ public static int inetAddressToInt(InetAddress inetAddr) throws IllegalArgumentException { byte[] addr = inetAddr.getAddress(); return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | ((addr[1] & 0xff) << 8) | (addr[0] & 0xff); } }

使用方法請看一下activity的程式碼:

package com.lake.wifiutilsdemo;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    TextView mWifiState;//wifi狀態
    TextView mWifiName;//Wi-Fi名稱
    TextView mMac;//實體地址
    TextView mIP;//ip地址
    TextView mGateway;//閘道器地址
    ListView mListWifi;//Wi-Fi列表
    Button mBtnSearch;//搜尋Wi-Fi
    Button mBtnConnect;//連線Wi-Fi
    WifiListAdapter mWifiListAdapter;
    public static final int WIFI_SCAN_PERMISSION_CODE = 2;
    WorkAsyncTask mWorkAsyncTask = null;
    ConnectAsyncTask mConnectAsyncTask = null;
    List<ScanResult> mScanResultList = new ArrayList<>();
    String ssid = "";
    WifiAutoConnectManager.WifiCipherType type = WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS;
    String password = "11111111";
    FrameLayout progressbar;
    boolean isLinked = false;

    String gateway = "";
    String mac = "";
    /**
     * 處理訊號量改變或者掃描結果改變的廣播
     */
    private BroadcastReceiver mWifiSearchBroadcastReceiver;
    private IntentFilter mWifiSearchIntentFilter;
    private BroadcastReceiver mWifiConnectBroadcastReceiver;
    private IntentFilter mWifiConnectIntentFilter;
    private WifiAutoConnectManager mWifiAutoConnectManager;

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mWifiSearchBroadcastReceiver, mWifiSearchIntentFilter);
        registerReceiver(mWifiConnectBroadcastReceiver, mWifiConnectIntentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mWifiSearchBroadcastReceiver);
        unregisterReceiver(mWifiConnectBroadcastReceiver);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intiView();
        //初始化wifi工具
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        mWifiAutoConnectManager = WifiAutoConnectManager.newInstance(wifiManager);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 獲取wifi連線需要定位許可權,沒有獲取許可權
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
            }, WIFI_SCAN_PERMISSION_CODE);
            return;
        }
        //設定監聽wifi狀態變化廣播
        initWifiSate();
    }

    private void initWifiSate() {
        //wifi 搜尋結果接收廣播
        mWifiSearchBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {// 掃描結果改表
                    mScanResultList = WifiAutoConnectManager.getScanResults();
                    if (mWifiListAdapter != null) {
                        mWifiListAdapter.setmWifiList(mScanResultList);
                        mWifiListAdapter.notifyDataSetChanged();
                    }
                }
            }
        };
        mWifiSearchIntentFilter = new IntentFilter();
        mWifiSearchIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mWifiSearchIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mWifiSearchIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);

        //wifi 狀態變化接收廣播
        mWifiConnectBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                    int wifState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
                    if (wifState != WifiManager.WIFI_STATE_ENABLED) {
                        Toast.makeText(MainActivity.this, "沒有wifi", Toast.LENGTH_SHORT).show();
                    }
                } else if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
                    int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                    Log.e("wifidemo", ssid + "linkWifiResult:" + linkWifiResult);
                    if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
                        Log.e("wifidemo", ssid + "onReceive:密碼錯誤");
                    }
                } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                    NetworkInfo.DetailedState state = ((NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)).getDetailedState();
                    setWifiState(state);
                }
            }
        };
        mWifiConnectIntentFilter = new IntentFilter();
        mWifiConnectIntentFilter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);
        mWifiConnectIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mWifiConnectIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        mWifiConnectIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    }

    /**
     * 顯示wifi狀態
     *
     * @param state
     */
    public void setWifiState(final NetworkInfo.DetailedState state) {
        if (state == NetworkInfo.DetailedState.AUTHENTICATING) {

        } else if (state == NetworkInfo.DetailedState.BLOCKED) {

        } else if (state == NetworkInfo.DetailedState.CONNECTED) {
            progressbar.setVisibility(View.GONE);
            isLinked = true;
            mWifiState.setText("wifi state:連線成功");
            mWifiName.setText("wifi name:" + WifiAutoConnectManager.getSSID());
            mIP.setText("ip address:" + WifiAutoConnectManager.getIpAddress());
            mGateway.setText("gateway:" + WifiAutoConnectManager.getGateway());
            mMac.setText("mac:" + WifiAutoConnectManager.getMacAddress());
            gateway = WifiAutoConnectManager.getGateway();
            mac = WifiAutoConnectManager.getMacAddress();
        } else if (state == NetworkInfo.DetailedState.CONNECTING) {
            isLinked = false;
            mWifiState.setText("wifi state:連線中...");
            mWifiName.setText("wifi name:" + WifiAutoConnectManager.getSSID());
            mIP.setText("ip address");
            mGateway.setText("gateway");
        } else if (state == NetworkInfo.DetailedState.DISCONNECTED) {
            isLinked = false;
            mWifiState.setText("wifi state:斷開連線");
            mWifiName.setText("wifi name");
            mIP.setText("ip address");
            mGateway.setText("gateway");
        } else if (state == NetworkInfo.DetailedState.DISCONNECTING) {
            isLinked = false;
            mWifiState.setText("wifi state:斷開連線中...");
        } else if (state == NetworkInfo.DetailedState.FAILED) {
            isLinked = false;
            mWifiState.setText("wifi state:連線失敗");
        } else if (state == NetworkInfo.DetailedState.IDLE) {

        } else if (state == NetworkInfo.DetailedState.OBTAINING_IPADDR) {

        } else if (state == NetworkInfo.DetailedState.SCANNING) {

        } else if (state == NetworkInfo.DetailedState.SUSPENDED) {

        }
    }

    private void intiView() {
        progressbar = (FrameLayout) findViewById(R.id.progressbar);
        mWifiState = (TextView) findViewById(R.id.wifi_state);
        mWifiName = (TextView) findViewById(R.id.wifi_name);
        mMac = (TextView) findViewById(R.id.wifi_mac);
        mIP = (TextView) findViewById(R.id.ip_address);
        mGateway = (TextView) findViewById(R.id.ip_gateway);
        mListWifi = (ListView) findViewById(R.id.list_wifi);
        mBtnSearch = (Button) findViewById(R.id.search_wifi);
        mBtnConnect = (Button) findViewById(R.id.connect_wifi);

        mBtnSearch.setOnClickListener(this);
        mBtnConnect.setOnClickListener(this);

        mListWifi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mWifiListAdapter.setSelectItem(i);
                mWifiListAdapter.notifyDataSetChanged();
                ScanResult scanResult = mScanResultList.get(i);
                ssid = scanResult.SSID;
                type = WifiAutoConnectManager.getCipherType(ssid);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_wifi:
                if (mWorkAsyncTask != null) {
                    mWorkAsyncTask.cancel(true);
                    mWorkAsyncTask = null;
                }
                mWorkAsyncTask = new WorkAsyncTask();
                mWorkAsyncTask.execute();
                break;
            case R.id.connect_wifi:
                if (ssid.equals(WifiAutoConnectManager.getSSID())) {
                    return;
                }
                if (mConnectAsyncTask != null) {
                    mConnectAsyncTask.cancel(true);
                    mConnectAsyncTask = null;
                }
                mConnectAsyncTask = new ConnectAsyncTask(ssid, password, type);
                mConnectAsyncTask.execute();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case WIFI_SCAN_PERMISSION_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // 不允許
                    Toast.makeText(this, "開啟許可權失敗", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 獲取wifi列表
     */
    private class WorkAsyncTask extends AsyncTask<Void, Void, List<ScanResult>> {
        private List<ScanResult> mScanResult = new ArrayList<>();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressbar.setVisibility(View.VISIBLE);
        }

        @Override
        protected List<ScanResult> doInBackground(Void... params) {
            if (WifiAutoConnectManager.startStan()) {
                mScanResult = WifiAutoConnectManager.getScanResults();
            }
            List<ScanResult> filterScanResultList = new ArrayList<>();
            if (mScanResult != null) {
                for (ScanResult wifi : mScanResult) {
                    filterScanResultList.add(wifi);
                    Log.e("wifidemo", "doInBackground: wifi:" + wifi);
                }
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return filterScanResultList;
        }

        @Override
        protected void onPostExecute(final List<ScanResult> result) {
            super.onPostExecute(result);
            progressbar.setVisibility(View.GONE);
            mScanResultList = result;
            mWifiListAdapter = new WifiListAdapter(result, LayoutInflater.from(MainActivity.this));
            mListWifi.setAdapter(mWifiListAdapter);

        }
    }

    /**
     * wifi列表介面卡
     */
    class WifiListAdapter extends BaseAdapter {

        private List<ScanResult> mWifiList;
        private LayoutInflater mLayoutInflater;

        public WifiListAdapter(List<ScanResult> wifiList, LayoutInflater layoutInflater) {
            this.mWifiList = wifiList;
            this.mLayoutInflater = layoutInflater;
        }

        @Override
        public int getCount() {
            return mWifiList.size();
        }

        @Override
        public Object getItem(int position) {
            return mWifiList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = mLayoutInflater.inflate(R.layout.fragment_wifi_list_item, null);
            }
            ScanResult sr = mWifiList.get(position);
            convertView.setTag(sr);
            TextView textView = (TextView) convertView.findViewById(R.id.wifi_item_name);
            int numLevel = WifiAutoConnectManager.getSignalNumsLevel(sr.level, 5);
            String password = sr.capabilities;
            String text = "加密方式:";
            if (password.contains("WPA") || password.contains("wpa")) {
                password = "WPA";
            } else if (password.contains("WEP") || password.contains("wep")) {
                password = "WEP";
            } else {
                text = "";
                password = "";
            }
            textView.setText(sr.SSID + " " + text + password + "  訊號強度:" + numLevel);
            convertView.setBackgroundColor(Color.WHITE);
            if (position == selectItem) {
                convertView.setBackgroundColor(Color.GRAY);
            }
            return convertView;
        }

        public void setSelectItem(int selectItem) {
            this.selectItem = selectItem;
        }

        private int selectItem = -1;

        public void setmWifiList(List<ScanResult> mWifiList) {
            this.mWifiList = mWifiList;
        }
    }


    /**
     * 連線指定的wifi
     */
    class ConnectAsyncTask extends AsyncTask<Void, Void, Boolean> {
        private String ssid;
        private String password;
        private WifiAutoConnectManager.WifiCipherType type;
        WifiConfiguration tempConfig;

        public ConnectAsyncTask(String ssid, String password, WifiAutoConnectManager.WifiCipherType type) {
            this.ssid = ssid;
            this.password = password;
            this.type = type;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressbar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            // 開啟wifi
            mWifiAutoConnectManager.openWifi();
            // 開啟wifi功能需要一段時間(我在手機上測試一般需要1-3秒左右),所以要等到wifi
            // 狀態變成WIFI_STATE_ENABLED的時候才能執行下面的語句
            while (mWifiAutoConnectManager.wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
                try {
                    // 為了避免程式一直while迴圈,讓它睡個100毫秒檢測……
                    Thread.sleep(100);

                } catch (InterruptedException ie) {
                    Log.e("wifidemo", ie.toString());
                }
            }

            tempConfig = mWifiAutoConnectManager.isExsits(ssid);
            //禁掉所有wifi
            for (WifiConfiguration c : mWifiAutoConnectManager.wifiManager.getConfiguredNetworks()) {
                mWifiAutoConnectManager.wifiManager.disableNetwork(c.networkId);
            }
            if (tempConfig != null) {
                Log.d("wifidemo", ssid + "配置過!");
                boolean result = mWifiAutoConnectManager.wifiManager.enableNetwork(tempConfig.networkId, true);
                if (!isLinked && type != WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS) {
                    try {
                        Thread.sleep(5000);//超過5s提示失敗
                        if (!isLinked) {
                            Log.d("wifidemo", ssid + "連線失敗!");
                            mWifiAutoConnectManager.wifiManager.disableNetwork(tempConfig.networkId);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progressbar.setVisibility(View.GONE);
                                    Toast.makeText(getApplicationContext(), "連線失敗!請在系統裡刪除wifi連線,重新連線。", Toast.LENGTH_SHORT).show();
                                    new AlertDialog.Builder(MainActivity.this)
                                            .setTitle("連線失敗!")
                                            .setMessage("請在系統裡刪除wifi連線,重新連線。")
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            })
                                            .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    Intent intent = new Intent();
                                                    intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
                                                    startActivity(intent);
                                                }
                                            }).show();
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Log.d("wifidemo", "result=" + result);
                return result;
            } else {
                Log.d("wifidemo", ssid + "沒有配置過!");
                if (type != WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            final EditText inputServer = new EditText(MainActivity.this);
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("請輸入密碼")
                                    .setView(inputServer)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("連線", new DialogInterface.OnClickListener() {

                                        public void onClick(DialogInterface dialog, int which) {
                                            password = inputServer.getText().toString();
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    WifiConfiguration wifiConfig = mWifiAutoConnectManager.createWifiInfo(ssid, password,
                                                            type);
                                                    if (wifiConfig == null) {
                                                        Log.d("wifidemo", "wifiConfig is null!");
                                                        return;
                                                    }
                                                    Log.d("wifidemo", wifiConfig.SSID);

                                                    int netID = mWifiAutoConnectManager.wifiManager.addNetwork(wifiConfig);
                                                    boolean enabled = mWifiAutoConnectManager.wifiManager.enableNetwork(netID, true);
                                                    Log.d("wifidemo", "enableNetwork status enable=" + enabled);
//                                                    Log.d("wifidemo", "enableNetwork connected=" + mWifiAutoConnectManager.wifiManager.reconnect());
//                                                    mWifiAutoConnectManager.wifiManager.reconnect();
                                                }
                                            }).start();
                                        }
                                    }).show();
                        }
                    });
                } else {
                    WifiConfiguration wifiConfig = mWifiAutoConnectManager.createWifiInfo(ssid, password, type);
                    if (wifiConfig == null) {
                        Log.d("wifidemo", "wifiConfig is null!");
                        return false;
                    }
                    Log.d("wifidemo", wifiConfig.SSID);
                    int netID = mWifiAutoConnectManager.wifiManager.addNetwork(wifiConfig);
                    boolean enabled = mWifiAutoConnectManager.wifiManager.enableNetwork(netID, true);
                    Log.d("wifidemo", "enableNetwork status enable=" + enabled);
//                    Log.d("wifidemo", "enableNetwork connected=" + mWifiAutoConnectManager.wifiManager.reconnect());
//                    return mWifiAutoConnectManager.wifiManager.reconnect();
                    return enabled;
                }
                return false;


            }
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            mConnectAsyncTask = null;
        }
    }
}

佈局程式碼沒什麼好說的。這裡就不貼出來了。這裡為了實現連線指定的wifi,做了一個特殊處理,就是西先禁用掉所有的wifi,然後只連線所選擇的wifi網路,這樣系統就不會自己切換wifi了。6.0以後,app內無法修改系統或者其他app建立的WifiConfiguration物件的。