Android 通过WIFI状态监听广播,判断进入指定wifi范围

原文地址:http://blog.csdn.net/kongxiuqi/article/details/52524500

---------------------------------------------

WIFI状态变化会发送广播,一些可用的广播在WifiManger.java中可以看到。
广播一:WIFI 状态开关变化的监听,enabled,disabled等
/**
 * Broadcast intent action indicating that Wi-Fi has been enabled, disabled,
 * enabling, disabling, or unknown. One extra provides this state as an int.
 * Another extra provides the previous state, if available.
 *
 * @see #EXTRA_WIFI_STATE
 * @see #EXTRA_PREVIOUS_WIFI_STATE
 */
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String WIFI_STATE_CHANGED_ACTION ="android.net.wifi.WIFI_STATE_CHANGED";
// 自定义个broadcast 在广播接收器Broadcast中判断,
 if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {//这个监听wifi的打开与关闭,与wifi的连接无关  
            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);   
            LogTag.showTAG_e("WIFI状态", "wifiState"+wifiState);  
            switch (wifiState) {   
            case WifiManager.WIFI_STATE_DISABLED:   
                break;   
            case WifiManager.WIFI_STATE_DISABLING:   
                break;   
           //  
            }   
        }
各个状态的值如下:
/**
 * Wi-Fi is currently being disabled. The state will change to {@link #WIFI_STATE_DISABLED} if
 * it finishes successfully.
 *
 * @see #WIFI_STATE_CHANGED_ACTION
 * @see #getWifiState()
 */
public static final int WIFI_STATE_DISABLING = 0;
/**
 * Wi-Fi is disabled.
 *
 * @see #WIFI_STATE_CHANGED_ACTION
 * @see #getWifiState()
 */
public static final int WIFI_STATE_DISABLED = 1;
/**
 * Wi-Fi is currently being enabled. The state will change to {@link #WIFI_STATE_ENABLED} if
 * it finishes successfully.
 *
 * @see #WIFI_STATE_CHANGED_ACTION
 * @see #getWifiState()
 */
public static final int WIFI_STATE_ENABLING = 2;
/**
 * Wi-Fi is enabled.
 *
 * @see #WIFI_STATE_CHANGED_ACTION
 * @see #getWifiState()
 */
public static final int WIFI_STATE_ENABLED = 3;
/**
 * Wi-Fi is in an unknown state. This state will occur when an error happens while enabling
 * or disabling.
 *
 * @see #WIFI_STATE_CHANGED_ACTION
 * @see #getWifiState()
 */
public static final int WIFI_STATE_UNKNOWN = 4;
广播二 wifi连接状态变化的监听
/**
 * Broadcast intent action indicating that the state of Wi-Fi connectivity
 * has changed. One extra provides the new state
 * in the form of a {@link android.net.NetworkInfo} object. If the new
 * state is CONNECTED, additional extras may provide the BSSID and WifiInfo of
 * the access point.
 * as a {@code String}.
 * @see #EXTRA_NETWORK_INFO
 * @see #EXTRA_BSSID
 * @see #EXTRA_WIFI_INFO
 */
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE";

 // 这个监听wifi的连接状态即是否连上了一个有效无线路由,当上边广播的状态是WifiManager.WIFI_STATE_DISABLING,和WIFI_STATE_DISABLED的时候,根本不会接到这个广播。  
    // 在上边广播接到广播是WifiManager.WIFI_STATE_ENABLED状态的同时也会接到这个广播,当然刚打开wifi肯定还没有连接到有效的无线  
    if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {  
            Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);    
            if (null != parcelableExtra) {    
                NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;    
                State state = networkInfo.getState();  
                boolean isConnected = state==State.CONNECTED;//当然,这边可以更精确的确定状态  
                LogTag.showTAG_e(this.getClass().getSimpleName(), "isConnected"+isConnected);  
                if(isConnected){  
                }else{  
                      
                }  
            }    
        }  

