使用 LocationManager 时请求权限 [英] Asking for permissions while using LocationManager

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

问题描述

我刚刚开始使用 Android 编程,到目前为止,我只是在按钮、文本视图和一些活动方面有点混乱,但我想从服务和 GPS 位置开始.为了稍微练习一下,我正在构建一个简单的应用程序,它只显示用户的坐标.我已经用一些方法创建了自己的服务类,但是每当我尝试实现以下方法时,我的应用程序就会崩溃:

I've just started with Android programming and so far, I've just messed a little bit around buttons, textviews and some activities, but I would like to begin with services and GPS locations. In order to practise a little bit, I'm building a simple app that just shows the coordinates of the user. I've created my own service class with some methods, but whenever I try to implement the following one, my app crashes:

    @TargetApi(23)
public Location getLocation(){
    try{
        locationManager = (LocationManager)this.ctx.getSystemService(LOCATION_SERVICE);
        gpsActivado = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
    }catch(Exception e){
        e.printStackTrace();
    }


    if(gpsActivado && (ctx.checkSelfPermission("ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED)){
        locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER
                ,1000*60
                ,2
                ,this);
        return locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);

    }else{
        return null;
    }

}

通过一些调试消息,我知道问题与检查权限有关.那有什么问题?您现在是否有任何其他方法来检查我是否具有所需的权限?出于某种原因,我不喜欢我正在使用的那个.

With some debugging messages, I know that the problem is related to checking of permissions. Whats wrong with that? Do you now any other method in order to check if I have the required permissions? For some reason, I don't like the one I'm using.

提前致谢:)

PS:我使用的是 API 16

PS: I'm using API 16

推荐答案

使用 Android Marshmallow,即使您在 Manifest 文件中指定了权限,您也必须明确请求用户的权限.因此,您必须以这种方式请求位置权限:首先为位置创建一个请求代码

With Android Marshmallow, you have to explicitly request permission from the user even if you have specified those in Manifest file. So, you have to request for location permissions this way : First you create a request code for location

public static final int LOCATION_REQUEST_CODE = 1001; //Any number

然后检查是否已经授予权限,如果没有,则代码将请求权限,这将显示一个本机弹出窗口,要求拒绝/允许位置权限

And then check if already permission is granted or not, if not then the code will request for permission which will show a native popup asking to deny/allow the location permission

if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST_CODE);
        } else {
           locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER
            ,1000*60,2,this);
   Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
        }

上述代码应该在请求任何位置之前编写,最好在活动的 onCreate() 中.然后根据用户在弹出窗口上采取的操作,您将获得一个回调,您可以在其中根据您的要求执行.

The above code should be written before requesting any location preferably in onCreate() of the activity. Then based on the action taken by the user on the popup , you'll get a callback where you can perform according to your requirement.

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case LOCATION_REQUEST_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
                  locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER
            ,1000*60,2,this);
   Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
                }
            }
        }
    }

此外,无论您在何处尝试获取位置,都应检查是否已向您的应用授予位置权限,然后再获取位置.

Also, wherever you are trying to fetch the location, you should check whether the location permission has been granted to your application or not and then fetch the location.

 if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                          locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER
            ,1000*60,2,this);
   Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
                    }

您可以请求 Manifest.permission.ACCESS_FINE_LOCATIONManifest.permission.ACCESS_COARSE_LOCATION 或两者.这取决于您的要求.

You can request Manifest.permission.ACCESS_FINE_LOCATION or Manifest.permission.ACCESS_COARSE_LOCATION or both. It depends upon your requirement.

这篇关于使用 LocationManager 时请求权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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