如何在Android中以编程方式逐个连接到多个Wifi网络?

时间:2014-08-01 07:46:43

标签: java android android-wifi

我想使用Android API检查是否存在一些预定义的开放Wifi网络(我想在检查它们的存在之前以编程方式添加它们)。这就是我所做的。我创建了一个空白活动,如下所示:

WifiManager wifiManager;
protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        myWifis();
    }

public void myWifis() {
    //Add first network
    wcOne = new WifiConfiguration();
    wcOne.SSID = "\"" + networkOne + "\"";
    wcOne.status = WifiConfiguration.Status.ENABLED;
    wcOne.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    //Get Network ID from the wifiManager Object
    netOneId = wifiManager.addNetwork(wcOne);
    if (networkOneId != -1) {
        networkOnePresent = wifiManager.enableNetwork(wcOne.networkId, true);
    }

    //Add second network
    wcTwo = new WifiConfiguration();
    wcTwo.SSID = "\"" + networkTwo + "\"";
    wcTwo.status = WifiConfiguration.Status.ENABLED;
    wcTwo.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    //Get Network ID from the wifiManager Object
    netTwoId = mainWifiObj.addNetwork(wcTwo);        
    if (netTwoId != -1) {
        networkTwoPresent = mainWifiObj.enableNetwork(wcTwo.networkId, true);
    }

     if(networkOnePresent && networkTwoPresent)
        createAlert(true);
    else
        createAlert(false);

    wifiManager.disconnect();
    wifiManager.removeNetwork(wcOne.networkId);
    wifiManager.removeNetwork(wcTwo.networkId);

}

public void createAlert(boolean bothNetworksPresent){
        if(bothNetworksPresent){
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            alertDialog.setTitle("Both networks present")
                    .setMessage("Both networks present")
                    .setCancelable(false)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog, int id){

                        }
                    });
            AlertDialog dialog = alertDialog.create();
            dialog.show();
        }
        else{
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            alertDialog.setTitle("Not Present")
                    .setMessage("Not Present")
                    .setCancelable(false)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog, int id){

                        }
                    });
            AlertDialog dialog = alertDialog.create();
            dialog.show();
        }
    }

。 我看到两个网络都被添加到我的Wifi列表中但是我得到了一条消息"不存在"。这很奇怪,因为当我进入Android的Wifi菜单时,我最初看不到Wifi存在,但是当我点击扫描时,我看到了那些网络。

我想检查一下是否可以连接两个 Wifi热点。我希望连接到一个热点断开然后连接到另一个热点。我该怎么做?

修改

我还注意到我添加的Wifi网络没有从列表中删除。这有什么特别的原因吗?

修改2

我甚至尝试更改我的整个代码以分别监听BroadcastReceiver扫描和连接,并且在一定时间间隔之后也是如此。所以这就是我所做的:

WifiManager wifiManager;
private final Handler mHandler = new Handler();
public final String TAG = "myWifiScanner";
boolean isOneAdded = false, isTwoAdded = false, isThreeAdded = false;
boolean isOneConnected = false, isTwoConnected = false, isThreeConnected = false;
boolean isOneEnabled = false, isTwoEnabled = false, isThreeEnabled = false;
IntentFilter iFScan, iFConnect;
List<ScanResult> scanList;

protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        checkConnections();
    }

private void receiverMethod(){
    //iFScan = new IntentFilter();
    iFConnect = new IntentFilter();
    iFConnect.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    iFConnect.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);        
    //registerReceiver(scanR, iFScan);
    registerReceiver(connectR, iFConnect);
    wifiManager.startScan();
    Log.d(TAG, "\nScan started\n");
}

private final BroadcastReceiver connectR = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
            if(intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)){
                String ssid = null;
                ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if(netInfo.isConnected()){
                    final WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
                    final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
                    if(connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())){
                        ssid = connectionInfo.getSSID();
                        if(isOneAdded && ssid.equals(networkOne)){
                            isOneConnected = true;
                            Log.d(TAG, "One Connected\n");
                        }
                        if(isTwoAdded && ssid.equals(networkTwo)){
                            isTwoConnected = true;
                            Log.d(TAG, "Two Connected\n");
                        }
                        if(isThreeAdded && ssid.equals(networkThree)){
                            isThreeConnected = true;
                            Log.d(TAG, "Three Connected\n");
                        }
                }
            }
        }
        if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
            scanList = wifiManager.getScanResults();
            for(int i = 0; i < scanList.size(); i++){                
                if(isOneAdded && scanList.get(i).toString().contains(networkOne)){
                    isOneEnabled = true;
                    Log.d(TAG, "One Enabled\n");
                }
                if(isTwoAdded && scanList.get(i).toString().contains(networkTwo)){
                    isTwoEnabled = true;
                    Log.d(TAG, "Two Enabled\n");
                }
                if(isThreeAdded && scanList.get(i).toString().contains(networkThree)){
                    isThreeEnabled = true;
                    Log.d(TAG, "Three Enabled\n");
                }
            } 
        }
    }
};

