我想在应用程序启动时获取设备的当前位置。它工作得很好,但是如果位置被停用,它就会崩溃。所以我使用了一些代码来提示用户激活它,但似乎程序在位置被实际激活之前就到达了崩溃线。(在提示用户激活它之前)。
下面的enableLocation()方法负责提示用户和getDeviceLocation()获取位置。我尝试将getDeviceLocation()放在onstart方法中,将enableLocation()放在oncreate方法中,但仍然不起作用。有什么想法吗?
例如,在uber应用程序中,如果location被禁用,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));
} 发布于 2018-08-03 18:59:08
私有空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();
}
}https://stackoverflow.com/questions/51653176
复制相似问题