Android Wifi广播接收器无法按预期工作

时间:2015-07-08 05:35:40

标签: android broadcastreceiver wifi

每当手机连接到新的WiFi网络时,我都必须获得WiFi ssid。我注册了以下

receiver `registerReceiver(this.mybroadcast, new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION));`

这部分代码完美无缺。但是在onReceive方法中,

NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO));

始终返回null。我也尝试了EXTRA_NETWORK_INFO,但它也返回了Null。

我无法使用

this.registerReceiver(this.mybroadcast, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));,

因为服务将在n分钟后停止/启动,并且使用此服务将在每次重新启动服务时生成事件。

有关如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以在活动中创建广播

  

第1步:

 @Override
    public void onResume() {
        registerReceiver();
        super.onResume();
    }

 private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(mReceiver, filter);
    }
  

第2步

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (info != null) {
                if (info.isConnected()) {
                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    String ssid = wifiInfo.getSSID();
                    if (ssid != null) {
                        if (isConnectClicked) {
                          //YOUR CONNECTED WITH WIFI

                                               } 
                                      }
                                         }

                               }
            } else {
                if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                    if (intent.hasExtra(WifiManager.EXTRA_SUPPLICANT_ERROR)) {

                  //Connection failed    


                    }
                }
             }
          }

    };
  

第3步

 @Override
    public void onPause() {
        unregisterReceiver(mReceiver);
        super.onPause();
    }