Android 23使用定位权限报错Call requires permission which may be rejected by user

报错了“Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
权限问题
使用时,需要检查用户是否授权
参考链接1:http://blog.5ibc.net/p/62176.html
参考链接2:http://blog.csdn.net/qq_27278679/article/details/51095770
代码解决(亲测可用):

private void getlocationGps(){
//此处的判定是主要问题,API23之后需要先判断之后才能调用locationManager中的方法

//包括这里的getLastKnewnLocation方法和requestLocationUpdates方法
    if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
        //获取定位服务
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取当前可用的位置控制器
        List list = locationManager.getProviders(true);

        if (list.contains(LocationManager.GPS_PROVIDER)) {
            //是否为GPS位置控制器
            provider = LocationManager.GPS_PROVIDER;
        } else if (list.contains(LocationManager.NETWORK_PROVIDER)) {
            //是否为网络位置控制器
            provider = LocationManager.NETWORK_PROVIDER;

        } else {
            Toast.makeText(this, "请检查网络或GPS是否打开",
                    Toast.LENGTH_LONG).show();
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            //获取当前位置,这里只用到了经纬度
            String string = "纬度为:" + location.getLatitude() + ",经度为:"
                    + location.getLongitude();
        }
//绑定定位事件,监听位置是否改变
//第一个参数为控制器类型第二个参数为监听位置变化的时间间隔(单位:毫秒)
//第三个参数为位置变化的间隔(单位:米)第四个参数为位置监听器
        locationManager.requestLocationUpdates(provider, 2000, 2, locationListener);
    }
}
public LocationListener locationListener=new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};
    //关闭时解除监听器
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //api23需要这样写
        if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
            if (locationManager != null) {
                locationManager.removeUpdates(locationListener);
            }
        }
    }

你可能感兴趣的:(android开发)