Select WiFi Access point in Android? - android

I am developing one android application which select wifi access point from list of wifi. I used following code..
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = hotSpotSsid;
wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
wifiConfiguration.BSSID = hotSpotBssid;
wifiConfiguration.hiddenSSID = false;
// wifiConfiguration.priority = 1;
// add this to the configured networks
int inetId = wifiManager.addNetwork(wifiConfiguration);
Log.i(TAG,"INetId :"+inetId);
configs = wifiManager.getConfiguredNetworks();
Log.e(TAG,"After adding config :"+configs);
if(inetId < 0) {
Log.i(TAG,"Unable to add network configuration for SSID: "+hotSpotSsid);
return;
}else {
message="\t Successfully added to configured Networks";
Log.i(TAG,message);
}
My problem is i am not able select wifi access point..Every time it shows previous configured wifi details.

Looks like you need to call WifiManager.enableNetwork with disableOthers=true
wifiManager.enableNetwork(inetId, true);

You have to include permissions given below in your manifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE">

Related

WifiManager.disconnect() deprecated in Android Q

In Android Q and above (API >= 29), the WifiManager.disconnect() method has been deprecated.
What would be the solution to disconnect from the Wi-Fi network in Android 10 and above?
I have implemented the next code, yet it fails always returning:
STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID.
I guess the reason for the failure could be that removeNetworkSuggestions maybe is expected to work in conjunction with addNetworkSuggestions, but I don't need to add any networks, on the contrary, to disconnect from the active one.
public final class WifiUtils {
private static final String TAG = "WifiUtils";
public static void disconnect(final Context context) {
// Sanity check
if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
// Without the <Fine location> permission the returned SSID is always: '<unknown ssid>'.
// Note: The <Coarse location> permission is not enough.
Log.e(WifiUtils.TAG, "Missing <ACCESS_FINE_LOCATION> permission. Required to obtain the Wifi SSID.");
return;
}
final WifiManager manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
if (!manager.isWifiEnabled())
return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
final WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo == null) {
Log.w(WifiUtils.TAG, "Failed to get connection details.");
return;
}
final String ssid = wifiInfo.getSSID();
if (TextUtils.isEmpty(ssid)) {
Log.e(WifiUtils.TAG, "Unable to resolve Wifi SSID.");
} else {
Log.i(WifiUtils.TAG, "Resolved Wifi SSID: " + ssid);
final List<WifiNetworkSuggestion> suggestions = new ArrayList<>();
suggestions.add(new WifiNetworkSuggestion.Builder()
.setSsid(wifiInfo.getSSID())
.build());
final int status = manager.removeNetworkSuggestions(suggestions);
Log.d(WifiUtils.TAG, "Wifi disconnection status result: " + status);
}
} else {
manager.disconnect();
}
}
}
I have the required permissions in the manifest, granted at runtime:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I struggled with this for a while. Best thing to do is have the Android System take care of it with the following intent.
startActivity(new Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY));
This will show a number of WiFi SSIDs around the user's location and they are able to pick one of the WiFis to connect to.

How to update an already created Wi-Fi configuration (or "UID XXX does not have permission to update [Wi-Fi] configuration error")?

