INSTALL_NON_MARKET_APPS alternative? - android

I need to check if the option "Install apps from unknown sources" is enabled or disabled. However, INSTALL_NON_MARKET_APPS was deprecated in API 17. Is there a new alternative to check this? This is the old way of checking:
boolean canInstallFromOtherSources = Settings.Secure.getInt(Settings.Secure.INSTALL_NON_MARKET_APPS) == 1;
Edit:
boolean unknownSource = false;
if (Build.VERSION.SDK_INT < 17) {
unknownSource = Settings.Secure.getInt(null, Settings.Secure.INSTALL_NON_MARKET_APPS, 0) == 1;
} else {
unknownSource = Settings.Global.getInt(null, Settings.Global.INSTALL_NON_MARKET_APPS, 0) == 1;
}

As the documentation for Settings.Secure.INSTALL_NON_MARKET_APPS points out, the replacement is Settings.Global.INSTALL_NON_MARKET_APPS.

Settings.Secure.INSTALL_NON_MARKET_APPS is deprecated in API 17 thus if you have minimalSDK set lower than 17, it is not directly reachable and reflection has to be used.
My solution:
public class BackwardCompatibility {
private static Class<?> settingsGlobal;
/**
* Returns Settings.Global class for reflective calls.
* Global is a nested class of the Settings, has to be done in a special way.
*
* #return
*/
public static Class<?> getSettingsGlobal(){
if (settingsGlobal!=null){
return settingsGlobal;
}
try {
Class<?> master = Class.forName("android.provider.Settings");
Class<?>[] classes = master.getClasses();
for(Class<?> cls : classes){
if (cls==null) {
continue;
}
if ("android.provider.Settings$Global".equals(cls.getName())){
settingsGlobal = cls;
return settingsGlobal;
}
}
return null;
} catch(Exception ex){
Log.e(TAG, "Reflective call not successfull", ex);
}
return null;
}
/**
* Determines whether installing Android apks from unknown sources is allowed.
*
* #param ctxt
* #return
*/
public static boolean isUnknownSourceInstallAllowed(Context ctxt){
try {
boolean unknownSource = false;
if (Build.VERSION.SDK_INT < 17) {
unknownSource = Settings.Secure.getInt(ctxt.getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS, 0) == 1;
} else {
// Has to use reflection since API 17 is not directly reachable.
// Original call would be:
// unknownSource = Settings.Global.getInt(ctxt.getContentResolver(), Settings.Global.INSTALL_NON_MARKET_APPS, 0) == 1;
//
Class<?> c = getSettingsGlobal();
Method m = c.getMethod("getInt", new Class[] { ContentResolver.class, String.class, int.class });
// Obtain constant value
Field f = c.getField("INSTALL_NON_MARKET_APPS");
final String constVal = (String) f.get(null);
unknownSource = Integer.valueOf(1).equals((Integer) m.invoke(null, ctxt.getContentResolver(), constVal, 0));
}
return unknownSource;
} catch(Exception e){
// Handle this as you like.
Log.w(TAG, "Cannot determine if installing from unknown sources is allowed", e);
}
return false;
}
}

Related

PackageManager check of isEphemeralDisabled causes a deadlock on Android 7.1

private boolean isEphemeralAllowed(
Intent intent, List<ResolveInfo> resolvedActivities, int userId,
boolean skipPackageCheck) {
// Short circuit and return early if possible.
if (isEphemeralDisabled()) {
return false;
}
final int callingUser = UserHandle.getCallingUserId();
if (callingUser != UserHandle.USER_SYSTEM) {
return false;
}
if (mEphemeralResolverConnection == null) {
return false;
}
if (intent.getComponent() != null) {
return false;
}
if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
return false;
}
if (!skipPackageCheck && intent.getPackage() != null) {
return false;
}
final boolean isWebUri = hasWebURI(intent);
private boolean isEphemeralDisabled() {
// ephemeral apps have been disabled across the board
if (DISABLE_EPHEMERAL_APPS) {
return true;
}
// system isn't up yet; can't read settings, so, assume no ephemeral apps
if (!mSystemReady) {
return true;
}
// we can't get a content resolver until the system is ready; these checks must happen last
final ContentResolver resolver = mContext.getContentResolver();
if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
return true;
}
return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
}
For Android 7.0, DISABLE_EPHEMERAL_APPS default is true
private static final boolean DISABLE_EPHEMERAL_APPS = true;
But in Android 7.1, Google enabled Instant apps support: https://android.googlesource.com/platform/frameworks/base.git/+/7ef97b6624054fff0d712d85336a45eee70bcc3f%5E%21/#F0
for isEphemeralAllowed method, if call resolveIntent, most of intents will call isEphemeralAllowed method, so this will cause PackageManager service user binder call settingProvider, and will probability cause a deadlock.

