有没有办法检查我当前连接的wifi与以前连接的wifi是否不同?

时间:2018-09-26 14:56:47

标签: android android-intent android-wifi android-broadcastreceiver android-networking

从后台返回应用后,我想检测我的wifi连接是否已更改(如果已更改为蜂窝或其他wifi,但不相同)。有什么办法吗? 我尝试了下面的代码,但是它不起作用,即使我保持连接状态,每次返回应用程序时,它都会不断启动。

 IntentFilter networkIntent = new IntentFilter();
        networkIntent.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkIntent.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        registerReceiver(wifichangereceiver, networkIntent);

下面是我的接收者:

public final BroadcastReceiver wifichangereceiver = new BroadcastReceiver() {


        @Override
        public void onReceive(final Context context, final Intent intent) {
            final ConnectivityManager connMgr = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            final android.net.NetworkInfo wifi = connMgr
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (wifi.isConnected()) {
                hasWifiChanged = true;
              } else {
                hasWifiChanged = false;
              }
}

1 个答案:

答案 0 :(得分:1)

为什么不在变量中注册wifi ID,然后在连接WiFi时,可以将新的wifi ID与旧的wifi ID进行比较?

 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
 WifiInfo wifiInfo = wifiManager.getConnectionInfo();
 String ssid = wifiInfo.getSSID();
 int networkid = wifiInfo.getNetworkId();

如果networkid在您的设备上返回O,请改用SSID。