本文介绍了Wifi 连接断开监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的班级必须实现哪个侦听器才能在 wifi 连接/断开连接时自动检查代码?

Which listener does my class have to implement inorder to automatically check code if the wifi connects/disconnects?

我可以手动检查 wifi 连接/断开连接,但每次我需要从 android 设置连接/断开 WIFI 时,然后运行我的程序以获得结果.

I'm able to manually check for wifi connection/disconnection but each time I need to connect/disconnect WIFI from android settings and then run my program for the result.

我目前的代码很简单:

WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()==true)
{
    tv.setText("You are connected");
}
else
{
    tv.setText("You are NOT connected");
}

推荐答案

实际上您正在检查 Wi-Fi 是否启用,这并不一定意味着它已连接.这只是意味着手机上的 Wi-Fi 模式已启用并且能够连接到 Wi-Fi 网络.

Actually you're checking for whether Wi-Fi is enabled, that doesn't necessarily mean that it's connected. It just means that Wi-Fi mode on the phone is enabled and able to connect to Wi-Fi networks.

这就是我在广播接收器中监听实际 Wi-Fi 连接的方式:

This is how I'm listening for actual Wi-Fi connections in my Broadcast Receiver:

public class WifiReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = conMan.getActiveNetworkInfo();
        if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI)
            Log.d("WifiReceiver", "Have Wifi Connection");
        else
            Log.d("WifiReceiver", "Don't have Wifi Connection");
    }
};

为了访问活动网络信息,您需要将以下使用权限添加到您的 AndroidManifest.xml 中:

In order to access the active network info you need to add the following uses-permission to your AndroidManifest.xml:

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

以及以下意图接收器(或者您可以以编程方式添加它...)

And the following intent receiver (or you could add this programmatically...)

<!-- Receive Wi-Fi connection state changes -->
<receiver android:name=".WifiReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

在 Lollipop 中,如果您希望在用户连接到未计量的网络连接时执行操作,则作业调度可能会有所帮助.看看:http://developer.android.com/about/versions/android-5.0.html#Power

编辑 2:另一个考虑因素是我的回答不会检查您是否连接到互联网.您可能已连接到需要您登录的 Wi-Fi 网络.这是一个有用的IsOnline()"检查:https:///stackoverflow.com/a/27312494/1140744

EDIT 2: Another consideration is that my answer doesn't check that you have a connection to the internet. You could be connected to a Wi-Fi network which requires you to sign in. Here's a useful "IsOnline()" check: https://stackoverflow.com/a/27312494/1140744

这篇关于Wifi 连接断开监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:04