java - 定位器不适用于 Android 6.0 +

标签 java android google-maps android-layout android-fragments

我的应用程序中的定位器出现问题。我有使用用户当前位置的服务,并基于它显示来自最近市场的图钉。它在 Android 6.0 上运行没有问题,但在 6.0 上无法获取用户位置。我认为是因为其中有新的权限系统。

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


    View v = inflater.inflate(R.layout.locator_fragment, container, false);


    // Gets the MapView from the XML layout and creates it

    mapView = (MapView) v.findViewById(R.id.mapview);
    mapView.onCreate(savedInstanceState);

    // Gets to GoogleMap from the MapView and does initialization stuff
    map = mapView.getMap();
    map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(final Location location) {
            Latitude= location.getLatitude();
            Longitude=  location.getLongitude();
            float distance = location.distanceTo(location);
            Location locationzoom = map.getMyLocation();
            LatLng mapCenter = new LatLng(location.getLatitude(), location.getLongitude());
            if(!didSetLocation) {
                CameraPosition cameraPosition = CameraPosition.builder()
                        .target(mapCenter)
                        .zoom(13)
                        .bearing(80)
                        .build();

                map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
                        2000, null);
                didSetLocation=true;
            }
            if ((lastcall!=null)?(location.distanceTo(lastcall)>1000):true)
            {
                map.clear();
                NetworkSDK.getInstance().getCoordinates(Latitude, Longitude, new Callback<List<Coordinate>>() {
                    @Override
                    public void onResponse(Call<List<Coordinate>> call, Response<List<Coordinate>> response) {
                        for (int i = 0; i < response.body().size(); i++) {
                            map.addMarker(new MarkerOptions()
                                    .position(new LatLng(response.body().get(i).getLatitude(), response.body().get(i).getLongitude()))
                                    .title(response.body().get(i).getName()));

                        }
                        lastcall=location;

                    }

                    @Override
                    public void onFailure(Call<List<Coordinate>> call, Throwable t) {
                        Toast.makeText(getContext(), R.string.errorNoconnection, Toast.LENGTH_SHORT).show();

                    }
                });
            }
        }

    });

    Location mLastLocation;
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    map.getUiSettings().setMyLocationButtonEnabled(false);
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return v;
    }
    map.setMyLocationEnabled(true);
    map.isTrafficEnabled();

    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls

    MapsInitializer.initialize(this.getActivity());

    // Updates the location and zoom of the MapView
    return v;
}

我应该如何让用户选择授予应用程序权限?

最佳答案

private static final int REQUEST_CAMERA_PERMISSION = 1;

     void checkPremission() {
            //select which permission you want
            final String permission = Manifest.permission.CAMERA;
                // if in fragment use getActivity()
            if (ContextCompat.checkSelfPermission(ActivityName.this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(ActivityName.this, permission)) {

                } else {
                    ActivityCompat.requestPermissions(ActivityName.this, new String[]{permission}, REQUEST_CAMERA_PERMISSION);
                }
            } else {
                // you have permission go ahead

            }
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode) {
                case REQUEST_CAMERA_PERMISSION:
                    final int numOfRequest = grantResults.length;
                    final boolean isGranted = numOfRequest == 1
                            && PackageManager.PERMISSION_GRANTED == grantResults[numOfRequest - 1];
                    if (isGranted) {
                        // you have permission go ahead
                    }else{
                        // you dont have permission show toast
                    }
                    break;
                default:
                    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }

Full Documentation

关于java - 定位器不适用于 Android 6.0 +,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37587333/

相关文章:

java - 如何使用 Jackson 从 Json 文件中读取特定对象

java - Java 中是否可能存在运行时类型不匹配?

java - android 通话时如何设置延迟时间?

java - Android 程序中 onCreate() 中的 NullPointerException

android - Geocoder.getFromLocationName 不适用于某些地方

java - 从API读取JSON数据

Java自定义枚举值枚举

android - 如何删除自定义对话框的矩形框

android - 此 api 项目无权使用此 API

android - 提高谷歌地图绘制长路径的性能