问题
Well even having a lot of reading here, i can't figure out the issue. It looks like i never get gps turned on event.
After some checking in debug, the flag isGps is correct. But as a result, user alert works nice but not update location. I just want to add a marker when gps is turned on and it looks like something is not correctly synchronised here.
And that even with high accuraty location.
I use this code from my fragment.
public class MapDialogFragment extends DialogFragment
implements OnMapReadyCallback, GoogleMap.OnMarkerDragListener {
.....
private BroadcastReceiver mGpsSwitchStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
boolean isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGPS){
// never goes here WHEN GPS TURNED ON !!! WHY ?? MAKES ME CRAZY
// + how get current location here ? is updateMyLocation call ok ?
updateMyLocation();
}
else{
// user alert
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.message_location_error_gps_off), Toast.LENGTH_LONG).show();
}
}
}
};
@Override
public void onResume() {
super.onResume();
getContext().registerReceiver(mGpsSwitchStateReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
@Override
public void onPause() {
super.onPause();
getContext().unregisterReceiver(mGpsSwitchStateReceiver);
}
private void updateMyLocation(){
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful() && task.getResult() != null) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = (Location) task.getResult();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
latitude = mLastKnownLocation.getLatitude();
longitude = mLastKnownLocation.getLongitude();
// add marker
buildMarkerFromLocation();
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
}
}
});
}
...
}
So here is my logic :
- Check if GPS is turned on
- If it is send mFusedLocationProviderClient.getLastLocation() request
- Get the result but always get no result when GPS is just turned on
So basically, how to provide a default location without hard code one ?
Here is more information about google api page :
The getLastLocation() method returns a Task that you can use to get a Location object with the latitude and longitude coordinates of a geographic location. The location object may be null in the following situations:
Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see Receiving Location Updates.
Hope i will solve this with your help. Should be something obvious but i dunno what is going wrong...
回答1:
since you receive the event, that means it has nothing to do with the device itself, and looks like it's in your update location, method in my case I'm using 'OnSuccessListener' not 'OnCompleteListener', I don't know if that would be an issue or not, but anyhow that's how I update the location at my side:
/**
* To get the current MapLocation and add marker at that location
*/
@SuppressLint("MissingPermission")
private void setCurrentLocation() {
try {
FusedLocationProviderClient locationClient = new FusedLocationProviderClient(getActivity());
if (checkLocationPermissions()) {
Task<Location> currentLocationTask = locationClient.getLastLocation(); // already checked
currentLocationTask.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
try {
// Now, add the required Marker
addMarker(new LatLng(location.getLatitude(), location.getLongitude()));
} catch (NullPointerException npe) {
npe.printStackTrace();
Toast.makeText(getActivity(), getResources().getString(R.string.cannot_get_location), Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Adding a Marker at the Map
*
* @param point the point contains the latitude and longitude to add the marker at
*/
private void addMarker(LatLng point) {
try {
marker.remove();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
MarkerOptions markerOptions = new MarkerOptions().position(
new LatLng(point.latitude, point.longitude)).title(getAddressAtLocation(point));
marker = mMap.addMarker(markerOptions);
currentChosenLocation = point;
}
来源:https://stackoverflow.com/questions/58837839/android-broadcast-gps-turned-on-update-location