I am developing an app which manages the Wi-Fi connections. My scenario is as follows: Let's say, the entire building has a Wi-Fi network named “testing-tls”. My app should be able to connect to only selected access points (based on BSSID or MAC ID). We use TLS authentication mechanism to verify the user (Custom CA Certificates).
I am able to establish a connection through the app, but failing when I try to connect to a different access point (different BSSID). Even though I created the Wi-Fi configuration programmatically, I am unable to update configuration after a first successful connection. I have tested my app in Oreo and Marshmallow. But, I am facing problems in Oreo (Not sure about Nougat). I am beginning to wonder if it is even possible to update the configuration once it is created.
These are the steps I am following:
1) Create a WifiConfiguration object
private WifiConfiguration createWifiConfiguration() {
WifiConfiguration config = new WifiConfiguration();
config.SSID = "\"testing-tls\"";
config.priority = 1;
config.status = WifiConfiguration.Status.ENABLED;
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP;
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
config.enterpriseConfig.setIdentity(identityName);
config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
PKCS12ParseInfo parseInfo;
try {
parseInfo = CertificateUtils.parsePKCS12Certificate(
certificateFilePath, identityPassword);
if (parseInfo != null) {
config.enterpriseConfig.setClientKeyEntry(parseInfo.getPrivateKey(),
parseInfo.getCertificate());
return config;
}
return null;
} catch (KeyStoreException | NoSuchAlgorithmException | IOException |
CertificateException | UnrecoverableKeyException | KeyManagementException e1) {
Timber.e("WifiMonitorService, Fail to parse the input certificate: %s", e1.toString());
Toast.makeText(this, "Error occurred", Toast.LENGTH_SHORT).show();
return null;
}
}
2) Try to establish a connection
private void establishWifiConnection(String result) {
Timber.d("WifiMonitorService, establishing WifiConnection");
WifiConfiguration configuration = createWifiConfiguration();
if (configuration != null) {
// result contains a mac id - 00:45:69:c5:34:f2
configuration.BSSID = result;
int networkId = wifiManager.addNetwork(configuration);
if (networkId == -1) {
networkId = getExistingNetworkId(wifiSsid);
// Add a new configuration to the db
if (networkId == -1) {
Timber.e("Couldn't add network with SSID");
Toast.makeText(this, "Wifi configuration error", Toast.LENGTH_SHORT).show();
return;
}
}
Timber.i("WifiMonitorService, # addNetwork returned: %d", networkId);
wifiManager.saveConfiguration();
wifiManager.enableNetwork(networkId, true);
wifiManager.reassociate();
} else {
Toast.makeText(this, "Wifi conf Error occurred", Toast.LENGTH_SHORT).show();
}
}
3) Get Exiting network id if present
private int getExistingNetworkId(String ssid) {
List<WifiConfiguration> configuredNetworks =
wifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (existingConfig.SSID.equals("\"testing-tls\"")) {
return existingConfig.networkId;
}
}
}
return -1;
}
Manifest Permissions are as follows:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.OVERRIDE_WIFI_CONFIG" />
<uses-permission android:name="android.permission.NETWORK_SETTINGS" />
<uses-feature android:name="android.hardware.wifi" />
<uses-feature android:name="android.hardware.camera" />
<permission
android:name="android.permission.INTERACT_ACROSS_USERS"
android:protectionLevel="signature" />
Error: I always get UID 10189 does not have permission to update configuration error in Oreo
2018-12-28 12:23:44.571 1320-1847/? E/WifiConfigManager: UID 10189 does not have permission to update configuration "testing-tls"WPA_EAP
2018-12-28 12:23:44.571 1320-1847/? I/WifiStateMachine: connectToUserSelectNetwork Allowing uid 10189 with insufficient permissions to connect=1
Investigation
After digging through the source code, I found the implementation of the addOrUpdateNetwork method in WifiConfigManager class.
The implementation addOrUpdateNetwork, in tag android_8.0.0_r21 (Build number OPD1.170816.010) is as follows:
First check if we already have a network with the provided network id or configKey
If no existing network found, validate the configuration, and add.
If existing network found, update the network configuration. Before that, check whether app has necesssary permissions to update the network.
AddOrUpdateNetwork internally calls a function called canModifyNetwork:
/**
* Checks if |uid| has permission to modify the provided configuration.
*
* #param config WifiConfiguration object corresponding to the network to be modified.
* #param uid UID of the app requesting the modification.
* #param ignoreLockdown Ignore the configuration lockdown checks for connection attempts.
*/
private boolean canModifyNetwork(WifiConfiguration config, int uid, boolean ignoreLockdown) {
// Passpoint configurations are generated and managed by PasspointManager. They can be
// added by either PasspointNetworkEvaluator (for auto connection) or Settings app
// (for manual connection), and need to be removed once the connection is completed.
// Since it is "owned" by us, so always allow us to modify them.
if (config.isPasspoint() && uid == Process.WIFI_UID) {
return true;
}
// EAP-SIM/AKA/AKA' network needs framework to update the anonymous identity provided
// by authenticator back to the WifiConfiguration object.
// Since it is "owned" by us, so always allow us to modify them.
if (config.enterpriseConfig != null
&& uid == Process.WIFI_UID
&& TelephonyUtil.isSimEapMethod(config.enterpriseConfig.getEapMethod())) {
return true;
}
final DevicePolicyManagerInternal dpmi = LocalServices.getService(
DevicePolicyManagerInternal.class);
final boolean isUidDeviceOwner = dpmi != null && dpmi.isActiveAdminWithPolicy(uid,
DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
// If |uid| corresponds to the device owner, allow all modifications.
if (isUidDeviceOwner) {
return true;
}
final boolean isCreator = (config.creatorUid == uid);
// Check if the |uid| holds the |NETWORK_SETTINGS| permission if the caller asks us to
// bypass the lockdown checks.
if (ignoreLockdown) {
return mWifiPermissionsUtil.checkNetworkSettingsPermission(uid);
}
// Check if device has DPM capability. If it has and |dpmi| is still null, then we
// treat this case with suspicion and bail out.
if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)
&& dpmi == null) {
Log.w(TAG, "Error retrieving DPMI service.");
return false;
}
// WiFi config lockdown related logic. At this point we know uid is NOT a Device Owner.
final boolean isConfigEligibleForLockdown = dpmi != null && dpmi.isActiveAdminWithPolicy(
config.creatorUid, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
if (!isConfigEligibleForLockdown) {
return isCreator || mWifiPermissionsUtil.checkNetworkSettingsPermission(uid);
}
final ContentResolver resolver = mContext.getContentResolver();
final boolean isLockdownFeatureEnabled = Settings.Global.getInt(resolver,
Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) != 0;
return !isLockdownFeatureEnabled
&& mWifiPermissionsUtil.checkNetworkSettingsPermission(uid);
}
As far I can see, only the following uids have access to modify network configurations.
System app
Device owner
Creator (It is failing for some reason)
I am getting the same behaviour in these two phones.
Pixel 2 (Oreo 8.0.0)
Samsung J8 (Oreo 8.0.0)
Additionally, Samsung J8 always shows this warning:
CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certificate path not found
Question:
How can an already created Wi-Fi configuration be updated programmatically?
Is it even possible to update the Wi-Fi configuration once it is created in the Wi-Fi's internal database?
Is it mandatory to disconnect Wi-Fi before updating or enabling the configuration?
After digging the source code, finally got answers to my questions.
Question: Is it possible to update the configurations once it is created?
Answer: Yes, Android os allows you to update the configuration created from your application. When I called wifiManager.addNetwork(), in the log window the following statements were printed.
2019-01-04 12:23:16.168 1328-3114/? I/addOrUpdateNetwork: uid = 10190 SSID "testing-tls" nid=-1
2019-01-04 12:23:16.169 1328-1851/? V/WifiConfigManager: Adding/Updating network testing-tls
2019-01-04 12:23:16.193 1328-1851/? D/WifiConfigManager: addOrUpdateNetworkInternal: added/updated config. netId=6 configKey="testing-tls"WPA_EAP uid=10190 name=in.ac.iisc.wifimonitoring vendorAP=false hiddenSSID=false autoReconnect=1
2019-01-04 12:23:16.204 1328-1851/? D/WifiConfigStore: Writing to stores completed in 7 ms.
2019-01-04 12:23:16.205 1328-1851/? D/WifiIssueDetector: report htime=2019-01-04_12:23:16 time=1546584796205 rid=105 callBy=in.ac.iisc.wifimonitoring apiName=addOrUpdateNetwork netid=6 callUid=in.ac.iisc.wifimonitoring
2019-01-04 12:23:16.206 15873-15873/in.ac.iisc.wifimonitoring I/WifiMonitorService: WifiMonitorService, #addNetwork returned: 6
Question: what is "UID 10189 does not have permission to update configuration error" in Oreo?
Answer: After updating the configuration, we have to call wifimanager.enableNetwork() method to establish a connection to the desired access point. Workflow of EnableNetwork() is as follows.
WifiManager.enableNetwork() internally calls SyncEnableNetwork() method of WifiStateMachine class.
WifiStateMachine is the core class which tracks the state of Wifi connectivity. All event handling and all changes in connectivity state are initiated in this class.
SyncEnableNetwork() method sends CMD_ENABLE_NETWORK message to ConnectModeState class.
If disableOthers is true, call connectToUserSelectNetwork() method and passes networkId, calling UID and force reconnect [always false - hardcoded value] as arguments.
If an app does not have all the necessary permissions to update the configuration [uses checkAndUpdateLastUid() method in WifiConfigManager class - returns true only for system settings/sysui app] or if enabling of a network is failed, the following statements will be printed.
2018-12-28 12:23:44.571 1320-1847/? E/WifiConfigManager: UID 10189 does not have permission to update configuration "testing-tls"WPA_EAP
2018-12-28 12:23:44.571 1320-1847/? I/WifiStateMachine: connectToUserSelectNetwork Allowing uid 10189 with insufficient permissions to connect=1
Note: checkAndUpdateLastUid() method has been renamed to updateLastConnectUid() in Android Pie. They have slightly modified its functionality as well.
For more information, please refer to the below diagram [I am no good in drawing flowcharts. Please bear with me or suggest if any changes required].
Question 3: Is it mandatory to disconnect wifi before updating or enabling the configuration?
Answer: OS triggers a connection/reconnection to a network under the following conditions:
Selected network id must be different from currently connected network id.
If forceReconnect argument is true, Android prepares for reconnection [True only for system settings/sysui app].
Since developer apps do not have the ability to a force connection, we should disconnect the wifi in order to connect/reconnect to the network after updating the configuration.
Hope this will help others.

