本文介绍了我如何连接到多个WiFi网络相继在Android上的另一个编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查使用Android API一些pre定义的开放WiFi网络的presence(我要检查他们的presence之前编程添加它们)。这就是我所做的。我创建了一个空白的活动如下:

I want to check the presence of some pre-defined open Wifi networks using the Android API (and I want to add them programatically before checking their presence). Here's what I've done. I have created a blank Activity as follows:

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名单,但是我得到一个消息不present。这很奇怪,因为当我去了Android的WiFi菜单,我最初没有看到无线是present但是当我打扫描我看到那些网络。

. I see that both the networks get added to my Wifi list however I get a message "Not present". This is strange because when I go to the Android's Wifi menu, I initially don't see the Wifi being present but when I hit scan I see those networks.

我要检查,如果我可以连接到的两个的的WiFi热点。我要连接到一个热点断开,然后连接到另一个。我该怎么做呢?

I want to check if I can connect to both the Wifi hotspots. I want connect to one hotspot disconnect and then connect to another one. How do I do this?

编辑:

我也注意到,没有被从列表中删除的WiFi网络,我补充。是否有任何特别的原因?

I also note that the Wifi networks that I add are not being removed from the list. Is there any particular reason for this?

编辑2

我甚至试图改变我的整个code听广播接收器分开扫描和连接,而且也经过一定的时间间隔。因此,这里是我所做的:

I even tried changing my entire code to listen to BroadcastReceiver for scan and connection separately and that too after certain intervals of time. So here's what I did:

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是连接检查接收器是没有得到调用。我不知道为什么。

**Edit 3: **I also noticed that the receiver for checking if Wifi is connected is not getting called. I am not sure why.

推荐答案

请方法改变你的MyWifi(),以

Please change your MyWifi() method to

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);

}

这会工作。

这篇关于我如何连接到多个WiFi网络相继在Android上的另一个编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 01:16