- Java android wifi connect
- crearo / WiFiConnector.java
- Saved searches
- Use saved searches to filter your results more quickly
- japrogbogdan/wifi-connect
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Java android wifi connect
A subreddit for all questions related to programming in any language.
I’m building an Android app that uses OCR to capture a wifi name and password from a picture.
I have everything done except I can’t get the connect functionality to work.
How can I connect to a WiFi network once I have the network name and password?
UPDATE: Added network suggestion rather than connecting directly. I just allow android to automatically connect shortly after. It’s now working , thanks to everyone for commenting.
String networkSSID = nameEditText.getText().toString(); String networkPass = passwordEditText.getText().toString(); WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) < wifiManager.setWifiEnabled(true); >if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) < WifiNetworkSuggestion networkSuggestion1 = new WifiNetworkSuggestion.Builder() .setSsid(networkSSID) .setWpa2Passphrase(networkPass) .build(); WifiNetworkSuggestion networkSuggestion2 = new WifiNetworkSuggestion.Builder() .setSsid(networkSSID) .setWpa3Passphrase(networkPass) .build(); ListsuggestionsList = new ArrayList<>(); suggestionsList.add(networkSuggestion1); suggestionsList.add(networkSuggestion2); wifiManager.addNetworkSuggestions(suggestionsList); > else
I don’t entirely understand what WPA2 and WPA3 are, for now I’m adding both as suggestions. I’ve also only tested it on my device running Android 9 so it followed the ‘else’ block. I believe I had something similar (or maybe even the same) as that earlier, not sure why it wasn’t working.
crearo / WiFiConnector.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
package com . tonbo . streamer . network ; |
import android . content . Context ; |
import android . content . IntentFilter ; |
import android . net . NetworkInfo ; |
import android . net . wifi . ScanResult ; |
import android . net . wifi . WifiConfiguration ; |
import android . net . wifi . WifiInfo ; |
import android . net . wifi . WifiManager ; |
import android . support . annotation . CheckResult ; |
import android . util . Log ; |
import java . util . ArrayList ; |
import java . util . List ; |
/** |
* Created by rish on 4/8/17. |
*/ |
public class WiFiConnector implements WiFiBroadcastReceiver . WiFiBroadcastListener |
private static final String TAG = WiFiConnector . class . getSimpleName (); |
public static final String NO_WIFI = quoted ( «» ); |
private Context mContext ; |
private boolean mIsWifiBroadcastRegistered ; |
private IntentFilter mWifiIntentFilter ; |
private WifiManager mWifiManager ; |
private WiFiBroadcastReceiver mWiFiBroadcastReceiver ; |
private WiFiConnectorListener mWifiConnectorListener ; |
public WiFiConnector ( Context context , WiFiConnectorListener wifiConnectorListener ) |
mContext = context ; |
mWifiIntentFilter = new IntentFilter (); |
mWifiIntentFilter . addAction ( WifiManager . NETWORK_STATE_CHANGED_ACTION ); |
mWifiIntentFilter . addAction ( WifiManager . RSSI_CHANGED_ACTION ); |
mWifiIntentFilter . addAction ( WifiManager . RSSI_CHANGED_ACTION ); |
mWifiIntentFilter . addAction ( WifiManager . SCAN_RESULTS_AVAILABLE_ACTION ); |
mWifiManager = ( WifiManager ) context . getSystemService ( Context . WIFI_SERVICE ); |
if ( mWiFiBroadcastReceiver == null ) |
this . mWiFiBroadcastReceiver = new WiFiBroadcastReceiver (); |
mWiFiBroadcastReceiver . setOnWiFiBroadcastListener ( this ); |
mWifiConnectorListener = wifiConnectorListener ; |
> |
public NetworkInfo . DetailedState connectToWiFi ( int securityType , String ssid , String key ) |
Log . d ( TAG , «connectToWiFi() called with: securityType = [» + securityType + «], ssid = [» + ssid + «], key = [» + key + «]» ); |
/* Check if already connected to that wifi */ |
String currentSsid = getActiveConnection (). getSSID (); |
Log . d ( TAG , «Current Ssid » + currentSsid ); |
NetworkInfo . DetailedState currentState = WifiInfo . getDetailedStateOf ( getActiveConnection (). getSupplicantState ()); //todo check this |
if ( currentState == NetworkInfo . DetailedState . CONNECTED && currentSsid . equals ( quoted ( ssid ))) |
Log . d ( TAG , «Already connected» ); |
mWifiConnectorListener . onWiFiStateUpdate ( getActiveConnection (), NetworkInfo . DetailedState . CONNECTED ); |
return NetworkInfo . DetailedState . CONNECTED ; |
> |
int highestPriorityNumber = 0 ; |
WifiConfiguration selectedConfig = null ; |
/* Check if not connected but has connected to that wifi in the past */ |
for ( WifiConfiguration config : mWifiManager . getConfiguredNetworks ()) |
if ( config . priority > highestPriorityNumber ) highestPriorityNumber = config . priority ; |
if ( config . SSID . equals ( quoted ( ssid )) && config . allowedKeyManagement . get ( securityType )) |
Log . d ( TAG , «Saved preshared key is » + config . preSharedKey ); |
if ( securityType == WifiConfiguration . KeyMgmt . WPA_PSK |
&& config . preSharedKey != null && config . preSharedKey . equals ( key )) |
selectedConfig = config ; |
else if ( securityType == WifiConfiguration . KeyMgmt . NONE ) |
selectedConfig = config ; |
> |
> |
if ( selectedConfig != null ) |
selectedConfig . priority = highestPriorityNumber + 1 ; |
mWifiManager . updateNetwork ( selectedConfig ); |
// mWifiManager.disconnect(); /* disconnect from whichever wifi you’re connected to */ |
mWifiManager . enableNetwork ( selectedConfig . networkId , true ); |
mWifiManager . reconnect (); |
Log . d ( TAG , «Connection exists in past, enabling and connecting priority = » + highestPriorityNumber ); |
return NetworkInfo . DetailedState . CONNECTING ; |
> |
/* Make new connection */ |
WifiConfiguration config = new WifiConfiguration (); |
config . SSID = quoted ( ssid ); |
config . priority = highestPriorityNumber + 1 ; |
config . status = WifiConfiguration . Status . ENABLED ; |
if ( securityType == WifiConfiguration . KeyMgmt . WPA_PSK ) |
config . preSharedKey = quoted ( key ); |
config . allowedKeyManagement . set ( WifiConfiguration . KeyMgmt . WPA_PSK ); |
config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . TKIP ); |
config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . CCMP ); |
config . allowedPairwiseCiphers . set ( WifiConfiguration . PairwiseCipher . TKIP ); |
config . allowedPairwiseCiphers . set ( WifiConfiguration . PairwiseCipher . CCMP ); |
config . allowedProtocols . set ( WifiConfiguration . Protocol . RSN ); |
config . allowedProtocols . set ( WifiConfiguration . Protocol . WPA ); |
> else |
config . allowedKeyManagement . set ( WifiConfiguration . KeyMgmt . NONE ); |
> |
Log . d ( TAG , «Attempting new wifi connection, setting priority number to, connecting » + config . priority ); |
int netId = mWifiManager . addNetwork ( config ); |
// mWifiManager.disconnect(); /* disconnect from whichever wifi you’re connected to */ |
mWifiManager . enableNetwork ( netId , true ); |
mWifiManager . reconnect (); // todo? |
return NetworkInfo . DetailedState . CONNECTING ; |
> |
@ CheckResult |
public boolean startScan () |
return mWifiManager . startScan (); |
> |
public WifiInfo getActiveConnection () |
WifiInfo currentInfo = mWifiManager . getConnectionInfo (); |
return currentInfo ; |
> |
@ Override |
public void onStateUpdate ( NetworkInfo . DetailedState detailedState ) |
mWifiConnectorListener . onWiFiStateUpdate ( getActiveConnection (), detailedState ); |
> |
@ Override |
public void onRssiChanged ( int rssi ) |
mWifiConnectorListener . onWiFiRssiChanged ( rssi ); |
> |
@ Override |
public void onScanResultsAvailable () |
List < ScanResult >scanResults = mWifiManager . getScanResults (); |
ArrayList < BriefWiFiInfo >wiFiList = new ArrayList <>(); |
for ( ScanResult scanResult : scanResults ) |
BriefWiFiInfo briefWiFiInfo = new BriefWiFiInfo (); |
briefWiFiInfo . setSsid ( scanResult . SSID ); |
int rssiPercentage = WifiManager . calculateSignalLevel ( scanResult . level , 100 ); |
briefWiFiInfo . setRssi ( rssiPercentage ); |
wiFiList . add ( briefWiFiInfo ); |
> |
mWifiConnectorListener . onWiFiScanResults ( wiFiList ); |
> |
public void setup () |
registerReceiver ( mContext ); |
> |
public void destroy () |
unregisterReceiver (); |
> |
private void registerReceiver ( Context context ) |
context . getApplicationContext (). registerReceiver ( mWiFiBroadcastReceiver , mWifiIntentFilter ); |
mIsWifiBroadcastRegistered = true ; |
> |
private void unregisterReceiver () |
if ( mContext != null && mWiFiBroadcastReceiver != null && mIsWifiBroadcastRegistered ) |
try |
mContext |
. getApplicationContext () |
. unregisterReceiver ( mWiFiBroadcastReceiver ); |
mIsWifiBroadcastRegistered = false ; |
> catch ( IllegalArgumentException e ) |
Log . d ( TAG , «Unable to unregister receiver» ); |
> |
> |
> |
public static String quoted ( String s ) |
return » \» » + s + » \» » ; |
> |
public interface WiFiConnectorListener |
void onWiFiStateUpdate ( WifiInfo wifiInfo , NetworkInfo . DetailedState detailedState ); |
void onWiFiRssiChanged ( int rssi ); |
/** |
* list contains SSID and RSSI only |
*/ |
void onWiFiScanResults ( ArrayList < BriefWiFiInfo >wiFiList ); |
> |
> |
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Android Wifi connection sdk
japrogbogdan/wifi-connect
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Android Wifi Connect library
Steps to add sdk to your project:
Step 1: Copy/paste sdk-release.aar file to your dependencies directory (Let’s say ‘libs’):
Step 2: Add sdk aar as dependency:
Step 3. (Optional) Add source of sdk:
In code click on one of sdk’s reference classes
From toolbar press ‘Navigate’ -> ‘Declaration or Usage’
On toolbar of opened class press ‘Choose sources. ‘ button
Inside popup select ‘libs/sdk-sources.jar’. This file is inside .aar file
Step1. Check On WiFiModule
/** * Сheck if Wi-Fi is enabled */ fun isWifiEnabled(context: Context): Boolean
Step 2. Create wifi session instance:
private var wifi: WifiSession? = null
/** * Create new session instance */ private fun createSession() < val apiKey: String = "YOUR_API_KEY" val userId: String = "USER_ID" val apiDomain: String = "API_DOMAIN" //identifier for domain name server of the API SmartWiFi val channelId: Int = 1 //your channel id val projectId: Int = 1 //your project id val triggerSuccessTracking: Boolean = true //internally trigger success tracking url by sdk val contextReference: Context = this@MainActivity //Holds activity reference to call activity.startActivityForResult(Intent, Int) function when needed. //Will clear reference when session canceled. //This is required if contextReference is not activity reference. val activityHelper: ActivityHelper = ActivityHelperDelegate(activity = this@MainActivity) wifi = WifiSession.Builder(context = contextReference) .apiKey(apiKey) .userId(userId) .apiDomain(apiDomain) .channelId(channelId) .projectId(projectId) .autoDeliverSuccessCallback(triggerSuccessTracking) .activityHelper(activityHelper) .statusCallback(object : WifiSessionCallback < override fun onStatusChanged(newStatus: WiFiSessionStatus) < when(newStatus)< WiFiSessionStatus.RequestConfigs -> < >WiFiSessionStatus.ReceivedConfigs -> < >is WiFiSessionStatus.RequestConfigsError -> < val reason = newStatus.reason.message >is WiFiSessionStatus.CreateWifiConfigError -> < val reason = newStatus.reason.message >WiFiSessionStatus.Connecting -> < >WiFiSessionStatus.Success -> < >is WiFiSessionStatus.ConnectionByLinkSend -> < val link = newStatus.url >is WiFiSessionStatus.ConnectionByLinkSuccess -> < val response = newStatus.response >is WiFiSessionStatus.ConnectionByLinkError -> < val reason = newStatus.reason.message >is WiFiSessionStatus.NotFoundWiFiPoint -> < val ssid = newStatus.ssid >is WiFiSessionStatus.Error -> < //check the reason newStatus.reason.printStackTrace() >WiFiSessionStatus.CancelSession -> <> > > >) .create() >
Step 3. Request permissions result for wifi scan:
/** * Permissions result sent from activity into wifi session instance */ override fun onRequestPermissionsResult( requestCode: Int, permissions: Array, grantResults: IntArray )
Step 4. Request config and save to cache:
/** * Get config if session instance present */ private fun getSessionConfig()
Step 5. Start wifi session (connect to wifi from cached config ):
/** * Start session if session instance present */ private fun startSession()
Step 6. Clean session reference when navigate to other context (activity, fragment):
/** * Cancel session when leaving current context(activity, fragment) * and clean reference to prevent leaks */ private fun stopSession() < wifi?.let < it.cancelSession() wifi = null >>
## License ```Copyright 2021 Oleksii Bolshakov Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
About
Android Wifi connection sdk