如何以编程方式获取使用权限 [英] How to get Usage Access Permission programmatically

查看:217
本文介绍了如何以编程方式获取使用权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用需要具有使用访问权限才能在用户手机上获取有关当前正在运行的应用的信息.在以下链接的帮助下,我可以使用以下代码成功实现它.

My app needs to have Usage Access Permission in order to get information about the current running app on user's phone. I am able to successfully implement it using the following code with the help from the following link.

使用访问应用程序

这是我的工作代码

public void showDialog()
 {
     if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

         @SuppressWarnings("WrongConstant")
         UsageStatsManager usm = (UsageStatsManager) getSystemService("usagestats");
         long time = System.currentTimeMillis();
         List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
                 time - 1000 * 1000, time);
         if (appList.size()==0)
         {
             AlertDialog alertDialog = new AlertDialog.Builder(this)
                     .setTitle("Usage Access")
                     .setMessage("App will not run without usage access permissions.")
                     .setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                         @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                         public void onClick(DialogInterface dialog, int which) {
                             // continue with delete
                             Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                            // intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Settings$SecuritySettingsActivity"));
                             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                             startActivityForResult(intent,0);
                         }
                     })
                     .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                             // do nothing
                             dialog.dismiss();
                         }
                     })
                     .setIcon(android.R.drawable.ic_dialog_alert)
                     .create();

             alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
             alertDialog.show();
         }                      else {
             Intent intent = new Intent(this, PackageService.class);
             startService(intent);
             finish();
         }
     }else
     {
         Intent intent = new Intent(this, PackageService.class);
         startService(intent);
         finish();
     }
 }

此代码将向用户显示一个警告对话框,提示需要使用访问权限,并将用户带到可以启用它的设置屏幕.

This code will show a user an alert dialog that Usage Access permission is required and will take user to the settings screen from where it can be enabled.

一切与此完美配合.我唯一需要的是如何在不手动关闭用户的情况下默认授予我的应用使用访问权限?

Everything works perfectly with this. Only thing that I want is that how to give my app usage access permission by default without showing any dialog to user until he/she doesn't turn it off manually?

推荐答案

您可以在清单上简单地授予此许可权,而忽略此许可权错误:

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions"/>

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions"/>

比使用以下代码获得许可

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (!isAccessGranted()) {
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        startActivity(intent);
    }
}


private boolean isAccessGranted() {
        try {
            PackageManager packageManager = getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
            AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
            int mode = 0;
            if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.KITKAT) {
                mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                        applicationInfo.uid, applicationInfo.packageName);
            }
            return (mode == AppOpsManager.MODE_ALLOWED);

        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

这篇关于如何以编程方式获取使用权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