【问题标题】:Get WIFI ID from last connected WIFI从上次连接的 WIFI 获取 WIFI ID
【发布时间】:2015-06-14 13:49:11
【问题描述】:

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

WifiManager mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo currentWifi = mainWifi.getConnectionInfo();

int id = currentWifi.getNetworkId();

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

【问题讨论】:

    标签: android broadcastreceiver android-wifi


    【解决方案1】:

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

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

    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. 
    

    您可以在这里找到sample app

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2019-03-01
      相关资源
      最近更新 更多