您所做的是正确的,但位置提供程序有时返回null。你可能得好好处理。如果要手动获取位置使用
LocationManager
.
private void updateLocations(){
String str_latitude = "";
String str_longitude = "";
String provider = "";
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
}
if (!provider.equals("")) {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
@SuppressLint("MissingPermission") Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(MainActivity.this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Location mLastKnownLocation = (Location) task.getResult();
if (mLastKnownLocation != null) {
str_longitude = String.valueOf(mLastKnownLocation.getLatitude());
str_latitude = String.valueOf(mLastKnownLocation.getLongitude());
Toast.makeText(context, "Lat: "+str_latitude + ", Long " + str_longitude, Toast.LENGTH_LONG).show();
}
if (str_latitude.equals("") || str_longitude.equals("")) {
Snackbar.make(coordinatorLayout, "Couldn't find location, please try again in a moment", Snackbar.LENGTH_LONG).show();
}
}
}
});
} else if (provider.equals("")) {
Snackbar snackbar = Snackbar.make(coordinatorLayout, "Seems like all providers of device are disabled", Snackbar.LENGTH_LONG);
snackbar.setAction("Enable", new View.OnClickListener() {
@Override
public void onClick(View v) {
//Takes user to gps enable settings.
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
snackbar.show();
}
}});