How to programmatically change password of a saved wifi network in Android (API level 23, Android 6.0)

Premise:
I'm currently work on an Android App (API level 23, Android 6.0) that connect with a device via Wi-Fi and uses UDP packets to communicate. I'm able to change the device Wi-Fi password using a particular command. This works fine.
Target:
What I'm tring to programmatically do is:
search Wi-Fi generated from the device
connect to the device
send the command to change the password
reconnect to the device using the new password
I'm able to connect the first time (steps 1,2,3) using code like this:
private void connect(String ssid, String password) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = String.format("\"%s\"", ssid);
conf.preSharedKey = String.format("\"%s\"", password);
netId = mWifiManager.addNetwork(conf);
mWifiManager.saveConfiguration();
mWifiManager.disconnect();
mWifiManager.enableNetwork(netId, true);
mWifiManager.reconnect();
}
Additional info:
In the Manifest file I declared these permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
The problem:
If I try to use the same method to connect after the change of the password, I'm not able to achive the connection because (I think) Android remembers the previous password.
If I try to use updateNetwork(conf) instead of addNetwork(conf), I don't notice any difference.
I've tried to remove or disable in some ways the saved network before try to connect again, but unsaccesfully.
mWifiManager.removeNetwork(netId)
returns false (I have no idea why it fails)
mWifiManager.disableNetwork(netId);
returns true but it appears to have no effects
If I use the Android settings to change password, all works fine... but I want to change the saved password programmatically.
Any help is very appreciated
After several attempts, I currently have no problems following the instructions I report below.
Before connecting to a Wi-Fi network it is important to check the list of previously saved networks. If there is no network with the same SSID it is possible to create a new configuration, otherwise it is necessary to modify the existing one.
public void connect(String ssid, String password) {
WifiConfiguration wifiConf = null;
WifiConfiguration savedConf = null;
//existing configured networks
List<WifiConfiguration> list = mWifiManager.getConfiguredNetworks();
if(list!=null) {
for( WifiConfiguration i : list ) {
if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
Log.d(TAG, "existing network found: " + i.networkId + " " + i.SSID);
savedConf = i;
break;
}
}
}
if(savedConf!=null) {
Log.d(TAG, "coping existing configuration");
wifiConf = savedConf;
} else {
Log.d(TAG, "creating new configuration");
wifiConf = new WifiConfiguration();
}
wifiConf.SSID = String.format("\"%s\"", ssid);
wifiConf.preSharedKey = String.format("\"%s\"", password);
int netId;
if(savedConf!=null) {
netId = mWifiManager.updateNetwork(wifiConf);
Log.d(TAG, "configuration updated " + netId);
} else {
netId = mWifiManager.addNetwork(wifiConf);
Log.d(TAG, "configuration created " + netId);
}
mWifiManager.saveConfiguration();
mWifiManager.disconnect();
mWifiManager.enableNetwork(netId, true);
mWifiManager.reconnect();
}
Android after version 6 does not allow any application to modify Wi-Fi networks unless it has been created by the application itself. In addition, it does not allow adding Wi-Fi networks with the same name as others already configured previously. This is very curious because when you configure Wi-Fi networks manually from the settings, it does allow it.
After thinking for a long time about a possible solution it occurred to me that perhaps the Wifi network could be added with another name and once added, change it to the desired name. I have tried it and it works. It would be something like the following:
int networkId = -1;
// Find my Wifi
List<WifiConfiguration> configuredWifis = wifiManager.getConfiguredNetworks();
for(WifiConfiguration wifi : configuredWifis)
{
if(wifi.SSID != null && wifi.SSID.equals("\"" + WIFI_SSID + "\"") && wifi.priority == WIFI_PRIORITY)
{
networkId = wifi.networkId;
}
else
{
wifiManager.disableNetwork(wifi.networkId);
wifiManager.removeNetwork(wifi.networkId); // After android 6 it really does not remove the Wifi network
wifiManager.saveConfiguration();
}
}
if(networkId == -1)
{
// If my Wifi is not yet configured then add it
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + WIFI_SSID + "\"";
conf.preSharedKey = "\""+ WIFI_PASSW +"\"";
conf.priority = WIFI_PRIORITY;
networkId = wifiManager.addNetwork(conf);
if(networkId == -1) // This ocurs when a wifi with the same name is yet configured. After Android 6 is not possible modify it.
{
Random random = new Random(System.currentTimeMillis());
int randomInteger = random.nextInt(10000);
conf.SSID = "\"" + WIFI_SSID + randomInteger + "\"";
networkId = wifiManager.addNetwork(conf); // Add my wifi with another name
conf.SSID = "\"" + WIFI_SSID + "\"";
conf.networkId = networkId;
networkId = wifiManager.updateNetwork(conf); // After my wifi is added with another name, I change it to the desired name
}
}
// Connect to my wifi
if(wifiManager.getConnectionInfo().getNetworkId() != networkId)
{
wifiManager.disconnect();
wifiManager.enableNetwork(networkId, true);
wifiManager.reconnect();
}

