Does any of you have experience with return value of setWifiEnabled()
?
Documentation is unclear, it says:
Returns true if the operation succeeds (or if the existing state is the same as the requested state).
What it does when operation fails? Does it throw exception or return false
?
Is it possible to do something like:
if (!WifiManager.setWifiEnabled(true)) {
Log.i(LOG_TAG, "Wifi switch failed.");
} else {
Log.i(LOG_TAG, "Wifi switch succeeded.")
}
Many thanks.
Have a look at implementation of WifiService#setWifiEnabled(boolean):
/**
* see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
* @param enable {@code true} to enable, {@code false} to disable.
* @return {@code true} if the enable/disable operation was
* started or is already in the queue.
*/
public synchronized boolean setWifiEnabled(boolean enable) {
enforceChangePermission();
Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid());
if (DBG) {
Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
}
if (enable) {
reportStartWorkSource();
}
mWifiStateMachine.setWifiEnabled(enable);
/*
* Caller might not have WRITE_SECURE_SETTINGS,
* only CHANGE_WIFI_STATE is enforced
*/
long ident = Binder.clearCallingIdentity();
try {
handleWifiToggled(enable);
} finally {
Binder.restoreCallingIdentity(ident);
}
if (enable) {
if (!mIsReceiverRegistered) {
registerForBroadcasts();
mIsReceiverRegistered = true;
}
} else if (mIsReceiverRegistered) {
mContext.unregisterReceiver(mReceiver);
mIsReceiverRegistered = false;
}
return true;
}
So, it never returns false
. If for some reason the desired operation couldn't succeed, then exception will be thrown, see WifiManager.setWifiEnabled(boolean):
/**
* Enable or disable Wi-Fi.
* @param enabled {@code true} to enable, {@code false} to disable.
* @return {@code true} if the operation succeeds (or if the existing state
* is the same as the requested state).
*/
public boolean setWifiEnabled(boolean enabled) {
try {
return mService.setWifiEnabled(enabled);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}