Android WIFI 如何检测特定 WIFI 连接何时可用

发布于 2025-01-07 11:03:39 字数 185 浏览 0 评论 0原文

我需要检测何时有到特定 WIFI 网络的网络连接。

例如:当您走进家中,并且您的手机接收到您的家庭 WiFi 网络时,我希望收到一条通知,内容为“您不在家庭网络中,您想连接到您的家庭网络吗?”但我希望只有当我在我的特定房子里时才会发生这种情况。

我应该监听什么以及应该做什么测试来确保它是我的特定家庭网络,而不是另一个网络?

I need to detect when I have network connectivity to a SPECIFIC WIFI network.

For example: As soon as you walk into your house, and your phone picks up your home WiFi network, I would like a notification that says "You are not at your home network, would you like to connect to you Home?" But I would like that to only happen when I am at my specific house.

What should I listen for and what tests should I do to make sure it is my specific home network, and not another network?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

终陌 2025-01-14 11:03:39

您可以使用 BroadcastReceiver 来发现 wifi 网络已更改:

BroadcastReceiver broadcastReceiver = new WifiBroadcastReceiver();

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
context.registerReceiver(broadcastReceiver, intentFilter);

BroadcastReceiver 可能如下所示。
要检查特定的 MAC 地址,请参阅下面的 checkConnectedToDesiredWifi() 方法。

public class WifiBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION .equals(action)) {
            SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            if (SupplicantState.isValidState(state) 
                    && state == SupplicantState.COMPLETED) {

                boolean connected = checkConnectedToDesiredWifi();
            }
        }
    }

    /** Detect you are connected to a specific network. */
    private boolean checkConnectedToDesiredWifi() {
        boolean connected = false;

        String desiredMacAddress = "router mac address";

        WifiManager wifiManager = 
            (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        WifiInfo wifi = wifiManager.getConnectionInfo();
        if (wifi != null) {
            // get current router Mac address
            String bssid = wifi.getBSSID();
            connected = desiredMacAddress.equals(bssid);
        }

        return connected;
    }
}

You can use BroadcastReceiver to find out that wifi network has changed:

BroadcastReceiver broadcastReceiver = new WifiBroadcastReceiver();

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
context.registerReceiver(broadcastReceiver, intentFilter);

The BroadcastReceiver may look like this.
And to check for specific MAC address see the checkConnectedToDesiredWifi() method bellow.

public class WifiBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION .equals(action)) {
            SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            if (SupplicantState.isValidState(state) 
                    && state == SupplicantState.COMPLETED) {

                boolean connected = checkConnectedToDesiredWifi();
            }
        }
    }

    /** Detect you are connected to a specific network. */
    private boolean checkConnectedToDesiredWifi() {
        boolean connected = false;

        String desiredMacAddress = "router mac address";

        WifiManager wifiManager = 
            (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        WifiInfo wifi = wifiManager.getConnectionInfo();
        if (wifi != null) {
            // get current router Mac address
            String bssid = wifi.getBSSID();
            connected = desiredMacAddress.equals(bssid);
        }

        return connected;
    }
}
云雾 2025-01-14 11:03:39

只要我们不提供免费服务所需的代码,我只能建议您在创建此类应用程序时阅读有关 Android 及其网络/Wifi 可能性的所有内容。

  • 您应该阅读和研究的资源

http://developer.android .com/reference/android/net/wifi/package-summary.html
如何在android中查看wifi是否已连接
如何在当前的 Android 系统中获取我的 wifi 热点 ssid
如何使用android API从android中获取wifi网络的名称?
获取 Android 上的 Wifi 接口名称

  • 创建应用程序清单时应请求的权限

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

