How to connect Wi-Fi in Android
I am a new student for Android application development. I have currently made a wifi connection code for android to make the connection. The app shows available connections, but I can't connect to specific Wi-Fi connections.
Below is one link when I get from a search and I see many of these types of connections in my university premises.
Ex: capabilities [WPA2-PSK CCMP] [WPS] [ESS], level: -37, freequency 2412 timestamp: 9103895476
Could you please help me to solve this problem and correctly connect to the available connections. Also I decided to implement the Wifi on / off button and had no clear idea for this implementation.
Below is my Java code
TextView mainText;
WifiManager mainWifi;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_connections);
mainText = (TextView) findViewById(R.id.mainText);
// Initiate wifi service manager
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Check for wifi is disabled
if (mainWifi.isWifiEnabled() == false)
{
// If wifi disabled then enable it
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
mainWifi.setWifiEnabled(true);
}
// wifi scaned value broadcast receiver
receiverWifi = new WifiReceiver();
// Register broadcast receiver
// Broacast receiver will automatically call when number of wifi connections changed
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
mainText.setText("Starting Scan...");
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Refresh");
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
mainWifi.startScan();
mainText.setText("Starting Scan");
return super.onMenuItemSelected(featureId, item);
}
protected void onPause() {
unregisterReceiver(receiverWifi);
super.onPause();
}
protected void onResume() {
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
// Broadcast receiver class called its receive method
// when number of wifi connections changed
class WifiReceiver extends BroadcastReceiver {
// This method call when number of wifi connections changed
public void onReceive(Context c, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
sb.append("\n Number Of Wifi connections :"+wifiList.size()+"\n\n");
for(int i = 0; i < wifiList.size(); i++){
sb.append(new Integer(i+1).toString() + ". ");
sb.append((wifiList.get(i)).toString());
sb.append("\n\n");
}
mainText.setText(sb);
}
}
Below is my manifest code
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.androidexample.wificonnections.WifiConnections"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
source to share
The first step is to determine what type of encryption the access point has. For this you can refer to my other answer here .
Here's the code you could use to check the encryption type of a particular SSID:
public String getEncryptionType(String ssid){
String encryptType = "";
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
List<ScanResult> networkList = wifi.getScanResults();
if (networkList != null) {
for (ScanResult network : networkList)
{
//check if current connected SSID
if (ssid.equals(network.SSID)){
//get capabilities of current connection
String Capabilities = network.capabilities;
Log.d (TAG, network.SSID + " capabilities : " + Capabilities);
if (Capabilities.contains("WPA2")) {
encryptType = "WPA2";
}
else if (Capabilities.contains("WPA")) {
encryptType = "WPA";
}
else if (Capabilities.contains("WEP")) {
encryptType = "WEP";
}
}
}
}
return encryptType;
}
Then, once you determine which access point the user should connect to, you will need to prompt them for the correct credentials, and then configure the device with correct authentication to connect to the selected access point (SSID).
The link is my other answer on this as well as this question and also this is a pretty complete guide .
Here is the code I got and tested, taken from my other answer:
To connect to WEP:
public boolean ConnectToNetworkWEP( String networkSSID, String password )
{
try {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain SSID in quotes
conf.wepKeys[0] = "\"" + password + "\""; //Try it with quotes first
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.OPEN);
conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.SHARED);
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int networkId = wifiManager.addNetwork(conf);
if (networkId == -1){
//Try it again with no quotes in case of hex password
conf.wepKeys[0] = password;
networkId = wifiManager.addNetwork(conf);
}
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
//WiFi Connection success, return true
return true;
} catch (Exception ex) {
System.out.println(Arrays.toString(ex.getStackTrace()));
return false;
}
}
To connect to WPA2:
public boolean ConnectToNetworkWPA( String networkSSID, String password )
{
try {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain SSID in quotes
conf.preSharedKey = "\"" + password + "\"";
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
Log.d("connecting", conf.SSID + " " + conf.preSharedKey);
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
Log.d("after connecting", conf.SSID + " " + conf.preSharedKey);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
Log.d("re connecting", i.SSID + " " + conf.preSharedKey);
break;
}
}
//WiFi Connection success, return true
return true;
} catch (Exception ex) {
System.out.println(Arrays.toString(ex.getStackTrace()));
return false;
}
}
Then, once you have multiple SSIDs configured on your device, if the user of your app wants to force a connection to one specific SSID, and more than one range exists, you will run into another problem. You will need to disable the SSID the user does not want to connect to and enable the SSID the user wants to connect to. You can link to my other answer about this here .
Please note that this example code is only for two APs in a band, for more than two bands, you need to disable all other configured SSIDs to force a connection to one SSID.
Here's a general idea for solving this problem:
public void connectToNetwork(String ssid){
WifiInfo info = mWifiManager.getConnectionInfo(); //get WifiInfo
int id = info.getNetworkId(); //get id of currently connected network
for (WifiConfiguration config : configurations) {
// If it was cached connect to it and that all
if (config.SSID != null && config.SSID.equals("\"" +ssid + "\"")) {
// Log
Log.i("connectToNetwork", "Connecting to: " + config.SSID);
mWifiManager.disconnect();
mWifiManager.disableNetwork(id); //disable current network
mWifiManager.enableNetwork(config.networkId, true);
mWifiManager.reconnect();
break;
}
}
}
source to share