Android WiFi 状态侦听器

Android WiFi State Listener

我是 Android 开发的新手。如何在 Activity 中设置 WiFi connections/disconnections 的侦听器?它必须在 Activity 内部,因为我在其中设置了 UART 连接并且需要将 WiFi 状态信息发送到 UART 设备。我用 BroadcastReceivers 尝试了一些东西但失败了。这是我最后一次尝试:

private BroadcastReceiver myWifiReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
            if(networkInfo.isConnected()){
                Log.d("WIFI", "CONNECTED");
            }else{
                Log.d("WIFI", "DISCONNECTED");
            }
        }
}};

我可能还需要一些有关如何注册 BroadcastReceiver 的帮助,目前我正在 Activity 的 onResume:

中进行此操作
this.registerReceiver(this.myWifiReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

onPause中:

this.unregisterReceiver(myWifiReceiver);

编辑:

感谢 Devunwired 的回答,我已经实现了我想要的,我发布代码以供将来参考。

private BroadcastReceiver myWifiReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        SupplicantState newState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);

        switch(newState){
            case ASSOCIATED:
                Log.d("WIFI", "CONNECTED");
                break;
            case DISCONNECTED:
                if(!disconnected){
                    Log.d("WIFI", "DISCONNECTED");
                    disconnected = true;
                }
        }
}};

我也将 BroadcastReceiver 注册移动到 onStart(并因此将注销移动到 onStop),因为 onResume 并不总是被调用:

this.registerReceiver(this.myWifiReceiver, new IntentFilter(
        WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));

根据您所说的 "connections/disconnections" 的含义,您可能没有观察到正确的广播操作。 ConnectivityManager.CONNECTIVITY_ACTION 当默认连接完全建立或丢失时触发。

您可能对 WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTIONWifiManager.SUPPLICANT_STATE_CHANGED_ACTION 更感兴趣,它们会随着 WiFi 无线电的关联状态发生变化而触发。

I have tried some things with BroadcastReceivers but failed

如果以上操作不能满足您的需求,我鼓励您详细说明您遇到的失败。