Detect if 'High contrast' is enabled in Android accessibility settings

How can I detect if 'High Contrast' setting (available on Android 5.0+) is enabled in Accessibility settings?
In the AccessibilityManager class (see source here) you have a public method called isHighTextContrastEnabled that you can use to get your information:
/**
* Returns if the high text contrast in the system is enabled.
* <p>
* <strong>Note:</strong> You need to query this only if you application is
* doing its own rendering and does not rely on the platform rendering pipeline.
* </p>
*
* #return True if high text contrast is enabled, false otherwise.
*
* #hide
*/
public boolean isHighTextContrastEnabled() {
synchronized (mLock) {
IAccessibilityManager service = getServiceLocked();
if (service == null) {
return false;
}
return mIsHighTextContrastEnabled;
}
}
So in your code, you can access this method by doing so (if you're in an Activity):
AccessibilityManager am = (AccessibilityManager) this.getSystemService(Context.ACCESSIBILITY_SERVICE);
boolean isHighTextContrastEnabled = am.isHighTextContrastEnabled();
#alxscms' answer may be right but it does not help me So I found an alternative way to check High contrast text is Enabled or not in android.
Below function will return true if HighContrastText is enabled in user phone and otherwise return false.
Below function is checked in all android phones and it's working.
public static boolean isHighContrastTextEnabled(Context context) {
if (context != null) {
AccessibilityManager am = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
Method m = null;
if (am != null) {
try {
m = am.getClass().getMethod("isHighTextContrastEnabled", null);
} catch (NoSuchMethodException e) {
Log.i("FAIL", "isHighTextContrastEnabled not found in AccessibilityManager");
}
}
Object result;
if (m != null) {
try {
result = m.invoke(am, null);
if (result instanceof Boolean) {
return (Boolean) result;
}
} catch (Exception e) {
Log.i("fail", "isHighTextContrastEnabled invoked with an exception" + e.getMessage());
}
}
}
return false;
}
I hope this can help many more others.
we can check highContrast fonts like this
public boolean isHighTextContrastEnabled(Context context) {
return Settings.Secure.getInt(context.getContentResolver(), "high_text_contrast_enabled", 0) == 1;
}

How to check permission SYSTEM_ALERT_WINDOW is granted on Android Lollipop?

Note that I'm talking about Android Lollipop. For android 6.0 we can use method canDrawOverlays() to check that SYSTEM_ALERT_WINDOW is granted or not.
With Android Lollipop, almost devices grant this permission by default. But on some devices of Xiaomi, Meizu.. it is not granted. Users need to go to the App info to allow it.
How can we check it programmatically to warn users?
in MIUI use
public static boolean isMiuiFloatWindowOpAllowed(#NonNull Context context) {
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
return checkOp(context, OP_SYSTEM_ALERT_WINDOW); //See AppOpsManager.OP_SYSTEM_ALERT_WINDOW=24 /*#hide/
} else {
return (context.getApplicationInfo().flags & 1<<27) == 1;
}
}
public static boolean checkOp(Context context, int op, String packageName, int uid) {
final int version = Build.VERSION.SDK_INT;
if (version >= 19) {
AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
try {
return (AppOpsManager.MODE_ALLOWED == (Integer) ReflectUtils.invokeMethod(manager, "checkOp", op, uid, packageName));
} catch (Exception e) {
e.printStackTrace();
}
} else {
Flog.e("Below API 19 cannot invoke!");
}
return false;
}
ReflectUtils.java
public static Object invokeMethod(#NonNull Object receiver, String methodName, Object... methodArgs) throws Exception {
Class<?>[] argsClass = null;
if (methodArgs != null && methodArgs.length != 0) {
int length = methodArgs.length;
argsClass = new Class[length];
for (int i=0; i<length; i++) {
argsClass[i] = getBaseTypeClass(methodArgs[i].getClass());
}
}
Method method = receiver.getClass().getMethod(methodName, argsClass);
return method.invoke(receiver, methodArgs);
}
Reflection is risky because you take things for granted...and things can change in future versions of Android. The following method only uses reflection if the proper way fails.
#SuppressLint("NewApi")
public static boolean canDrawOverlayViews(Context con){
if(Build.VERSION.SDK_INT< Build.VERSION_CODES.LOLLIPOP)
return true;
try {
return Settings.canDrawOverlays(con);
}
catch(NoSuchMethodError e){
return canDrawOverlaysUsingReflection(con);
}
}
public static boolean canDrawOverlaysUsingReflection(Context context) {
try {
AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
Class clazz = AppOpsManager.class;
Method dispatchMethod = clazz.getMethod("checkOp", new Class[] { int.class, int.class, String.class });
//AppOpsManager.OP_SYSTEM_ALERT_WINDOW = 24
int mode = (Integer) dispatchMethod.invoke(manager, new Object[] { 24, Binder.getCallingUid(), context.getApplicationContext().getPackageName() });
return AppOpsManager.MODE_ALLOWED == mode;
} catch (Exception e) { return false; }
}

