温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android开发实践:WIFI扫描功能的封装

发布时间:2020-07-29 03:37:43 来源:网络 阅读:8355 作者:Jhuster 栏目:移动开发

   网上关于Android WIFI模块开发的博文已经很多,这里我也想给出我对WIFI模块编程的一些消化结果,将Android的一些API封装类,方便在各个Android APP中复用,简化程序的开发。


   本文先给出一个扫描WIFI功能的封装成类,创建该类对象后,当你简单地调用search()函数后,后台会自动扫描当前的WIFI SSID,并以回调的形式通知你扫描结果,代码如下,需要注意的地方都用注释标注出来了。


package com.example.testwifi;
import java.util.ArrayList;
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.ScanResult;
import android.net.wifi.WifiManager;
                                  
public class WifiSearcher {
                                                                                                                                                                                             
    private static final int WIFI_SEARCH_TIMEOUT = 20; //扫描WIFI的超时时间
                                                                                                                                                                                             
    private Context mContext;
    private WifiManager mWifiManager;   
    private WiFiScanReceiver mWifiReceiver;      
    private Lock mLock;
    private Condition mCondition;
    private SearchWifiListener mSearchWifiListener;
    private boolean mIsWifiScanCompleted = false;
                                                                                                                                                                                             
    public static enum ErrorType {
        SEARCH_WIFI_TIMEOUT, //扫描WIFI超时(一直搜不到结果)
        NO_WIFI_FOUND,       //扫描WIFI结束,没有找到任何WIFI信号
    }
                                                                                                                                                                                             
    //扫描结果通过该接口返回给Caller
    public interface SearchWifiListener {
        public void onSearchWifiFailed(ErrorType errorType);
        public void onSearchWifiSuccess(List<String> results);
    }
                                                                                                                                                                                             
    public WifiSearcher( Context context, SearchWifiListener listener ) {
                                                                                                                                                                                                 
        mContext = context;
        mSearchWifiListener = listener;
                                                                                                                                                                                                 
        mLock = new ReentrantLock();
        mCondition = mLock.newCondition();
        mWifiManager=(WifiManager)mContext.getSystemService(Context.WIFI_SERVICE);     
                                                                                                                                                                                                 
        mWifiReceiver = new WiFiScanReceiver();     
    }
                                                                                                                                                                                   
    public void search() {
                                                                                                                                                                                                 
        new Thread(new Runnable() {
                                                                                                                                                                                                     
            @Override
            public void run() {
                //如果WIFI没有打开,则打开WIFI
                if( !mWifiManager.isWifiEnabled() ) {
                    mWifiManager.setWifiEnabled(true);
                }
                                                                                                                                                                                                                 
                //注册接收WIFI扫描结果的监听类对象
                mContext.registerReceiver(mWifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
                                                                                                                                                                                                         
                //开始扫描
                mWifiManager.startScan();
                                                                                                                                                                                                                        
                mLock.lock();
                                                                                                                                                                                                         
                //阻塞等待扫描结果
                try {                
                    mIsWifiScanCompleted = false;                
                    mCondition.await(WIFI_SEARCH_TIMEOUT, TimeUnit.SECONDS);
                    if( !mIsWifiScanCompleted ) {
                        mSearchWifiListener.onSearchWifiFailed(ErrorType.SEARCH_WIFI_TIMEOUT);
                    }
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                                                                                                                                                                                                         
                mLock.unlock();
                                                                                                                                                                                                         
                //删除注册的监听类对象
                mContext.unregisterReceiver(mWifiReceiver);                          
            }
        }).start();  
    }
                                                                                                                                                                                     
    //系统WIFI扫描结果消息的接收者      
    protected class WiFiScanReceiver extends BroadcastReceiver {
                                                                                                                                                                                                 
        public void onReceive(Context c, Intent intent) {
                                                                                                                                                                                             
            //提取扫描结果
            List<String> ssidResults = new ArrayList<String>();
            List<ScanResult> scanResults = mWifiManager.getScanResults();              
            for(ScanResult result : scanResults ) {
                ssidResults.add(result.SSID);    
            }
                                                                                                                                                                                                     
            //检测扫描结果
            if( ssidResults.isEmpty() ) {
                mSearchWifiListener.onSearchWifiFailed(ErrorType.NO_WIFI_FOUND);
            }
            else {
                mSearchWifiListener.onSearchWifiSuccess(ssidResults);
            }
                                                                                                                                                                                                     
            mLock.lock();
            mIsWifiScanCompleted = true;
            mCondition.signalAll();  
            mLock.unlock();
        }
    }
}

   代码中用到了Lock和Condition,就是为了阻塞地等待WIFI扫描的结果,以来可以在search函数内部直接完成监听对象的registerReceiver和unregisterReceiver,防止由于某些原因忘记unregisterReceiver导致程序crash,另一方面,针对某些Android系统可能不一定能够及时收到WIFI扫描结果而设置一个超时时间,这样,不至于UI一直长时间地等待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/2364295
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI