Wifi Connect-Disconnect Listener

时间:2011-06-15 18:12:51

标签: android wifi android-wifi

如果wifi连接/断开连接,我的类必须实现哪个监听器以自动检查代码?

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

我目前的代码非常简单:

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

6 个答案:

答案 0 :(得分:75)

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

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

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添加以下用户权限:

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

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

<!-- 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网络。这是一个有用的&#34; IsOnline()&#34;检查:https://stackoverflow.com/a/27312494/1140744

答案 1 :(得分:18)

创建自己的类,扩展BroadcastReceiver ...

public class MyNetworkMonitor extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Process the Intent here

    }
}

在AndroidManifest.xml中

<receiver
    android:name=".MyNetworkMonitor" >
        <intent-filter>
            <action android:name="android.net.wifi.STATE_CHANGE" />
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
</receiver>

有关使用意图的说明,请参阅WIFI_STATE_CHANGED_ACTIONCONNECTIVITY_ACTION

答案 2 :(得分:14)

查看这两页javadoc: ConnectivityManager WiFiManager

请注意,每个人都定义了广播操作。如果您需要了解有关注册广播接收器的更多信息,请查看以下内容: Programmatically register a broadcast receiver

BroadcastReceiver receiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (wifi.isWifiEnabled()) {
      tv.setText("You are connected");
    } else {
      tv.setText("You are NOT connected");
    }
  }
};

在你的清单中你可以做这样的事情(如果你不想在代码中注册接收者):

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <receiver android:name=".WiFiReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
        </intent-filter>
    </receiver>
</application>

修改

我应该补充一点,如果您只需要在应用程序运行时接收广播,最好在代码中注册此广播接收器而不是在清单中。通过在清单中指定它,即使以前没有运行连接,也会通知您的进程。

答案 3 :(得分:3)

AndroidManifest.xml 中添加以下权限。

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

创建新的Receiver类。

public class ConnectionChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null
            && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            Toast.makeText(context, "Wifi Connected!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "Wifi Not Connected!", Toast.LENGTH_SHORT).show();
        }
    }

将接收器类添加到 AndroidManifest.xml 文件。

<receiver android:name="ConnectionChangeReceiver"
          android:label="NetworkConnection">
  <intent-filter>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
  </intent-filter>
</receiver>

答案 4 :(得分:1)

回应sabsab。为了连接到Connectivity Change广播接收器,我使用了warbi的答案并添加了一个静态方法的类。

public class WifiHelper
{
    private static boolean isConnectedToWifi;
    private static WifiConnectionChange sListener;

    public interface WifiConnectionChange {
        void wifiConnected(boolean connected);
    }

    /**
     * Only used by Connectivity_Change broadcast receiver
     * @param connected
     */
    public static void setWifiConnected(boolean connected) {
        isConnectedToWifi = connected;
        if (sListener!=null)
        {
            sListener.wifiConnected(connected);
            sListener = null;
        }
    }

    public static void setWifiListener(WifiConnectionChange listener) {
        sListener = listener;
    }
}

然后我在上面显示的第一个答案上对接收器类进行了更改。

public class ConnectivityReceiver 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");
        WifiHelper.setWifiConnected(true);
    } else
    {
        Log.d("WifiReceiver", "Don't have Wifi Connection");
        WifiHelper.setWifiConnected(false);
    }

}
}

最后,在您的活动中,您可以添加一个监听器来利用此回调。

wifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
wasWifiEnabled = (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED || wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING);
WifiHelper.setWifiListener(new WifiHelper.WifiConnectionChange()
    {
        @Override
        public void wifiConnected(boolean connected)
        {
            //Do logic here
        }
    });

请注意,在回调触发后会删除侦听器,这是因为它是一个静态侦听器。无论如何,这个实现对我有用,并且是一种挂钩你​​的活动的方式,或者任何地方让它静止。

答案 5 :(得分:1)

我同意@ tanner-perrien的回答,在2020年,科特林代表:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerReceiver(wifiBroadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
    }

    private val wifiBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager
            Log.d("TUT", "Wifi is ${wifiManager.isWifiEnabled}")
        }
    }

    override fun onDestroy() {
        unregisterReceiver(wifiBroadcastReceiver)
        super.onDestroy()
    }
}

但可能希望与时俱进:https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback

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

活动:

lateinit var connec: ConnectivityManager

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    connec = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    val networkRequestWiFi = NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .build()

    connec.registerNetworkCallback(networkRequestWiFi, networkCallbackWiFi)
 }

private var networkCallbackWiFi = object : ConnectivityManager.NetworkCallback() {
    override fun onLost(network: Network?) {
        Log.d("TUT", "WiFi disconnected")
    }

    override fun onAvailable(network: Network?) {
        Log.d("TUT", "WiFi connected")
    }
}

override fun onDestroy() {
    connec.unregisterNetworkCallback(networkCallbackWiFi)
    super.onDestroy()
}