从上次连接的WIFI获取WIFI ID

时间:2015-04-09 09:13:19

标签: android broadcastreceiver android-wifi

我正在编写一个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?

1 个答案:

答案 0 :(得分:1)

如果我错过了什么,请原谅我。您可以getSharedPreferences从广播接收器访问上下文。

此BroadcastReceiver拦截android.net.ConnectivityManager.CONNECTIVITY_ACTION,表示连接更改。它检查类型是否为TYPE_WIFI。如果是,则检查Wi-Fi是否已连接,并相应地在主活动中设置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