91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

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

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

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

青海省| 云梦县| 汉寿县| 临夏县| 泊头市| 岫岩| 平昌县| 株洲市| 厦门市| 刚察县| 盐边县| 任丘市| 茶陵县| 廉江市| 工布江达县| 延安市| 海晏县| 阜康市| 科技| 香河县| 南溪县| 蓝山县| 边坝县| 车致| 鲜城| 互助| 乌拉特前旗| 池州市| 嘉鱼县| 双桥区| 葵青区| 白玉县| 利川市| 长宁区| 安达市| 余干县| 竹山县| 泽州县| 福安市| 兰西县| 平塘县|