How can I programmatically grant the permission in Settings -> Apps -> Draw over other apps
in Android? I want to use system alert window but unable to in Android Marshmallow without forcing the user to go through the Settings app and grant the permission first.
You can check and ask for overlay permission to draw over other apps using this
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 0);
}
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 0);
}
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Here's the code for automatic granting the SYSTEM_ALERT_WINDOW permission to the package. To run this code, your Android application must be system (signed by platform keys).
This method is based on the following Android source code files: AppOpsManager.java and DrawOverlayDetails.java, see the method DrawOverlayDetails.setCanDrawOverlay(boolean newState)
.
@TargetApi(Build.VERSION_CODES.KITKAT)
public static void autoSetOverlayPermission(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
int uid = 0;
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
uid = applicationInfo.uid;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return;
}
AppOpsManager appOpsManager = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
final int OP_SYSTEM_ALERT_WINDOW = 24;
try {
Class clazz = AppOpsManager.class;
Method method = clazz.getDeclaredMethod("setMode", int.class, int.class, String.class, int.class);
method.invoke(appOpsManager, OP_SYSTEM_ALERT_WINDOW, uid, packageName, AppOpsManager.MODE_ALLOWED);
Log.d(Const.LOG_TAG, "Overlay permission granted to " + packageName);
} catch (Exception e) {
Log.e(Const.LOG_TAG, Log.getStackTraceString(e));
}
}
}
The code has been tested in Headwind MDM project, it successfully grants "Draw over other apps" permission without any user consent to the Headwind Remote application (disclaimer: I'm the project owner of Headwind MDM and Headwind Remote), when Headwind MDM application is signed by platform keys. The code has been tested on Android 10 (LineageOS 17).
Check this question and the answer:
"Every app that requests the SYSTEM_ALERT_WINDOW permission and that is installed through the Play Store (version 6.0.5 or higher is required), will have granted the permission automatically."
© 2022 - 2024 — McMap. All rights reserved.