在方法中检查 Android 权限 [英] Check Android Permissions in a Method

查看:25
本文介绍了在方法中检查 Android 权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,它运行良好.

if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    mMap.setMyLocationEnabled(true);
}

但我不喜欢每次检查都写这么大的代码,并希望将它委托给我的实用程序类中的一个方法.

But I don't like such a big code on every check, and want to delegate it to a method in my utility class.

if (Utils.hasMapLocationPermissions(getActivity())) {
    mMap.setMyLocationEnabled(true);
}

但是 setMyLocationEnabled 有注释 @RequiresPermission 因此我不能将它委托给一个方法,因为 linteditor 将其显示为错误.

But setMyLocationEnabled has annotation @RequiresPermission And thus I can't delegate it to a method, because lint and editor shows it as an error.

是否有一些注释要写在我的实用程序方法上并抑制 lint?

Is there some annotation to write on my utility method and suppress lint?

像这样

@ChecksPermission
public boolean hasMapLocationPermissions(Activity activity) {
  return // my checking logic..
}

推荐答案

您可以将您的方法重命名为 checkLocationPermission(Activity activity).我发现您的方法名称必须以check"开头并以Permission"结尾才能传递 Lint 警告.

You can rename your method as checkLocationPermission(Activity activity). I´ve discovered that your method's name must start with "check" and end with "Permission" to pass Lint warnings.

例如:

public static boolean checkLocationPermission(Context context) {
    return ActivityCompat.checkSelfPermission(context,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context,
            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}

这篇关于在方法中检查 Android 权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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