Wifi connection android code

How to connect wifi in android

I’m new student for android app developing, Currently I did the Android Wifi connection code in order to make the connectivity.The app is showing the available connections but I cannot possible to connect in to specific wifi connections. Below is the one connectivity when i get from searching and i can see lot of these type 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 overcome this problem and connect correctly to available connections. Also i have decide to implement Wifi ON/OFF button and didnt have clear idea for this implementation.. Below is my Java code

TextView mainText; WifiManager mainWifi; WifiReceiver receiverWifi; List 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); > > 

Источник

Creating an Android WiFi Connection Using Code

In the MainActivity.kt class, the device can connect to a WiFi network, but it requires the manual turning off and on of WiFi. When switching from the mobile network to a certain WiFi network, an unstable connection arises. To solve this issue, the WiFi connection is established through the specific network, and then forgotten after a 3-second delay before reconnecting again. Additionally, the AndroidManifest.xml permission is required.

Android WiFi connection programmatically

Can you suggest a method for setting up wifi connection on my android app that involves password transmission?

Provide the method with both the SSID and its corresponding password.

public void connectToAP(String ssid, String passkey) < Log.i(TAG, "* connectToAP"); WifiConfiguration wifiConfiguration = new WifiConfiguration(); String networkSSID = ssid; String networkPass = passkey; Log.d(TAG, "# password " + networkPass); for (ScanResult result : scanResultList) < if (result.SSID.equals(networkSSID)) < String securityMode = getScanResultSecurity(result); if (securityMode.equalsIgnoreCase("OPEN")) < wifiConfiguration.SSID = "\"" + networkSSID + "\""; wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); int res = wifiManager.addNetwork(wifiConfiguration); Log.d(TAG, "# add Network returned " + res); boolean b = wifiManager.enableNetwork(res, true); Log.d(TAG, "# enableNetwork returned " + b); wifiManager.setWifiEnabled(true); >else if (securityMode.equalsIgnoreCase("WEP")) < wifiConfiguration.SSID = "\"" + networkSSID + "\""; wifiConfiguration.wepKeys[0] = "\"" + networkPass + "\""; wifiConfiguration.wepTxKeyIndex = 0; wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); int res = wifiManager.addNetwork(wifiConfiguration); Log.d(TAG, "### 1 ### add Network returned " + res); boolean b = wifiManager.enableNetwork(res, true); Log.d(TAG, "# enableNetwork returned " + b); wifiManager.setWifiEnabled(true); >wifiConfiguration.SSID = "\"" + networkSSID + "\""; wifiConfiguration.preSharedKey = "\"" + networkPass + "\""; wifiConfiguration.hiddenSSID = true; wifiConfiguration.status = WifiConfiguration.Status.ENABLED; wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); int res = wifiManager.addNetwork(wifiConfiguration); Log.d(TAG, "### 2 ### add Network returned " + res); wifiManager.enableNetwork(res, true); boolean changeHappen = wifiManager.saveConfiguration(); if(res != -1 && changeHappen)< Log.d(TAG, "### Change happen"); AppStaticVar.connectedSsidName = networkSSID; >else < Log.d(TAG, "*** Change NOT happen"); >wifiManager.setWifiEnabled(true); > > > public String getScanResultSecurity(ScanResult scanResult) < Log.i(TAG, "* getScanResultSecurity"); final String cap = scanResult.capabilities; final String[] securityModes = < "WEP", "PSK", "EAP" >; for (int i = securityModes.length - 1; i >= 0; i--) < if (cap.contains(securityModes[i])) < return securityModes[i]; >> return "OPEN"; > 

Remember to include the required authorization in the Manifest file.

Читайте также:  Вай фай билайн все включено

Here’s the MainActivity.java code that enables you to establish a connection with specific Wifi.

 WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", "Wifi name"); wifiConfig.preSharedKey = String.format("\"%s\"", "Wifi password"); WifiManager wifiManager=(WifiManager)getSystemService(WIFI_SERVICE); int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); 

Additionally, ensure that you add this code to your AndroidManifest.xml file.

The code shared by AnujAroshA is quite useful, however, there is a missing else condition.

 .. > else if (securityMode.equalsIgnoreCase("PSK")) < // PSK code .. 

The PSK code is not exclusively executed for WPA networks, but also for WEP and OPEN networks.

In my opinion, the code style could be improved. There is no need to create two separate Strings named networkSSID and networkPass. Instead, you can just use ssid and passkey.

Consider dividing the process of creating the wifi configuration from the method of connecting to it.

(1) Procedure for generating the wificonfiguration :

