How do I program android to look for a particular network?

蹲街弑〆低调 提交于 2019-12-04 06:24:14

问题


My application only works if it's on the campus network in order to access campus data. When running the application on public wifi or 3g network, the application will hang then force close. How do I program my application to check for that private network/wifi or check what connection android is currently using, if not equal to "campus wifi" then....?


回答1:


From what you are saying i think you want to enforce application to use only Campus wifi.

So here you go

Create WifiConfiguration instance:

String networkSSID = "put network SSID here";
String networkPass = "put network password here";

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";   //ssid must be in quotes

Then, for WEP network you need to do this:

conf.wepKeys[0] = "\"" + networkPass + "\""; 
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 

For WPA network you need to add passphrase like this:

conf.preSharedKey = "\""+ networkPass +"\"";

For Open network you need to do this:

conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

Then, you need to add it to Android wifi manager settings:

WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
wifiManager.add(conf);

And finally, you might need to enable it, so Android conntects to it:

List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
    if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
         wm.disconnect();
         wm.enableNetwork(i.networkId, true);
         wm.reconnect();                

         break;
    }           
 }

Note that In case of WEP, if your password is in hex, you do not need to surround it with quotes.



来源:https://stackoverflow.com/questions/11060414/how-do-i-program-android-to-look-for-a-particular-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!