0

我需要从我的应用程序中打开 Usage Stats 设置。对于大多数手机,一切正常:

startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));

但是,有些手机(例如华为 Y6 Pro)会引发安全异常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

有没有办法检查我是否可以执行startActivity并且不会抛出任何异常?

4

2 回答 2

1

我认为您可以检查是否可以使用此执行以下意图

科特林:

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

爪哇:

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;
    }

并像这样使用

if (canPerformIntent(this, Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS))) {
            //TODO: start the intent
        }
于 2018-02-07T10:09:33.163 回答
0

更新

试试这个:

将此添加到您的活动清单中

   <activity
        android:name=".MainActivity"

        android:exported="true">


    </activity>
于 2018-02-07T09:39:26.813 回答