public final Runnable addNetworkOne = new Runnable() {
    @Override
    public void run() {
        //Add first network
        wcOne = new WifiConfiguration();
        wcOne.SSID = "\"" + networkOne + "\"";
        wcOne.status = WifiConfiguration.Status.ENABLED;
        wcOne.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        //Get Network ID from the wifiManager Object
        netOneId = wifiManager.addNetwork(wcOne);
        if (networkOneId != -1) {
            networkOnePresent = wifiManager.enableNetwork(wcOne.networkId, true);
        }
    }
    isOneAdded = true
    receiverMethod();
};

public final Runnable addNetworkTwo = new Runnable() {
    @Override
    public void run() {
        //Add second network
        wcTwo = new WifiConfiguration();
        wcTwo.SSID = "\"" + networkTwo + "\"";
        wcTwo.status = WifiConfiguration.Status.ENABLED;
        wcTwo.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        //Get Network ID from the wifiManager Object
        netTwoId = wifiManager.addNetwork(wcTwo);        
        if (netTwoId != -1) {
            networkTwoPresent = wifiManager.enableNetwork(wcTwo.networkId, true);
        }
    }
    isTwoAdded = true
    receiverMethod();
};

public final Runnable addNetworkThree = new Runnable() {
    @Override
    public void run() {
        //Add three network
        wcThree = new WifiConfiguration();
        wcThree.SSID = "\"" + networkThree + "\"";
        wcThree.status = WifiConfiguration.Status.ENABLED;
        wcThree.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        //Get Network ID from the wifiManager Object
        netThreeId = wifiManager.addNetwork(wcTwo);        
        if (netThreeId != -1) {
            networkThreePresent = wifiManager.enableNetwork(wcThree.networkId, true);
        }
    }
    isThreeAdded = true
    receiverMethod();
};


public final Runnable areAllWifisPresent = new Runnable() {
    @Override
    public void run() {
        if(isOneEnabled && isTwoEnabled && isThreeeEnabled){
            if(isOneConnected && isTwoConnected && isThreeConnected){
                Log.d(TAG, "All three Wifis are present.");
            }
        }
};


public void checkConnections() {
    mHandler.postDelayaed(addNetworkOne, 10*1000);
    mHandler.postDelayed(addNetworkTwo, 20*1000);
    mHandler.postDelayed(addNetworkThree, 30*1000);
    mHandler.postDelayed(areAllWifisPresent, 40*1000); 

    //wifiManager.disconnect();
    //wifiManager.removeNetwork(wcOne.networkId);
    //wifiManager.removeNetwork(wcTwo.networkId);
    //wifiManager.removeNetwork(wcThree.networkId);

}

**编辑3:** 我还注意到用于检查Wifi是否已连接的接收器未被调用。我不知道为什么。

1 个答案:

答案 0 :(得分:3)

请将您的MyWifi()方法更改为

public void myWifis() {
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                        wifiManager.setWifiEnabled(true);

    //Add first network
    wcOne = new WifiConfiguration();
    wcOne.SSID = "\""+SSID+"\"";
    wcOne.status = WifiConfiguration.Status.ENABLED;
    wcOne.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    //Get Network ID from the MainWiFi Object
    int netOneId = mainWifiObj.addNetwork(wcOne);
    boolean networkOnePresent = false;

//this way we will enable wifi network.
    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for( WifiConfiguration i : list ) {
        Log.d("wifi", "wifi SSID is = "+i.SSID);
        if(i.SSID != null && i.SSID.equals("\"" + SSID + "\"")) {
             wifiManager.disconnect();
             networkOnePresent = wifiManager.enableNetwork(i.networkId, true);
             wifiManager.reconnect();               
             Log.d("wifi", "net id is = "+netOneId);
             break;
        }           
     }

     if(networkOnePresent)
            createAlert(true);
        else
            createAlert(false);

}

它会起作用。