1. 程式人生 > >Android Wifi 資訊儲存與忘記

Android Wifi 資訊儲存與忘記

最近在做專案的時候,遇到一個需求,在某一個頁面內需要連線指定Wifi,當退出這個頁面時需要恢復原來的網路狀態。於是就想到了退出頁面時忘記此時連線的指定wifi。於是,程式碼開始了

WifiManager mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
mWifiManager.forget()...

等等,為什麼forget是紅色的,沒提示呢???驚歎三秒鐘只有趕緊回原始碼檢視,原來是這樣的

/**
     * Delete the network in the supplicant config.
     *
     * This function is used instead of a sequence of removeNetwork()
     * and saveConfiguration().
     *
     * @param
config the set of variables that describe the configuration, * contained in a {@link WifiConfiguration} object. * @param listener for callbacks on success or failure. Can be null. * @throws IllegalStateException if the WifiManager instance needs to be * initialized again * @hide
*/
public void forget(int netId, ActionListener listener) { if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative"); getChannel().sendMessage(FORGET_NETWORK, netId, putListener(listener)); }

看到這個@hide了沒,原來這方法被隱藏掉了,看來要用只能用反射了啊,可是還是不甘心,不想用反射,於是就繼續找啊找啊,於是在這個方法的註釋裡找到了這個:

* This function is used instead of a sequence of removeNetwork()
     * and saveConfiguration().

好吧,我們就看看removeNetwork(),

/**
     * Remove the specified network from the list of configured networks.
     * This may result in the asynchronous delivery of state change
     * events.
     * @param netId the integer that identifies the network configuration
     * to the supplicant
     * @return {@code true} if the operation succeeded
     */
    public boolean removeNetwork(int netId) {
        try {
            return mService.removeNetwork(netId);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

看了上面的註釋,大夥都應該明白了。於是問題完美解決,同樣的save也用saveConfiguration()替代

/**
     * Tell the supplicant to persist the current list of configured networks.
     * <p>
     * Note: It is possible for this method to change the network IDs of
     * existing networks. You should assume the network IDs can be different
     * after calling this method.
     *
     * @return {@code true} if the operation succeeded
     */
    public boolean saveConfiguration() {
        try {
            return mService.saveConfiguration();
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

好了,就這樣,再查資料的時候找到了有些部落格,命名上面方法寫的@hide,下面程式碼還是用forget,不知道最後成功了沒。。。

歡迎不同意見的朋友一起留言討論,共同學習進步。