广播三 wifi扫描列表完成
/**
 * An access point scan has completed, and results are available from the supplicant.
 * Call {@link #getScanResults()} to obtain the results. {@link #EXTRA_RESULTS_UPDATED}
 * indicates if the scan was completed successfully.
 */
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String SCAN_RESULTS_AVAILABLE_ACTION = "android.net.wifi.SCAN_RESULTS";
wifi扫描完成,获取wili列表 可以通过wifimanager的startScan主动发起扫描,扫描完成后会发送这个广播
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {Log.e(TAG, "WifiManager.SCAN_RESULTS_AVAILABLE_ACTION");WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);List<ScanResult> list = wifiManager.getScanResults();for (int i = 0; i < list.size(); i++) {Log.e(TAG, list.get(i).toString());Log.e(TAG, "ScanResult SSID = " + list.get(i).SSID);}
}
getScanResults 只能得到可用的列表,获取所有wifi列表需用如下方法,该方法可以获取已连接过的但是
不在范围内的wifi信息
/**
 * Return a list of all the networks configured in the supplicant.
 * Not all fields of WifiConfiguration are returned. Only the following
 * fields are filled in:
 * <ul>
 * <li>networkId</li>
 * <li>SSID</li>
 * <li>BSSID</li>
 * <li>priority</li>
 * <li>allowedProtocols</li>
 * <li>allowedKeyManagement</li>
 * <li>allowedAuthAlgorithms</li>
 * <li>allowedPairwiseCiphers</li>
 * <li>allowedGroupCiphers</li>
 * </ul>
 * @return a list of network configurations in the form of a list
 * of {@link WifiConfiguration} objects. Upon failure to fetch or
 * when when Wi-Fi is turned off, it can be null.
 */
public List<WifiConfiguration> getConfiguredNetworks() {try {return mService.getConfiguredNetworks();} catch (RemoteException e) {Log.w(TAG, "Caught RemoteException trying to get configured networks: " + e);return null;}
}
广播四
/**
 * Broadcast intent action indicating that a connection to the supplicant has
 * been established (and it is now possible
 * to perform Wi-Fi operations) or the connection to the supplicant has been
 * lost. One extra provides the connection state as a boolean, where {@code true}
 * means CONNECTED.
 * @see #EXTRA_SUPPLICANT_CONNECTED
 */
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String SUPPLICANT_CONNECTION_CHANGE_ACTION ="android.net.wifi.supplicant.CONNECTION_CHANGE";
另外还有一个监听网络状态变化的广播
ConnectivityManager.CONNECTIVITY_ACTION
/**
 * A change in network connectivity has occurred. A default connection has either
 * been established or lost. The NetworkInfo for the affected network is
 * sent as an extra; it should be consulted to see what kind of
 * connectivity event occurred.
 * <p/>
 * If this is a connection that was the result of failing over from a
 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
 * set to true.
 * <p/>
 * For a loss of connectivity, if the connectivity manager is attempting
 * to connect (or has already connected) to another network, the
 * NetworkInfo for the new network is also passed as an extra. This lets
 * any receivers of the broadcast know that they should not necessarily
 * tell the user that no data traffic will be possible. Instead, the
 * receiver should expect another broadcast soon, indicating either that
 * the failover attempt succeeded (and so there is still overall data
 * connectivity), or that the failover attempt failed, meaning that all
 * connectivity has been lost.
 * <p/>
 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
 * is set to {@code true} if there are no connected networks at all.
 */
@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

如果我们需要判断手机进入到某个wifi地区就可以通过该广播,以及扫描wifi列表进行实现
代码如下

public class NetworkConnectChangedReceiver extends BroadcastReceiver {private static final String TAG = NetworkConnectChangedReceiver.class.getSimpleName();@Override
    public void onReceive(Context context, Intent intent) {// 处理扫描完成广播,根据扫描结果比对是否进入了某个特定wifi范围if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {Log.e(TAG, "WifiManager.SCAN_RESULTS_AVAILABLE_ACTION");WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);List<ScanResult> list = wifiManager.getScanResults();
            // 此处循环遍历,可以根据SSID 或者MAC,与某个指定wifi进行对比,如果相等可以认为进入了该wifi的范围。
            for (int i = 0; i < list.size(); i++) {Log.e(TAG, list.get(i).toString());Log.e(TAG, "ScanResult SSID = " + list.get(i).SSID);}}// 这个监听网络连接的设置,包括wifi和移动数据的打开和关闭。.
        // 最好用的还是这个监听。wifi如果打开,关闭,以及连接上可用的连接都会接到监听。见log
        // 这个广播的最大弊端是比上边两个广播的反应要慢,如果只是要监听wifi,我觉得还是用上边两个配合比较合适
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);Log.i(TAG, "网络状态改变:" + wifi.isConnected() + " 3g:" + gprs.isConnected());Log.e(TAG, "ConnectivityManager.CONNECTIVITY_ACTION");NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);if (info != null) {Log.e(TAG, "info.getTypeName()" + info.getTypeName());Log.e(TAG, "getSubtypeName()" + info.getSubtypeName());Log.e(TAG, "getState()" + info.getState());Log.e(TAG, "getDetailedState()"
                        + info.getDetailedState().name());Log.e(TAG, "getDetailedState()" + info.getExtraInfo());Log.e(TAG, "getType()" + info.getType());if (NetworkInfo.State.CONNECTED == info.getState()) {} else if (info.getType() == 1) {if (NetworkInfo.State.DISCONNECTING == info.getState()) {Log.e(TAG, "disconnect");}}}
            // 开启wifi扫描,扫描完成后发送广播
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);wifiManager.startScan();
        }}
}
需要注册
    mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
    mIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  registerReceiver(mReceiver, mIntentFilter);