How to check programmatically if data roaming is enabled/disabled?

I'm trying to check if the user has enabled/disabled data roaming. All I found so far is that you can check whether or not the user is currently IN roaming, using TelephonyManager.isNetworkRoaming() and NetworkInfo.isRoaming(), but they are not what I need.
Based on Nippey's answer, the actual piece of code that worked for me is:
public Boolean isDataRoamingEnabled(Context context) {
try {
// return true or false if data roaming is enabled or not
return Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.DATA_ROAMING) == 1;
}
catch (SettingNotFoundException e) {
// return null if no such settings exist (device with no radio data ?)
return null;
}
}
You can request the state of the Roaming-Switch via
ContentResolver cr = ContentResolver(getCurrentContext());
Settings.Secure.getInt(cr, Settings.Secure.DATA_ROAMING);
See: http://developer.android.com/reference/android/provider/Settings.Secure.html#DATA_ROAMING
public static final Boolean isDataRoamingEnabled(final Context application_context)
{
try
{
if (VERSION.SDK_INT < 17)
{
return (Settings.System.getInt(application_context.getContentResolver(), Settings.Secure.DATA_ROAMING, 0) == 1);
}
return (Settings.Global.getInt(application_context.getContentResolver(), Settings.Global.DATA_ROAMING, 0) == 1);
}
catch (Exception exception)
{
return false;
}
}
Updated function to account for API deprecation. It is now replaced with:
http://developer.android.com/reference/android/provider/Settings.Global.html#DATA_ROAMING
public static boolean IsDataRoamingEnabled(Context context) {
try {
// return true or false if data roaming is enabled or not
return Settings.Global.getInt(context.getContentResolver(), Settings.Global.DATA_ROAMING) == 1;
}
catch (SettingNotFoundException e) {
return false;
}
}

android turning on wifi programmatically

