Android WiFi状态监听器

时间:2017-05-03 21:06:27

标签: android broadcastreceiver android-wifi android-things

我是Android开发的新手。如何在Activity中设置WiFi连接/断开连接的监听器?它必须在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));

1 个答案:

答案 0 :(得分:3)

取决于您的意思&#34;连接/断开连接&#34;你可能没有观察到正确的广播动作。 <{1}}在完全建立或丢失默认连接时触发。

您可能对ConnectivityManager.CONNECTIVITY_ACTIONWifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION更感兴趣,这会触发WiFi无线电的关联状态发生变化。

  

我尝试过使用BroadcastReceivers的一些东西但是失败了

如果上述行为不能满足您的需求,我建议您详细说明您遇到的失败。