how to check if wifi is really connected in Android

前端 未结 4 943
一生所求
一生所求 2021-01-15 12:04

I\'d like my android device to connect to a wifi hotspot. I created a new wificonfiguration and add it into the wifimanager, this wificonfigu

4条回答
  •  野的像风
    2021-01-15 12:11

    You can try this:

    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
    if (wifi.isConnected()) {
        // Your code here
    }
    

    Edit: More details:

    Register a BroadcastReceiver in your manifest like so:

    
        
            
            
        
    
    

    Then put the code above on the onReceive() method of your receiver like so:

    @Override
    public void onReceive(Context context, final Intent intent) {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
        if (wifi.isConnected()) {
            // Your code here
        }
    }
    

提交回复
热议问题