private WifiConfiguration createAPConfiguration(String networkSSID, String networkPasskey, String securityMode) < WifiConfiguration wifiConfiguration = new WifiConfiguration(); wifiConfiguration.SSID = "\"" + networkSSID + "\""; if (securityMode.equalsIgnoreCase("OPEN")) < wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); >else if (securityMode.equalsIgnoreCase("WEP")) < wifiConfiguration.wepKeys[0] = "\"" + networkPasskey + "\""; wifiConfiguration.wepTxKeyIndex = 0; wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); >else if (securityMode.equalsIgnoreCase("PSK")) < wifiConfiguration.preSharedKey = "\"" + networkPasskey + "\""; wifiConfiguration.hiddenSSID = true; wifiConfiguration.status = WifiConfiguration.Status.ENABLED; wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); >else < Log.i(TAG, "# Unsupported security mode: "+securityMode); return null; >return wifiConfiguration; > 

(2) Method for the AP connect:

 public int connectToAP(String networkSSID, String networkPasskey) < for (ScanResult result : scanResultList) < if (result.SSID.equals(networkSSID)) < String securityMode = getScanResultSecurity(result); WifiConfiguration wifiConfiguration = createAPConfiguration(networkSSID, networkPasskey, securityMode); int res = wifiManager.addNetwork(wifiConfiguration); Log.d(TAG, "# addNetwork returned " + res); boolean b = wifiManager.enableNetwork(res, true); Log.d(TAG, "# enableNetwork returned " + b); wifiManager.setWifiEnabled(true); boolean changeHappen = wifiManager.saveConfiguration(); if (res != -1 && changeHappen) < Log.d(TAG, "# Change happen"); connectedSsidName = networkSSID; >else < Log.d(TAG, "# Change NOT happen"); >return res; > > return -1; > 

As per AnujAroshA's post, the scanning technique has a success rate of 100%.

public String getScanResultSecurity(ScanResult scanResult) < final String cap = scanResult.capabilities; final String[] securityModes = < "WEP", "PSK", "EAP" >; for (int i = securityModes.length - 1; i >= 0; i--) < if (cap.contains(securityModes[i])) < return securityModes[i]; >> return "OPEN"; > 

Give your ssid and password

 fun connectToWifi(ssid: String, password: String)

Java - Android - connect to wifi programmatically, Here are two possible solutions to your problem: 1) This is the easiest solution, but not the best. Loop as described by another user checking for the …

Android - connect to wifi programmatically

I am interested in establishing a programmatic connection to WiFi network.

wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(true); WifiConfiguration config = new WifiConfiguration(); config.SSID = "\"" + ssid + "\""; config.preSharedKey = "\""+ key +"\""; int netId = wifiManager.addNetwork(config); wifiManager.saveConfiguration(); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); 

My phone operates efficiently with wifi enabled, however, the issue arises when wifi is turned off. It only shows the enabling wifi adapter without connecting to the network, which indicates that it may take too long to enable. Additionally, I find it peculiar that the wifiManager.getConfiguredNetworks() returns null. Can you suggest a solution to this problem?

The connection does not seem to establish because the process of enabling takes too much time.

Indeed, the reason for this is that the network activation is performed asynchronously, meaning it takes place simultaneously and not instantly. To address your issue, consider these two potential remedies:

Читайте также:  Сеть асус вай фай

The most straightforward way to solve the problem is by using a loop, but it may not be optimal. Another user has suggested using a loop to check for the scan results, but it's important to include a sleep command between each cycle to avoid consuming too many CPU resources. However, implementing this in Android is not immediately clear. Additionally, this method can cause issues if you are in the GUI thread as it can block all GUI events while waiting for the connection to be established.

Here's a viable solution: Wait until the network connection is established before registering for broadcast events. Once the network connection is established, you'll receive an event notification indicating its completion. You can then carry out any necessary operations.

Please accept my apologies for the hurried response. Although I lack expertise in Android, I cannot provide an immediate explanation of how to accomplish this. However, I can lead you in the correct direction.

Performing connect WiFi multiple times can effectively resolve the problem.

If my WiFi network is enabled and connected, I can confirm that it's functioning properly.

When I switch from using my mobile network to a particular WiFi network, the connection becomes unstable. To resolve this issue, I connect to the specific WiFi network and then forget it after a 3-second delay. Then, I reconnect and the connection works correctly.

This code comes in handy when there is a delay or when the WiFi network is not available.

 < wifi(SSID,PASS); final Handler handler = new Handler(); handler.postDelayed( new Runnable() < Override public void run() < forgot(); >>, 3000); final Handler handler1 = new Handler(); handler1.postDelayed( new Runnable() < Override public void run() >, 3000); > 

Connect to Wifi in Android Q programmatically, Connect to a network as follows: val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder () .setSsid (ssid) .setWpa2Passphrase (pass) .build …

