Get WIFI ID from last connected WIFI
我正在编写一个 Android 应用程序,它会在手机连接或断开 WIFI 网络时做出反应。我为此注册了一个
1 2 3 4 | WifiManager mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo currentWifi = mainWifi.getConnectionInfo(); int id = currentWifi.getNetworkId(); |
但是如果 WIFI 断开连接,我想获取最后连接的 WIFI 的 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. |
您可以在此处找到示例应用程序。