I am trying to turn add a wifi network programmatically and to connect to that network.
My code works fine if the wi-fi is already turned on.
If wi-fi is off, what i see wifimanager.addtonetwork() fails and when i see the wifi settings for the phone, i can see the status as scanning
If i try to connect again it works fine.
Please see code below.
Please help
private int changeNetwork(NetworkSetting setting) {
// If the SSID is empty, throw an error and return
if (setting.getSsid() == null || setting.getSsid().length() == 0) {
return doError(R.string.wifi_ssid_missing);
}
// If the network type is invalid
if (setting.getNetworkType() == NetworkType.NETWORK_INVALID) {
return doError(R.string.wifi_type_incorrect);
}
// If the password is empty, this is an unencrypted network
if (setting.getPassword() == null
|| setting.getPassword().length() == 0
|| setting.getNetworkType() == null
|| setting.getNetworkType() == NetworkType.NETWORK_NOPASS) {
return changeNetworkUnEncrypted(setting);
}
if (setting.getNetworkType() == NetworkType.NETWORK_WPA) {
return changeNetworkWPA(setting);
} else {
return changeNetworkWEP(setting);
}
}
private int doError(int resource_string) {
statusView.setText(resource_string);
// Give up on the connection
wifiManager.disconnect();
if (networkId > 0) {
wifiManager.removeNetwork(networkId);
networkId = -1;
}
if (receiverRegistered) {
unregisterReceiver(wifiReceiver);
receiverRegistered = false;
}
return -1;
}
private WifiConfiguration changeNetworkCommon(NetworkSetting input) {
statusView.setText(R.string.wifi_creating_network);
Log.d(TAG, "Adding new configuration: \nSSID: " + input.getSsid()
+ "\nType: " + input.getNetworkType());
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
// Android API insists that an ascii SSID must be quoted to be correctly
// handled.
config.SSID = NetworkUtil.convertToQuotedString(input.getSsid());
config.hiddenSSID = true;
return config;
}
private int requestNetworkChange(WifiConfiguration config) {
statusView.setText(R.string.wifi_changing_network);
return updateNetwork(config, false);
}
// Adding a WEP network
private int changeNetworkWEP(NetworkSetting input) {
WifiConfiguration config = changeNetworkCommon(input);
String pass = input.getPassword();
if (NetworkUtil.isHexWepKey(pass)) {
config.wepKeys[0] = pass;
} else {
config.wepKeys[0] = NetworkUtil.convertToQuotedString(pass);
}
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
return requestNetworkChange(config);
}
// Adding a WPA or WPA2 network
private int changeNetworkWPA(NetworkSetting input) {
WifiConfiguration config = changeNetworkCommon(input);
String pass = input.getPassword();
// Hex passwords that are 64 bits long are not to be quoted.
if (HEX_DIGITS_64.matcher(pass).matches()) {
Log.d(TAG, "A 64 bit hex password entered.");
config.preSharedKey = pass;
} else {
Log.d(TAG, "A normal password entered: I am quoting it.");
config.preSharedKey = NetworkUtil.convertToQuotedString(pass);
}
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
// For WPA
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
// For WPA2
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
return requestNetworkChange(config);
}
// Adding an open, unsecured network
private int changeNetworkUnEncrypted(NetworkSetting input) {
Log.d(TAG, "Empty password prompting a simple account setting");
WifiConfiguration config = changeNetworkCommon(input);
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
return requestNetworkChange(config);
}
/**
* If the given ssid name exists in the settings, then change its password
* to the one given here, and save
*
* #param ssid
*/
private WifiConfiguration findNetworkInExistingConfig(String ssid) {
List<WifiConfiguration> existingConfigs = wifiManager
.getConfiguredNetworks();
Log.i("Start comparing","Size "+existingConfigs.size() );
for (WifiConfiguration existingConfig : existingConfigs) {
Log.i("Compare with SSID", ssid + existingConfig.SSID);
if (existingConfig.SSID.equals(ssid)) {
Log.i("Compare success with SSID", ssid + existingConfig.SSID);
return existingConfig;
}
}
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
/* if (intent == null
|| !intent.getAction().equals(Intents.WifiConnect.ACTION)) {
finish();
return;
} */
String ssid = intent.getStringExtra("ssid");
String password = intent.getStringExtra("password");
String networkType = intent.getStringExtra("type");
setContentView(R.layout.network);
statusView = (TextView) findViewById(R.id.networkStatus);
NetworkType networkT;
if ("WPA".equals(networkType)) {
networkT = NetworkType.NETWORK_WPA;
} else if ("WEP".equals(networkType)) {
networkT = NetworkType.NETWORK_WEP;
} else if ("nopass".equals(networkType)) {
networkT = NetworkType.NETWORK_NOPASS;
} else {
networkT = NetworkType.NETWORK_INVALID;
}
// This is not available before onCreate
wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
// Start WiFi, otherwise nothing will work
wifiManager.setWifiEnabled(true);
// So we know when the network changes
wifiReceiver = new WifiReceiver(wifiManager, this, statusView, ssid);
// The order matters!
mWifiStateFilter = new IntentFilter(
WifiManager.WIFI_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mWifiStateFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(wifiReceiver, mWifiStateFilter);
receiverRegistered = true;
if (password == null) {
password = "";
}
Log.d(TAG, "Adding new configuration: \nSSID: " + ssid + "Type: "
+ networkT);
NetworkSetting setting = new NetworkSetting(ssid, password, networkT);
changeNetwork(setting);
}
#Override
public void onPause() {
super.onPause();
if (receiverRegistered) {
unregisterReceiver(wifiReceiver);
receiverRegistered = false;
}
}
#Override
public void onResume() {
super.onResume();
if (wifiReceiver != null && mWifiStateFilter != null
&& !receiverRegistered) {
registerReceiver(wifiReceiver, mWifiStateFilter);
receiverRegistered = true;
}
}
#Override
protected void onDestroy() {
if (wifiReceiver != null) {
if (receiverRegistered) {
unregisterReceiver(wifiReceiver);
receiverRegistered = false;
}
wifiReceiver = null;
}
super.onDestroy();
}
/**
* Update the network: either create a new network or modify an existing
* network
*
* #param config
* the new network configuration
* #param disableOthers
* true if other networks must be disabled
* #return network ID of the connected network.
*/
private int updateNetwork(WifiConfiguration config, boolean disableOthers) {
WifiConfiguration found = findNetworkInExistingConfig(config.SSID);
wifiManager.disconnect();
if (found == null) {
Log.i("WIFI","SSID NOT FOUND");
statusView.setText(R.string.wifi_creating_network);
} else {
statusView.setText(R.string.wifi_modifying_network);
Log.d(TAG, "Removing network " + found.networkId);
wifiManager.removeNetwork(found.networkId);
wifiManager.saveConfiguration();
}
networkId = wifiManager.addNetwork(config);
Log.d(TAG, "Inserted/Modified network " + networkId);
if (networkId < 0) {
wifiManager.setWifiEnabled(true);
networkId = wifiManager.addNetwork(config);
Log.d(TAG, "Again Inserted/Modified network " + networkId);
return FAILURE_NO_NETWORK_ID;
}
// Try to disable the current network and start a new one.
if (!wifiManager.enableNetwork(networkId, disableOthers)) {
networkId = FAILURE_NO_NETWORK_ID;
return FAILURE_NO_NETWORK_ID;
}
errorCount = 0;
wifiManager.reassociate();
return networkId;
}
Here is my working code : ( its different from my previous code )
package com.idg.project.utils;
import java.util.List;
import java.util.regex.Pattern;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;
/**
* #author Vikram Aggarwal
* #author Sean Owen
*/
public final class WifiConfigManager {
private static final String TAG = WifiConfigManager.class.getSimpleName();
private static final Pattern HEX_DIGITS = Pattern.compile("[0-9A-Fa-f]+");
private WifiConfigManager() {
}
public static void configure(final WifiManager wifiManager,
final String ssid,
final String password,
final String networkTypeString) {
Runnable configureRunnable = new Runnable() {
public void run() {
// Start WiFi, otherwise nothing will work
if (!wifiManager.isWifiEnabled()) {
Log.i(TAG, "Enabling wi-fi...");
if (wifiManager.setWifiEnabled(true)) {
Log.i(TAG, "Wi-fi enabled");
} else {
Log.w(TAG, "Wi-fi could not be enabled!");
return;
}
// This happens very quickly, but need to wait for it to enable. A little busy wait?
int count = 0;
while (!wifiManager.isWifiEnabled()) {
if (count >= 10) {
Log.i(TAG, "Took too long to enable wi-fi, quitting");
return;
}
Log.i(TAG, "Still waiting for wi-fi to enable...");
try {
Thread.sleep(1000L);
} catch (InterruptedException ie) {
// continue
}
count++;
}
}
NetworkType networkType = NetworkType.forIntentValue(networkTypeString);
if (networkType == NetworkType.NO_PASSWORD) {
changeNetworkUnEncrypted(wifiManager, ssid);
} else {
if (password == null || password.length() == 0) {
throw new IllegalArgumentException();
}
if (networkType == NetworkType.WEP) {
changeNetworkWEP(wifiManager, ssid, password);
} else if (networkType == NetworkType.WPA) {
changeNetworkWPA(wifiManager, ssid, password);
} }
}
};
new Thread(configureRunnable).start();
}
/**
* Update the network: either create a new network or modify an existing network
* #param config the new network configuration
* #return network ID of the connected network.
*/
private static void updateNetwork(WifiManager wifiManager, WifiConfiguration config) {
Integer foundNetworkID = findNetworkInExistingConfig(wifiManager, config.SSID);
if (foundNetworkID != null) {
Log.i(TAG, "Removing old configuration for network " + config.SSID);
wifiManager.removeNetwork(foundNetworkID);
wifiManager.saveConfiguration();
}
int networkId = wifiManager.addNetwork(config);
if (networkId >= 0) {
// Try to disable the current network and start a new one.
if (wifiManager.enableNetwork(networkId, true)) {
Log.i(TAG, "Associating to network " + config.SSID);
wifiManager.saveConfiguration();
} else {
Log.w(TAG, "Failed to enable network " + config.SSID);
}
} else {
Log.w(TAG, "Unable to add network " + config.SSID);
}
}
private static WifiConfiguration changeNetworkCommon(String ssid) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
// Android API insists that an ascii SSID must be quoted to be correctly handled.
config.SSID = quoteNonHex(ssid);
return config;
}
// Adding a WEP network
private static void changeNetworkWEP(WifiManager wifiManager, String ssid, String password) {
WifiConfiguration config = changeNetworkCommon(ssid);
config.wepKeys[0] = quoteNonHex(password, 10, 26, 58);
config.wepTxKeyIndex = 0;
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
updateNetwork(wifiManager, config);
}
// Adding a WPA or WPA2 network
private static void changeNetworkWPA(WifiManager wifiManager, String ssid, String password) {
WifiConfiguration config = changeNetworkCommon(ssid);
// Hex passwords that are 64 bits long are not to be quoted.
config.preSharedKey = quoteNonHex(password, 64);
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // For WPA
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
updateNetwork(wifiManager, config);
}
// Adding an open, unsecured network
private static void changeNetworkUnEncrypted(WifiManager wifiManager, String ssid) {
WifiConfiguration config = changeNetworkCommon(ssid);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
updateNetwork(wifiManager, config);
}
private static Integer findNetworkInExistingConfig(WifiManager wifiManager, String ssid) {
List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals(ssid)) {
return existingConfig.networkId;
}
}
return null;
}
private static String quoteNonHex(String value, int... allowedLengths) {
return isHexOfLength(value, allowedLengths) ? value : convertToQuotedString(value);
}
/**
* Encloses the incoming string inside double quotes, if it isn't already quoted.
* #param string the input string
* #return a quoted string, of the form "input". If the input string is null, it returns null
* as well.
*/
private static String convertToQuotedString(String string) {
if (string == null || string.length() == 0) {
return null;
}
// If already quoted, return as-is
if (string.charAt(0) == '"' && string.charAt(string.length() - 1) == '"') {
return string;
}
return '\"' + string + '\"';
}
/**
* #param value input to check
* #param allowedLengths allowed lengths, if any
* #return true if value is a non-null, non-empty string of hex digits, and if allowed lengths are given, has
* an allowed length
*/
private static boolean isHexOfLength(CharSequence value, int... allowedLengths) {
if (value == null || !HEX_DIGITS.matcher(value).matches()) {
return false;
}
if (allowedLengths.length == 0) {
return true;
}
for (int length : allowedLengths) {
if (value.length() == length) {
return true;
}
}
return false;
}
}
package com.idg.project.utils;
enum NetworkType {
WEP,
WPA,
NO_PASSWORD;
static NetworkType forIntentValue(String networkTypeString) {
if (networkTypeString == null) {
return NO_PASSWORD;
}
if ("WPA".equals(networkTypeString)) {
return WPA;
}
if ("WEP".equals(networkTypeString)) {
return WEP;
}
if ("nopass".equals(networkTypeString)) {
return NO_PASSWORD;
}
throw new IllegalArgumentException(networkTypeString);
}
}
You can turn on/off wifi using following instructions :
WifiManager wManager = (WifiManager)this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wManager.setWifiEnabled(booleanValue); //true or false
Set following permissions to your manifest:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE">
This code is deprecated in API 29 or over
public boolean setWifiEnabled (boolean enabled)
**This method was deprecated in API level 29**.
Starting with Build.VERSION_CODES#Q, applications are not allowed to
enable/disable Wi-Fi. Compatibility Note: For applications targeting
Build.VERSION_CODES.Q or above, this API will always return false and
will have no effect. If apps are targeting an older SDK (
Build.VERSION_CODES.P or below), they can continue to use this API.
Source : Link
You need to create wifiLock with WIFI_MODE_FULL_HIGH_PERF mode, based on the docs it will only work with the following constraints:
The lock is only active when the device is connected to an access point.
The lock is only active when the screen is on.
The lock is only active when the acquiring app is running in the foreground.

Categories

Resources