代码之家  ›  专栏  ›  技术社区  ›  Manos Ntoulias

ANDROID:在提示用户启用位置后获取该位置

  •  0
  • Manos Ntoulias  · 技术社区  · 8 年前

    我想在应用程序启动时获取设备的当前位置。它工作正常,但如果禁用该位置,则会崩溃。因此,我使用了一些代码来提示用户激活它,但似乎程序在实际激活位置之前就到达了崩溃线(在提示用户激活它之前)。

    例如,在uber应用程序中,如果位置被禁用,R.id.container框架布局似乎会被虚拟片段(而不是SupportMapFragment)替换。点击一个按钮,提示用户启用它。然后SupportMapFragment将替换虚拟片段(据我所知)。但这一切似乎太过分了。这是唯一的办法吗?

    oncreate() {
    ....
        SupportMapFragment fragment;
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragment = new SupportMapFragment();
        fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
        fragment.getMapAsync(this);
    ..... 
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    
        // Prompt the user for permission.
        getLocationPermission();
    
        // Prompt the user to enable location if it is disabled
        // by using Task<LocationSettingsResponse>
        // and LocationSettingsRequest.Builder
        enableLocation();
    
        // Turn on the My Location layer and the related control on the map.
        updateLocationUI();
    
        // Get the current location of the device and set the position of the map.
        // uses Task.getResult which returns null because location
        // is yet to be activated despite chosing to do so above
        getDeviceLocation();
    }
    
    // inside getDeviceLocation();
    @Override
    public void onComplete(@NonNull Task<Location> task) {
           if (task.isSuccessful()) {
                    // Set the map's camera position to the current location of the device.
                    mLastKnownLocation = task.getResult(); // RETURNS NULL HERE
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(mLastKnownLocation.getLatitude(),
                    LastKnownLocation.getLongitude()), DEFAULT_ZOOM));
    } 
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   InsaneCat    8 年前

        gps = new GPSTracker(context, getActivity());
        if (gps.canGetLocation()) {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) 
             return;
            }
            currentLatitude = gps.getLatitude();
            currentLongitude = gps.getLongitude();
        } else {
            showSettingsAlert();
        }
    }
    
    推荐文章