javaandroidandroid-securityexception

Android security exception when accessing settings


I need to open Usage Stats settings from my application. For most of the phones, everything works fine:

startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));

However, there are some phones like Huawei Y6 Pro that throws Security Exception java.lang.SecurityException: Permission Denial: starting Intent { act=android.settings.USAGE_ACCESS_SETTINGS cmp=com.android.settings/.Settings$UsageAccessSettingsActivity } from ProcessRecord{3f032f8b 18712:com.example.pro/u0a924} (pid=18712, uid=10924) not exported from uid 1000

Is there a way to check if I can execute startActivity and it will not throw any exception?


Solution

  • I think you can check that if the following intent can be performed using this

    Kotlin:

    fun canPerformIntent(context: Context, intent: Intent): Boolean {
        val mgr = context.packageManager
        val list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
        return list.size > 0
    }
    

    Java:

    public static boolean canPerformIntent(Context context, Intent intent) {
            PackageManager mgr = context.getPackageManager();
            List<ResolveInfo> list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            return list.size() > 0;
        }
    

    and using like this

    if (canPerformIntent(this, Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS))) {
                //TODO: start the intent
            }