或者在AndroidManifest中添加
    
<receiver android:name=".receiver.NetworkConnectChangedReceiver"><intent-filter><action android:name="android.net.conn.CONNECTIVITY_CHANGE" /><action android:name="android.net.wifi.WIFI_STATE_CHANGED" /><action android:name="android.net.wifi.STATE_CHANGE" /><action android:name="android.net.wifi.SCAN_RESULTS" /></intent-filter>
</receiver>
另外需要配置权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />


-------------

更多的Java,Angular,Android,大数据,J2EE,Python,数据库,Linux,Java架构师,:

http://www.cnblogs.com/zengmiaogen/p/7083694.html



本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/538921.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java 截取byte数组_2020年的秋招已经开始了!最新Java面试题大全(文末附参考答案)送给大家...

包含的模块本文分为十九个模块&#xff0c;分别是&#xff1a;Java 基础、容器、多线程、反射、对象拷贝、Java Web 、异常、网络、设计模式、Spring/Spring MVC、Spring Boot/Spring Cloud、Hibernate、MyBatis、RabbitMQ、Kafka、Zookeeper、MySQL、Redis、JVM共包含 208 道面…

MVP模式在Android项目中的使用

烦了在Activity中编写太多的代码&#xff0c;该app由我来主导。就选择用MVP模式。 概述 MVP是模型&#xff08;Model&#xff09;、视图&#xff08;View&#xff09;、主持人&#xff08;Presenter&#xff09;的缩写&#xff0c;分别代表项目中3个不同的模块。 模型&#…

运行时错误7内存溢出_C++程序运行时的内存模型

C程序在运行时会将内存划分为4个区域&#xff1a;1代码区&#xff1a;存放函数体的二进制代码&#xff0c;由操作系统进行管理2全局区&#xff1a;存放程序的全局变量、静态变量、常量3栈区&#xff1a;由编译器进行自动分配和释放&#xff0c;存放函数的参数值&#xff0c;局部…

玩转Android之MVVM开发模式实战,炫酷的DataBinding!

原文&#xff1a;http://blog.csdn.net/u012702547/article/details/52077515 --------------------------------------------------------- MVP可以结合android的DataBinding -------------------------以下转载--------------- C# 很早就有了MVVM的开发模式&#xff0c;An…

打造一款便携版的Sublime Text

https://segmentfault.com/a/1190000000707661 https://www.cnblogs.com/52cik/p/sublime-diy.html 直接安装Sublime Text&#xff0c;不要打开 大家可以参照上文提到的《Sublime Text 全程指引》中的步骤去进行安装。我这里使用的是Sublime Text 2&#xff0c;其实3也是一样的…

confluence创建页面加载缓慢_树莓派4B使用docker安装confluence

说明confluence是一个专业的企业知识管理与协同软件&#xff0c;可以用于构建企业wiki。通过它可以实现团队成员之间的协作和知识共享。现在大多数公司都会部署一套confluence&#xff0c;用作内部wiki。另外confluence也可以作为个人的知识管理工具来用&#xff0c;只需要花10…

matlab粒子加速器仿真,粒子群算法优化PID参数 仿真不出结果 程序如下

用的是《MATLAB智能算法30个案例分析》中的程序1.文件名为PSO_PID.mfunction z PSO_PID(x)assignin(base,Kp,x(1)); % 粒子群依次赋值给Kp 这部分运行结果> PSO_PIDassignin(base,Ki,x(2)); …

CentOS5、6的启动流程

CentOS5/6的启动流程启动流程画了张图,看着更清晰些: (centos7的启动流程变化挺大的,这部分待补充)补充(/etc/rc.d/rc.local 不属于任何服务,为特殊文件,可将不能定义为服务又想开机运行的命令定义在此文件中)添加自定义服务:[rootel5 init.d]# vi /etc/init.d/testsrv #!/bin…

Spark交互式分析平台Apache Zeppelin的安装

Zeppelin介绍 Apache Zeppelin提供了web版的类似ipython的notebook&#xff0c;用于做数据分析和可视化。背后可以接入不同的数据处理引擎&#xff0c;包括Spark, Hive, tajo等&#xff0c;原生支持Scala, Java, shell, markdown等。它的整体展现和使用形式和Databricks Cloud是…

