开发者

How to check whether the wifi is connected to specific SSID

I read this solution : How to check netwo开发者_运维百科rk connection enable or disable in WIFI and 3G(data plan) in mobile? .BUT, it just check whether wifi network is connected or not. How to check whether the wifi is connected to the specific SSID or not?


The code is similar, again use a system service, make sure you are connected to something and get the SSID:

WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED) {
    String ssid = wifiInfo.getSSID();
}


public static boolean IsWiFiConnected(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
        .getApplicationContext().getSystemService(
            Context.CONNECTIVITY_SERVICE);

    if (connectivity != null) {
      NetworkInfo[] info = connectivity.getAllNetworkInfo();
      if (info != null) {
        for (int i = 0; i < info.length; i++) {
          if (info[i].getTypeName().equals("WIFI")
              && info[i].isConnected())
            return true;
        }
      }
    }

    return false;
  }


The best that worked for me:

Menifest:

<receiver android:name="com.AEDesign.communication.WifiReceiver" >
        <intent-filter android:priority="100">
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    </receiver>

Class:

 public class WifiReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {

            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if(info!=null){

                if(info.isConnected()){
                                    //Do your work. 

                                    //To check the Network Name or other info:
                        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                        String ssid = wifiInfo.getSSID();

                }
            }

Permissions:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