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

时间:2018-08-02 12:03:55

标签: android location

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

下面的enableLocation()方法负责提示用户,并提示getDeviceLocation()获取位置。我尝试将getDeviceLocation()放在onstart方法中,并将enableLocation()放在oncreate中,但是它仍然无法正常工作。有什么想法吗?

例如,在uber应用程序中,如果禁用了R.id.contrainer框架布局,则似乎将其替换为虚拟片段(而不是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 个答案:

答案 0 :(得分:0)

  

private void getCurrentLocation(){

    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();
    }
}