Android Wifi broadcast receiver not working as expected

后端 未结 1 410
栀梦
栀梦 2021-01-28 03:24

I have to get the WiFi ssid whenever phone connects to new WiFi network. I registered the following

receiver `registerReceiver(this.mybroadcast, new IntentFilter         


        
相关标签:
1条回答
  • 2021-01-28 04:00

    You can create broadcast within the activity

    Step 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);
        }
    

    Step 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    
    
    
                        }
                    }
                 }
              }
    
        };
    

    Step 3

     @Override
        public void onPause() {
            unregisterReceiver(mReceiver);
            super.onPause();
        }
    
    0 讨论(0)
提交回复
热议问题