How to create wifi tethering Hotspot in Android Marshmallow?

I've tried to create a Wi-Fi tethering hotspot in Android Marshmallow using the following code.
public class WifiAccessManager {
private static final String SSID = "1234567890abcdef";
public static boolean setWifiApState(Context context, boolean enabled) {
//config = Preconditions.checkNotNull(config);
try {
WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (enabled) {
mWifiManager.setWifiEnabled(false);
}
WifiConfiguration conf = getWifiApConfiguration();
mWifiManager.addNetwork(conf);
return (Boolean) mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class).invoke(mWifiManager, conf, enabled);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static WifiConfiguration getWifiApConfiguration() {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = SSID;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
return conf;
}
}
But it shows the following permission problem:
java.lang.SecurityException: googleplus.tarun.info.hotspotcreation was not granted either of these permissions: android.permission.CHANGE_NETWORK_STATE, android.permission.WRITE_SETTINGS.
Even though I have already added those on the manifest.
How can I solve the problem?
I was working in Android Marshmallow and have found a way to create WiFi tethering as describe below. Note that according to Android 6.0 Changes Your apps can now change the state of WifiConfiguration objects only if you created these objects. And beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. Read this article to know more about this. I can see you are creating Hotspot by your own. So no issue. The permission in Manifest is given below:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
I am using the following function to create WiFi tethering Hotspot in android marshmallow:
public void setWifiTetheringEnabled(boolean enable) {
//Log.d(TAG,"setWifiTetheringEnabled: "+enable);
String SSID=getHotspotName(); // my function is to get a predefined SSID
String PASS=getHotspotPassword(); // my function is to get a predefined a Password
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
if(enable){
wifiManager.setWifiEnabled(!enable); // Disable all existing WiFi Network
}else {
if(!wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(!enable);
}
Method[] methods = wifiManager.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals("setWifiApEnabled")) {
WifiConfiguration netConfig = new WifiConfiguration();
if(!SSID.isEmpty() || !PASS.isEmpty()){
netConfig.SSID=SSID;
netConfig.preSharedKey = PASS;
netConfig.hiddenSSID = false;
netConfig.status = WifiConfiguration.Status.ENABLED;
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
try {
method.invoke(wifiManager, netConfig, enable);
Log.e(TAG,"set hotspot enable method");
} catch (Exception ex) {
}
break;
}
}
}
Enabling the Hotspot the function call is: setWifiTetheringEnabled(true) and for disable setWifiTetheringEnabled(false).
That's it.
N.B. Be noted that SIM less devices are not supported to use Hotspot. You will not be able to create the Hotspot on those devices without root.
Hope this will be helpful for upcoming visitors.

Connect to wifi network in android, return if incorrect password

I would like to make an application that will let the user connect to a wifi network, however I am having trouble getting a connection to a network
My current code is:
WifiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
wifi.setWifiEnabled(true);
WifiConfiguration wc = new WifiConfiguration();
wifi.startScan();
List<ScanResult> l=wifi.getScanResults();
wc.SSID = l.get(NUMBER).SSID;
post(wc.SSID);
/*This is the bit that I think is failing, my network does not have these properties.. but I can't see how to get them from the Scan Result*/
wc.preSharedKey = "\"passw0rd123\"";
wc.hiddenSSID = false;
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int res = wifi.addNetwork(wc);
post("add Network returned " + res);
boolean b = wifi.enableNetwork(res, true);
post("enableNetwork returned " + b);
I think this has to do with the settings (after my comment) that are not the same as my networks configuration, but I don't know how to get these settings from the ScanResult..
EDIT:
I would also like to know if the it has connected properly.
make sure you set the correct permissions in the AndroidManifest.xml file
Check whether WIFI is enabled or not in ur device and remeber in emulator u cant check it
If WIFI is disabled in onclick of the alert u can show the Wifi- settings page like this
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if ((wifi.isWifiEnabled() == true)) {
Toast.makeText(RegisterActivity.this,"MOBILE Is Connected TO WI-FI!",
}
else {
AlertDialog.Builder WIFIOFF = new Builder(MyTestglobe.this);
WIFIOFF.setCancelable(false);
WIFIOFF.setTitle("Connection Error");
WIFIOFF.setMessage(" Please Enable Your WIFI/INTERNET !");
WIFIOFF.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
startActivity(new Intent( Settings.ACTION_WIFI_SETTINGS));
}
});
WIFIOFF.show();
}
And give these permisions in ur Manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

Categories

Resources