Question:
How to ask if "Installation from unsafe sources" is allowed on a device? Code example if possible.
Answer:
In short, in order for users с Android API 25 и ниже
to be able to install from insecure sources, they must enable the "Unknown Sources" option in the settings. one
Note: When users try to install an unknown app on a device running Android 7.1.1 (API level 25) or lower, the system will sometimes show a dialog asking the user whether they want to allow only one particular unknown app to be installed. In almost all cases, users should only allow one unknown installation app at a time if the option is available to them. one
boolean isNonPlayAppAllowed = Settings.Secure.getInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS) == 1;
if (!isNonPlayAppAllowed) {
startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS));
}
And in order for users с Android API 26 и выше
to be able to install from insecure sources , you must grant permission . one
Add to manifest.xml
2
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
Then the most basic: 2
private void checkIsAndroidO() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
boolean result = getPackageManager().canRequestPackageInstalls();
if (result) {
installApk();
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_PACKAGES_REQUESTCODE);
}
} else {
installApk();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case INSTALL_PACKAGES_REQUESTCODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
installApk();
} else {
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GET_UNKNOWN_APP_SOURCES:
checkIsAndroidO();
break;
default:
break;
}
}