( 最后一个,仅当您希望它检测您的位置时,以防止不必要的呼叫

  • 您还应该声明,您的应用程序需要设备中存在 wifi 才能正常工作:

AndroidManifest.xml

<uses-feature android:name="android.hardware.wifi" />

As long, as we are nothing like code as you need, for free service, I can only recommend you, to read everything possible about Android and its Network/Wifi possibilities, when creating such app.

  • Sources you should read up and study

http://developer.android.com/reference/android/net/wifi/package-summary.html
how to see if wifi is connected in android
How to get my wifi hotspot ssid in my current android system
How to get name of wifi-network out of android using android API?
Get Wifi Interface name on Android

  • Permissions you should ask for when creating application manifest

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

(the last one, only if you want it to detect your location, to prevent unnecessary calls)

  • You should also declare, that your application needs wifi to be available in device, to work properly:

AndroidManifest.xml

<uses-feature android:name="android.hardware.wifi" />
甜点 2025-01-14 11:03:39

使用标准代码列出所有可用网络:

  • 开始扫描

    字符串connectivity_context = Context.WIFI_SERVICE;
                最终 WifiManager wifi = (WifiManager) getSystemService(connectivity_context);  
    如果(wifi.isWifiEnabled()){
                            wifi.startScan();
                        }
    
  • 注册数据接收器

    IntentFilter i = new IntentFilter();
    i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    
    BroadcastReceiver 接收者 = new BroadcastReceiver() {
        @覆盖
        公共无效onReceive(上下文上下文,意图我){
            // TODO 自动生成的方法存根
            ScanWiFiActivity a = ScanWiFiActivity.instance();
            WifiManager w = (WifiManager) 上下文
                    .getSystemService(Context.WIFI_SERVICE);
            列表<扫描结果> l = w.getScanResults();
            a.清除();
            for (扫描结果 r : l) {
                                  //使用r.SSID或r.BSSID来识别您的家庭网络并采取行动
                a.setText(r.SSID + "" + r.level + "\r\n");
            }
        }
    };
    注册接收器(接收器,我);
    

在 FOR 块中,当您通过 SSID 或 BSSID 识别您的网络时,发挥您的魔力并采取行动

Use the standard code to list all available networks:

  • start the scan

    String connectivity_context = Context.WIFI_SERVICE;
                final WifiManager wifi = (WifiManager) getSystemService(connectivity_context);  
    if (wifi.isWifiEnabled()) {
                            wifi.startScan();
                        }
    
  • register a receiver for the data

    IntentFilter i = new IntentFilter();
    i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent i) {
            // TODO Auto-generated method stub
            ScanWiFiActivity a = ScanWiFiActivity.instance();
            WifiManager w = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            List<ScanResult> l = w.getScanResults();
            a.Clear();
            for (ScanResult r : l) {
                                  //use r.SSID or r.BSSID to identify your home network and take action
                a.setText(r.SSID + "" + r.level + "\r\n");
            }
        }
    };
    registerReceiver(receiver, i);
    

In the FOR block work your magic and take action when you identify your network by SSID or BSSID

半葬歌 2025-01-14 11:03:39

我的一个项目遇到了完全相同的问题,花了一段时间才找到解决方案。

首先,“连接到 WiFi”是一个非常抽象的东西,事实证明也是如此。在实践中,人们通常指的是以下所有阶段:

  • WiFi 接入点进行身份验证
  • 通过与接入点关联的
  • 从网络获取 IP 地址

所有这些阶段(以及其他几个阶段)都与不同的 Andoid 事件相关联。因此,言归正传,这是我的(稍作修改的)代码:

public class MyService extends Activity { // or Service

    //... Other stuff

