中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android開發實踐:WIFI連接功能的封裝

發布時間:2020-06-05 11:03:55 來源:網絡 閱讀:11137 作者:Jhuster 欄目:移動開發

   在上一篇文章《Android開發實踐:WIFI掃描功能的封裝》介紹了如何利用Andriod的API實現WIFI的掃描,本文則重點講述一下如何連接WIFI吧,在此,也給出一個封裝WIFI連接過程的類,提供簡單的接口以供在各個代碼工程中復用。


   與WIFI掃描類似,WIFI的連接同樣是一個耗時的過程,所以需要放到線程中執行,通過回調來通知調用者連接結果。該回調接口的定義如下:

public interface WifiConnectListener {
    public void OnWifiConnectCompleted( boolean isConnected );
}


   從Android的WIFI Setting可以看出,一般添加一個新的WIFI連接,需要給出三個信息,一個是WIFI的SSID,一個是WIFI的密碼,另一個是WIFI的加密類型,不同的加密方式,連接時程序中的配置是不同的,這里定義一個枚舉,給出四種常見的加密類型:


public enum SecurityMode {
    OPEN, WEP, WPA, WPA2
}


   Android的WIFI連接過程,總體上分為三步,第一步,添加網絡配置,第二步,根據網絡配置連接WIFI,第三步,監聽系統的WIFI連接狀態消息。下面就直接給出示例代碼,關鍵的地方都在代碼中注釋了。


package com.example.testwifi;
                     
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
                                                                                                                  
public class WifiConnector {
                                                                                                        
    private static final int WIFI_CONNECT_TIMEOUT = 20; //連接WIFI的超時時間
                                                                                                        
    private Context mContext;
    private WifiManager mWifiManager;           
    private Lock mLock;
    private Condition mCondition;
    private WiFiConncetReceiver mWifiConnectReceiver;
    private WifiConnectListener mWifiConnectListener;
    private boolean mIsConnnected = false;
    private int mNetworkID = -1;
              
    //網絡加密模式
    public enum SecurityMode {
        OPEN, WEP, WPA, WPA2
    }
                      
   //通知連接結果的監聽接口
    public interface WifiConnectListener {
        public void OnWifiConnectCompleted( boolean isConnected );
    }
                        
    public WifiConnector( Context context , WifiConnectListener listener ) {
                                                                                                            
        mContext = context;   
                                                                                                            
        mLock = new ReentrantLock();
        mCondition = mLock.newCondition();
        mWifiManager=(WifiManager)mContext.getSystemService(Context.WIFI_SERVICE);   
                                                                                                            
        mWifiConnectReceiver = new WiFiConncetReceiver();  
                                                                                                            
        mWifiConnectListener = listener;
    }
                                                                                                                
    public void connect( final String ssid, final String password, final SecurityMode mode ) {
                                                                                                            
        new Thread(new Runnable() {
                                                                                                                
            @Override
            public void run() {
                                                                                                                    
                //如果WIFI沒有打開,則打開WIFI
                if( !mWifiManager.isWifiEnabled() ) {
                    mWifiManager.setWifiEnabled(true);
                }
                                                                                                                            
                //注冊連接結果監聽對象
                mContext.registerReceiver(mWifiConnectReceiver, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
                                                                                                                    
                //連接指定SSID
                if( !onConnect(ssid,password,mode) ) {
                    mWifiConnectListener.OnWifiConnectCompleted(false);
                }
                else {
                    mWifiConnectListener.OnWifiConnectCompleted(true);
                }
                                                                                                                    
                //刪除注冊的監聽類對象
                mContext.unregisterReceiver(mWifiConnectReceiver);         
            }
        }).start();            
    }
                                                                                                        
    protected boolean onConnect( String ssid, String password, SecurityMode mode ) {
                                                                                                            
        //添加新的網絡配置
        WifiConfiguration cfg = new WifiConfiguration();
        cfg.SSID = "\"" + ssid + "\"";
        if( password !=null && !"".equals(password) ) {
            //這里比較關鍵,如果是WEP加密方式的網絡,密碼需要放到cfg.wepKeys[0]里面
            if( mode == SecurityMode.WEP ) {
                cfg.wepKeys[0]   = "\"" + password + "\"";
                cfg.wepTxKeyIndex = 0;
            }
            else {
                cfg.preSharedKey = "\"" + password + "\"";
            }                  
        }
        cfg.status = WifiConfiguration.Status.ENABLED;
         
        //添加網絡配置
        mNetworkID = mWifiManager.addNetwork(cfg);
                                                                                                            
        mLock.lock();
                                                                                 
        mIsConnnected = false;
            
        //連接該網絡
        if( !mWifiManager.enableNetwork(mNetworkID , true) ) {
            mLock.unlock();
            return false;
        }
                                                                                                            
        try {
            //等待連接結果
            mCondition.await(WIFI_CONNECT_TIMEOUT, TimeUnit.SECONDS);
        }
        catch (InterruptedException e) {
            e.printStackTrace();       
        }
                                                                                                            
        mLock.unlock();
                                                                                                            
        return mIsConnnected;
    }  
                                                                                                        
    //監聽系統的WIFI連接消息
    protected class WiFiConncetReceiver extends BroadcastReceiver {
                                                                                                                    
        @Override
        public void onReceive(Context context, Intent intent) {
                                                                                                                
            if (!WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                return;
            }          
                                                                                                                
            mLock.lock();
                                                                                                                
            WifiInfo info = mWifiManager.getConnectionInfo();
            if ( info.getNetworkId()==mNetworkID && info.getSupplicantState() == SupplicantState.COMPLETED ) {
                mIsConnnected = true;
                mCondition.signalAll();    
            }
                                                                                                                
            mLock.unlock();
        }
    }
}

   與WIFI掃描的封裝代碼類似,這里也用到了Lock和Condition,就是為了阻塞地等待WIFI連接的結果,保證正確的registerReceiver和unregisterReceiver網絡連接狀態監聽對象,同時,設置了WIFI連接超時,防止由于WIFI模塊的問題導致界面收不到回調而長時間“卡死”。


   另外,AndroidManifest.xml文件中記得添加權限支持哦:


<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>


   這個WIFI連接類的封裝就分享到這里啦,希望對初學者有幫助,java文件見博文后面的附件,有任何疑問歡迎留言或者來信lujun.hust@gmail.com交流,或者關注我的新浪微博 @盧_俊 獲取最新的文章和資訊。


附件:http://down.51cto.com/data/2364418
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

封开县| 湟中县| 襄樊市| 昌黎县| 固始县| 漳平市| 吴江市| 苏尼特左旗| 于田县| 纳雍县| 巴林右旗| 叶城县| 全州县| 长乐市| 巍山| 长泰县| 宁晋县| 明水县| 新田县| 桃园市| 双峰县| 都匀市| 循化| 淳安县| 广水市| 平舆县| 拉萨市| 芒康县| 陇南市| 赫章县| 绥宁县| 监利县| 凤台县| 南和县| 丹寨县| 岱山县| 晋州市| 毕节市| 曲阜市| 浦东新区| 天长市|