Last active
November 13, 2024 12:01
-
-
Save cp-radhika-s/74d2eb717bad62f39d28a8727708af9c to your computer and use it in GitHub Desktop.
Android - Connecting your app to a Wi-Fi connection which might not have internet
This file contains hidden or 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
public class MainActivity extends AppCompatActivity implements WifiChangeBroadcastReceiver.WifiChangeBroadcastListener { | |
private WifiManager wifiManager; | |
private ConnectivityManager connectivityManager; | |
private WifiChangeBroadcastReceiver wifiStateChangeReceiver; | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); | |
connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); | |
} | |
@Override | |
protected void onStart() { | |
super.onStart(); | |
wifiStateChangeReceiver = new WifiChangeBroadcastReceiver(this); | |
registerReceiver(wifiStateChangeReceiver, | |
new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)); | |
connectToAp(); | |
} | |
@Override | |
protected void onStop() { | |
super.onStop(); | |
unregisterReceiver(wifiStateChangeReceiver); | |
} | |
public static WifiConfiguration buildWifiConfig() { | |
WifiConfiguration config = new WifiConfiguration(); | |
config.SSID = "\"networkSSID\""; | |
config.wepKeys[0] = "\"networkPassword\""; | |
// have to set a very high number in order to ensure that | |
// Android doesn't immediately drop this connection and reconnect to //the a different AP. | |
config.priority = 999999; | |
return config; | |
} | |
public void connectToAp() { | |
WifiConfiguration wifiConfig = buildWifiConfig(); | |
String targetNetworkSSID = wifiConfig.SSID; | |
//Check we already connected to specific wifi | |
WifiInfo currentConnectionInfo = wifiManager.getConnectionInfo(); | |
if (currentConnectionInfo.getSSID().equals(targetNetworkSSID)) { | |
// we're already connected to this AP, nothing to do. | |
} else { | |
//If network is configured we can obtain the network ID from the WifiConfiguration object. | |
int networkId = getIdForConfiguredNetwork("networkSSID"); | |
if (networkId == -1) { | |
// Add network to configured network list. | |
networkId = wifiManager.addNetwork(wifiConfig); | |
} | |
// after enableNetwork call we will receive network broadcast. | |
wifiManager.enableNetwork(networkId, true); | |
} | |
} | |
@Override | |
public void onWifiChangeBroadcastReceived(Context context, Intent intent) { | |
WifiConfiguration wifiConfig = buildWifiConfig(); | |
WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); | |
if (wifiInfo == null || wifiInfo.getSSID() == null) { | |
// no WifiInfo or SSID means we're not interested. | |
return; | |
} | |
String newlyConnectedSSID = wifiInfo.getSSID(); | |
if (newlyConnectedSSID.equals(wifiConfig.SSID)) { | |
bindProcessToNetwork(); | |
} | |
} | |
public int getIdForConfiguredNetwork(String ssid) { | |
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks(); | |
for (WifiConfiguration configNetwork : configuredNetworks) { | |
if (configNetwork.SSID.equals(ssid)) { | |
return configNetwork.networkId; | |
} | |
} | |
return -1; | |
} | |
public void bindProcessToNetwork() { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { | |
Network network = getNetworkObjectForCurrentWifiConnection(); | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |
connectivityManager.bindProcessToNetwork(network); | |
} else { | |
ConnectivityManager.setProcessDefaultNetwork(network); | |
} | |
} | |
} | |
@Nullable | |
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) | |
public Network getNetworkObjectForCurrentWifiConnection() { | |
List<Network> networks = Arrays.asList(connectivityManager.getAllNetworks()); | |
for (Network network : networks) { | |
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network); | |
if (capabilities.hasTransport | |
(NetworkCapabilities.TRANSPORT_WIFI)) { | |
return network; | |
} | |
} | |
return null; | |
} | |
} |
This file contains hidden or 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
public class WifiChangeBroadcastReceiver extends BroadcastReceiver { | |
private final WifiChangeBroadcastListener listener; | |
public WifiChangeBroadcastReceiver(WifiChangeBroadcastListener listener) { | |
this.listener = listener; | |
} | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
listener.onWifiChangeBroadcastReceived(context, intent); | |
} | |
public interface WifiChangeBroadcastListener { | |
void onWifiChangeBroadcastReceived(Context context, Intent intent); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Android 10 (API level 29) and higher:
A successful call to WifiManager.startScan() requires all of the following conditions to be met:
If your app is targeting Android 10 (API level 29) SDK or higher, your app has the ACCESS_FINE_LOCATION permission.
If your app is targeting SDK lower than Android 10 (API level 29), your app has the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.
Your app has the CHANGE_WIFI_STATE permission.
Location services are enabled on the device (under Settings > Location).
To successfully call WifiManager.getScanResults(), ensure all of the following conditions are met:
If your app is targeting Android 10 (API level 29) SDK or higher, your app has the ACCESS_FINE_LOCATION permission.
If your app is targeting SDK lower than Android 10 (API level 29), your app has the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.
Your app has the ACCESS_WIFI_STATE permission.
Location services are enabled on the device (under Settings > Location).
If the calling app doesn't meet all of these requirements, the call fails with a SecurityException.