    BroadcastReceiver awaitIPAddress = null;
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                if (intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE) == SupplicantState.COMPLETED) {
                    //WiFi is associated
                    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wi = wifiManager.getConnectionInfo();
                    if (wi != null) {
                        // Wifi info available (should be, we are associated)
                        if (wi.getIpAddress() != 0) {
                            // Lucky us, we already have an ip address.
                            // This happens when a connection is complete, e.g. after rekeying
                            if (wi.getBSSID().equals("c0:ff:ee:c0:ff:ee")) {
                                // ... Do your stuff here
                                // ...
                                // ...
                            }
                        } else {
                            // No ip address yet, we need to wait...
                            // Battery friendly method, using events
                            if (awaitIPAddress == null) {
                                awaitIPAddress = new BroadcastReceiver() {
                                    @Override
                                    public void onReceive(Context ctx, Intent in) {
                                        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                                        WifiInfo wi = wifiManager.getConnectionInfo();
                                        if (wi != null) {
                                            if (wi.getIpAddress() != 0) {
                                                if (wi.getBSSID().equals("c0:ff:ee:c0:ff:ee")) {
                                                    // ... Do your stuff here
                                                    // ...
                                                    // ...
                                                }
                                            }
                                        } else {
                                            ctx.unregisterReceiver(this);
                                            awaitIPAddress = null;
                                        }
                                    }
                                };
                                // We register a new receiver for connectivity events
                                // (getting a new IP address for example)
                                context.registerReceiver(awaitIPAddress, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                            }
                        }
                    }
                } else {
                    // wifi connection not complete, release ip address receiver if registered
                    if (awaitIPAddress != null) {
                        context.unregisterReceiver(awaitIPAddress);
                        awaitIPAddress = null;
                    }
                }
            }
        }
    };

    //... Other stuff

    @Override
    public void onCreate() {
        super.onCreate();
        //... Other stuff
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(receiver, filter);
        //... Other stuff
    }

    //... Other stuff

}

另外,不要忽视清单的适当权限:

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

而且我强烈怀疑您还需要:

<uses-permission android:name="android.permission.INTERNET"/>

I had exactly the same problem for a project of mine and it took a while to find a solution.

First of all, "connecting to a WiFi" is something very abstract, and it turns out rightly so. In practice, people usually mean all of the following:

  • authenticated with a WiFi access point
  • associated with the access point
  • got an ip address from the network

All these stages (and several more) are associated with different Andoid events. So, without further ado, here is my (slightly modified) code:

public class MyService extends Activity { // or Service

    //... Other stuff

    BroadcastReceiver awaitIPAddress = null;
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                if (intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE) == SupplicantState.COMPLETED) {
                    //WiFi is associated
                    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wi = wifiManager.getConnectionInfo();
                    if (wi != null) {
                        // Wifi info available (should be, we are associated)
                        if (wi.getIpAddress() != 0) {
                            // Lucky us, we already have an ip address.
                            // This happens when a connection is complete, e.g. after rekeying
                            if (wi.getBSSID().equals("c0:ff:ee:c0:ff:ee")) {
                                // ... Do your stuff here
                                // ...
                                // ...
                            }
                        } else {
                            // No ip address yet, we need to wait...
                            // Battery friendly method, using events
                            if (awaitIPAddress == null) {
                                awaitIPAddress = new BroadcastReceiver() {
                                    @Override
                                    public void onReceive(Context ctx, Intent in) {
                                        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                                        WifiInfo wi = wifiManager.getConnectionInfo();
                                        if (wi != null) {
                                            if (wi.getIpAddress() != 0) {
                                                if (wi.getBSSID().equals("c0:ff:ee:c0:ff:ee")) {
                                                    // ... Do your stuff here
                                                    // ...
                                                    // ...
                                                }
                                            }
                                        } else {
                                            ctx.unregisterReceiver(this);
                                            awaitIPAddress = null;
                                        }
                                    }
                                };
                                // We register a new receiver for connectivity events
                                // (getting a new IP address for example)
                                context.registerReceiver(awaitIPAddress, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                            }
                        }
                    }
                } else {
                    // wifi connection not complete, release ip address receiver if registered
                    if (awaitIPAddress != null) {
                        context.unregisterReceiver(awaitIPAddress);
                        awaitIPAddress = null;
                    }
                }
            }
        }
    };

    //... Other stuff

    @Override
    public void onCreate() {
        super.onCreate();
        //... Other stuff
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(receiver, filter);
        //... Other stuff
    }

    //... Other stuff

}

Also, don't neglect the appropriate permissions to the manifest:

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

And I strongly suspect you will also need:

<uses-permission android:name="android.permission.INTERNET"/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文