How to create wifihotspot in Oreo programmatically? - android

Hello Given link question is just showing how to turn on/off wifi hotspot but i want to add create wifi hotspot with SSID and password.
I written code for creating wifihotspot(in both NONE and WPA2 PSK) in android and its working fine upto android 7 but in oreo it returning me false value.The summary of my code is-
private WifiManager wifiManager;
private Method method;
private WifiConfiguration config;
config.SSID = ssid;
config.status = WifiConfiguration.Status.ENABLED;
method = wifiManager.getClass().getMethod("setWifiApEnabled",
WifiConfiguration.class, Boolean.TYPE);
boolean status = (Boolean) method.invoke(wifiManager, config, true);
So my question is how to create wifihotspot in both NONE and WPA2 PSK format for android oreo? Is it possible?

Oreo doesnot support to create hotspot programmatically with no password. It always creates hotspot with unique ssid and key generated randomly.
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiManager.LocalOnlyHotspotReservation mReservation;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
assert manager != null;
manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
#SuppressLint("SetTextI18n")
#Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
Timber.d("Wifi Hotspot is on now , reservation is : %s", reservation.toString());
mReservation = reservation;
key = mReservation.getWifiConfiguration().preSharedKey;
ussid = mReservation.getWifiConfiguration().SSID;
}
#Override
public void onStopped() {
super.onStopped();
Timber.d("onStopped: ");
}
#Override
public void onFailed(int reason) {
super.onFailed(reason);
Timber.d("onFailed: ");
}
}, new Handler());
}

thanks, bro finally I found the solution on your answer,
first adding this (enable the modify setting)
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.getPackageName()));
startActivity(intent);
After pasting your code
then adding permissions in manifast
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
location mainly needs
<uses-feature android:name="android.hardware.wifi" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

The setWifiApEnabled will be deprecated. Looking at the source code, it always returns false :
/**
* This call will be deprecated and removed in an upcoming release. It is no longer used to
* start WiFi Tethering. Please use {#link ConnectivityManager#startTethering(int, boolean,
* ConnectivityManager#OnStartTetheringCallback)} if
* the caller has proper permissions. Callers can also use the LocalOnlyHotspot feature for a
* hotspot capable of communicating with co-located devices {#link
* WifiManager#startLocalOnlyHotspot(LocalOnlyHotspotCallback)}.
*
* #param wifiConfig SSID, security and channel details as
* part of WifiConfiguration
* #return {#code false}
*
* #hide
*/
#SystemApi
#RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
String packageName = mContext.getOpPackageName();
Log.w(TAG, packageName + " attempted call to setWifiApEnabled: enabled = " + enabled);
return false;
}
You can try using ConnectivityManager#startTethering(int, boolean, ConnectivityManager#OnStartTetheringCallback) as said in the javadoc. I personnally never tried it.

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 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.

Android Lollipop - WiFi Hotspot setWifiApEnabled() get InvocationTargetException

I'm using in the app
setWifiApEnabled()
from Hidden API (access by reflection). In some older phone it´s working (also with Samsung Galaxy S3, some phones with 4.4,...) but I tested it with Samsung Galaxy S5 and I get
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
...
I'm using similar code like there Android 2.2 wifi hotspot API or How and what to set to Android WifiConfiguration.preSharedKey to connect to the WPA2 PSK WiFi network but It´s a little old code.
Do you have experience with it? What do you suggest?
P.S. it's not working also in some Android 4.4 devices (but I don't get InvocationTargetException).
Try This.
ConnectivityManager cman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Method[] methods = cman.getClass().getMethods();
try
{
wifiManager.setWifiEnabled(false);
Method enableWifi = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
String ssid = " " //your SSID
String pass = " " // your Password
WifiConfiguration myConfig = new WifiConfiguration();
myConfig.SSID = ssid;
myConfig.preSharedKey = pass ;
myConfig.status = WifiConfiguration.Status.ENABLED;
myConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
myConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
myConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
myConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
myConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
myConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
myConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
result = (Boolean) enableWifi.invoke(wifiManager, myConfig, true);
}
catch (Exception e)
{
e.printStackTrace();
result = false;
}
In case of your exception try add this permission to your Manifest
android.permission.WRITE_SETTINGS
You need to add these permissions to your AndroidManifest.xml:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
It works for me.
I had the same problem.
Added android.permission.WRITE_SETTINGS to the manifest file and it worked. Try this.
public void setWiFiApMode(boolean mode) {
if (mContext == null) return;
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
if (wifiManager == null) return;
try {
Method setWifiApEnabled = WifiManager.class.getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
setWifiApEnabled.invoke(wifiManager, null, mode);
} catch (Exception e) {
}
}
and
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Fully works on Android N.
I found the cause:
Caused by: java.lang.SecurityException: ConnectivityService: Neither user 10260 nor current process has android.permission.CONNECTIVITY_INTERNAL.
Info:
How can system app located in /system/app have system permission in Android 4.4 KitKat build?
It´s a little big problem :)

Select WiFi Access point in 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">

Categories

Resources