win7 php zend,win7系统打开WZend Studio PHP出错的解决方法

很多朋友安装win7系统后&#xff0c;在使用的过程中会遇到win7系统打开WZend Studio PHP出错的情况&#xff0c;可能有很多用户还是不能自己处理win7系统打开WZend Studio PHP出错的问题&#xff0c;其实简单的来说处理win7系统打开WZend Studio PHP出错的问题只需要按照 1、在…

9个元素换6次达到排序序列_C语言必学的12个排序算法:希尔排序(第3篇)

基本思想希尔排序&#xff08;Shells Sort&#xff09;&#xff0c;以发明人命名&#xff0c;又称为缩小增量排序&#xff0c;也是一种插入排序算法。主要思想&#xff1a;直接插入排序算法时间和待排数据有关&#xff0c;其平均复杂度是O(n^2)&#xff0c;但是在待排数据已经有…

java快捷键禁用_pycharm 掌握这些快捷键,你就是大神!!

最重要的快捷键1. ctrlshiftA:万能命令行 2. shift两次:查看资源文件新建工程第一步操作1. module设置把空包分层去掉,compact empty middle package 2. 设置当前的工程是utf-8,设置的Editor-->File Encodings-->全部改成utf-8,注释1. ctrl/:单行注释光标操作1. ctrlalte…

如何在 5 分钟内读懂区块链的架构思维?

作为入门者&#xff0c;如何在最短的时间了解区块链技术&#xff0c;区块链思维&#xff0c;以及比特币的金融原理呢&#xff1f;本文尝试从比特币的架构设计思维出发&#xff0c;让人从宏观上搞清楚区块链的技术本质。 本文授权转载自阿里技术 作者 | 郑吉 区块链不是一种技术…

arduino 上传项目出错_Arduino多核编程:简单例子

不管你是Arduino领域的新手还是经验丰富的开发人员&#xff0c;很可能你还只使用过单核在进行编程。 这没有什么好笑的---- 事实上&#xff0c;直到几天前我才使用Arduino IDE进行了第一次多核编程。 我和所有其他Arduino粉丝都非常喜欢IDE的易用性以及MicroController 开发所需…

Hadoop-RPC应用demo

Hadoop里的rpc框架可以单独拿出来使用。jar包全在hadoop-common工程里。 导入hadoop-common工程里&#xff08;hadoop-2.7.3为例&#xff09;&#xff1a; hadoop-common-2.7.3.jar \hadoop-2.7.3\share\hadoop\common\lib下的全部jar包 实例 rpc.client 客户端 rpc.pr…

宝塔面板服务器ip地址修改_「网站」快速搭建服务器环境及网站

目录&#xff1a;「NAS」我的搭建NAS全过程在文章开头我想说明的是&#xff0c;此文章中所使用的工具为 BT 面板即宝塔面板&#xff0c;适合小白使用但是对于想要提升个人能力来说&#xff0c; BT 面板并不是一个好选择&#xff0c;而作为新手来说&#xff0c;可以使用该面板进…

杨辉三角python_Python面试150题汇总,都是常问的面试题!

周末&#xff0c;Python面试题每日一题暂停更新&#xff0c;下面把最近整理的1-50篇Python面试文整理一下&#xff0c;平时文章都放在比较末尾&#xff0c;阅读量都不高&#xff0c;相信很多人都没看过&#xff0c;如果对于Python感兴趣的&#xff0c;建议可以认真阅读一下&…

java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.wifi.SCAN_RESULTS flg

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.nokia.wlanapp, PID: 18526java.lang.RuntimeException: Error receiving broadcast Intent { actandroid.net.wifi.SCAN_RESULTS flg0x4000010 (has extras【外部】) } in com.nokia.wlanapp.Receive…

php处理上传文件的步骤,php文件上传步骤

我们在开发网站的时候&#xff0c;经常会遇到需要制作文件上传功能&#xff0c;下面我们就为大家介绍一下php制作文件上传功能的详细步骤。推荐教程&#xff1a;PHP视频教程第一步&#xff1a;创建一个文件上传表单允许用户从表单上传文件是非常有用的。请看下面这个供上传文件…

matlab求傅里叶级数展开式_傅里叶级数:从向量的角度看函数

帮助你理解线性代数与机器学习紧密结合的核心内容下文节选自北大出版社《机器学习线性代数基础》, [遇见]已获授权许可. 这本书不同于传统教材, 从新的角度来介绍线性代数的核心知识, 讲解也很棒, 又刚好参加参加了当当每满100-50的活动, 感兴趣的朋友可以关注下. 傅里叶级数&a…