Connecting to a specific wifi network programmatically in Android (API 30)

The objective is to establish a connection with the switch to a specific WiFi network automatically, without requiring any manual intervention except for entering the username and password.

Code Snippet

The MainActivity is a class that extends AppCompatActivity().

private var lastSuggestedNetwork:WifiNetworkSuggestion? = null var wifiManager:WifiManager? = null override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager val button = findViewById 

The current code allows the device to connect to the WiFi network, but it requires manual turning off and on of the WiFi. A more efficient method is needed to connect or switch to a specific WiFi network without any manual intervention.

  1. Launch the app and tap the button located on the main screen to establish a WiFi connection.
  2. Navigate to the settings menu and toggle the WiFi option off and back on again.
  3. The desired WiFi network has been connected by the device.

The image located at the link provided shows the output.

Eliminate the second step by utilizing programming methods.

Can a network configuration be included in Android Q? (Ref: Is it achievable?)

To clarify, the code snippet contains the ssid and password for the default AVD. However, they can be modified to work on any other WiFi connection. I have tested this on a Pixel 3XL and encountered the same issue. It should also work on physical devices.

To prompt users to enable wifi, you have the option to use either the new Settings.Panel (API 29+) or the old Settings API in a polite manner. Moreover, startActivityForResult() can be utilized to verify that the user has indeed enabled wifi through the Settings.

if(!wifiManager.isWifiEnabled()) < if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) < startActivity(new Intent(Settings.Panel.ACTION_WIFI)); >else < // Use a full page activity - if Wifi is critcal for your app startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); // Or use the deprecated method wifiManager.setWifiEnabled(true) >> 

Please be aware that this approach is effective only when you're not aiming at Android Q (API 29) or later.

Unfortunately, there is no automated method available to activate the process.

Wifi - Programmatically connect to an android device in, How do I connect to a specific Wi-Fi network in Android programmatically? 0. Wifi connection code. Related. 2085. Is there a way to run …

Источник

Android WiFi connection programmatically

Do you have any idea how to establish a wifi connection with sending password in my android application?

4 Answers 4

Pass the SSID and it's password to the following method.

public void connectToAP(String ssid, String passkey) < Log.i(TAG, "* connectToAP"); WifiConfiguration wifiConfiguration = new WifiConfiguration(); String networkSSID = ssid; String networkPass = passkey; Log.d(TAG, "# password " + networkPass); for (ScanResult result : scanResultList) < if (result.SSID.equals(networkSSID)) < String securityMode = getScanResultSecurity(result); if (securityMode.equalsIgnoreCase("OPEN")) < wifiConfiguration.SSID = "\"" + networkSSID + "\""; wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); int res = wifiManager.addNetwork(wifiConfiguration); Log.d(TAG, "# add Network returned " + res); boolean b = wifiManager.enableNetwork(res, true); Log.d(TAG, "# enableNetwork returned " + b); wifiManager.setWifiEnabled(true); >else if (securityMode.equalsIgnoreCase("WEP")) < wifiConfiguration.SSID = "\"" + networkSSID + "\""; wifiConfiguration.wepKeys[0] = "\"" + networkPass + "\""; wifiConfiguration.wepTxKeyIndex = 0; wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); int res = wifiManager.addNetwork(wifiConfiguration); Log.d(TAG, "### 1 ### add Network returned " + res); boolean b = wifiManager.enableNetwork(res, true); Log.d(TAG, "# enableNetwork returned " + b); wifiManager.setWifiEnabled(true); >wifiConfiguration.SSID = "\"" + networkSSID + "\""; wifiConfiguration.preSharedKey = "\"" + networkPass + "\""; wifiConfiguration.hiddenSSID = true; wifiConfiguration.status = WifiConfiguration.Status.ENABLED; wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); int res = wifiManager.addNetwork(wifiConfiguration); Log.d(TAG, "### 2 ### add Network returned " + res); wifiManager.enableNetwork(res, true); boolean changeHappen = wifiManager.saveConfiguration(); if(res != -1 && changeHappen)< Log.d(TAG, "### Change happen"); AppStaticVar.connectedSsidName = networkSSID; >else < Log.d(TAG, "*** Change NOT happen"); >wifiManager.setWifiEnabled(true); > > > public String getScanResultSecurity(ScanResult scanResult) < Log.i(TAG, "* getScanResultSecurity"); final String cap = scanResult.capabilities; final String[] securityModes = < "WEP", "PSK", "EAP" >; for (int i = securityModes.length - 1; i >= 0; i--) < if (cap.contains(securityModes[i])) < return securityModes[i]; >> return "OPEN"; > 

Don't forget to add necessary permission in the Manifest file.

Источник

Оцените статью
Adblock
detector