add wifi NetWork - Android Phone

Android examples for Phone:wifi

Description

add wifi NetWork

Demo Code


import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class Main{
    public static boolean addNetWork(WifiConfiguration cfg, Context mContext) {

        WifiManager wm = (WifiManager) mContext
                .getSystemService(Context.WIFI_SERVICE);

        WifiInfo mInfo = wm.getConnectionInfo();

        if (mInfo != null) {

            wm.disableNetwork(mInfo.getNetworkId());
            //         wm.disconnect();
        }//from  w  w  w .java  2s.  c  o  m

        boolean flag = false;

        if (cfg.networkId > 0) {

            Log.d(WifiUtil.class.getSimpleName(), "cfg networkId = "
                    + cfg.networkId);

            flag = wm.enableNetwork(cfg.networkId, true);

            wm.updateNetwork(cfg);
        } else {

            int netId = wm.addNetwork(cfg);

            Log.d(WifiUtil.class.getSimpleName(), "after adding netId = "
                    + netId);

            if (netId > 0) {
                wm.saveConfiguration();
                flag = wm.enableNetwork(netId, true);
            } else {

                //            Toast.makeText(mContext, "", Toast.LENGTH_SHORT).show();
            }
        }

        return flag;
    }
}

Related Tutorials