关于android:从上次连接的WIFI中获取WIFI ID | 珊瑚贝

Get WIFI ID from last connected WIFI


我正在编写一个 Android 应用程序,它会在手机连接或断开 WIFI 网络时做出反应。我为此注册了一个 BroadcastReceiver 并且效果很好。现在,如果手机连接到 WIFI,我可以使用此代码获取当前的 WIFI ID:

1
2
3
4
WifiManager mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo currentWifi = mainWifi.getConnectionInfo();

int id = currentWifi.getNetworkId();

但是如果 WIFI 断开连接,我想获取最后连接的 WIFI 的 WIFI ID 怎么办?我的问题是所有这些都在 BroadcastReceiver 中。如果有新的广播进来,这总是新创建的,所以我不能真正在那里保存一些数据。有没有什么方法或其他方法可以让我获得最后连接的 WIFI ID?


如果我遗漏了什么,请原谅我。您可以 getSharedPreferences 获得从广播接收器访问的上下文。

这个BroadcastReceiver拦截android.net.ConnectivityManager.CONNECTIVITY_ACTION,它表示连接发生了变化。它检查类型是否为 TYPE_WIFI。如果是,它会检查 Wi-Fi 是否已连接,并相应地在主活动中设置 wifiConnected 标志。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class NetworkReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connMgr =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        // Checks the user prefs and the network connection. Based on the result, decides
        // whether
        // to refresh the display or keep the current display.
        // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
        if (WIFI.equals(sPref) && networkInfo != null
                && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            // If device has its Wi-Fi connection, sets refreshDisplay
            // to true. This causes the display to be refreshed when the user
            // returns to the app.

您可以在此处找到示例应用程序。


来源:https://www.codenong.com/29534381/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9272.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?