I am new for Android coding, and have writen a code to get location of Android Device but failed. Nothing changed (e.g. mLastKnownLocation or cityName) after runing, and no expception. I have already checked permission and build.gradle. Could you give me advices to implement it?
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY,cancellationToken);
//Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>(){
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Obtain the current location of the device
mLastKnownLocation = task.getResult();
String currentOrDefault = "Current";
if (mLastKnownLocation != null) {
Log.d(TAG, "Get current location");
} else {
Log.d(TAG, "Current location is null. Using defaults.");
currentOrDefault = "Default";
// Set current location to the default location
mLastKnownLocation = new Location("");
mLastKnownLocation.setLatitude(mDefaultLocation.latitude);
mLastKnownLocation.setLongitude(mDefaultLocation.longitude);
}
String city = "CorrectCity";
try {
List<Address> address =
geocoder.getFromLocation(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude(), 1);
if(address.isEmpty())
city = "No_city";
else{
Address target = address.get(0);
if(target.getLocality()!=null)
city = target.getLocality();
else
city = target.getAdminArea();}
} catch (IOException e) {
Log.e("Exception: %s", e.getMessage());
}
cityName = city;
// Show location details on the location TextView
String msg = currentOrDefault + " Location: " +
Double.toString(mLastKnownLocation.getLatitude()) + ", " +
Double.toString(mLastKnownLocation.getLongitude())+ " " +
cityName;
locationTextView.setText(msg);
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
/*mMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);*/
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
cityName = "ErrorCity";
}
}
}
You can get your last known location using the code below
refer: https://developer.android.com/training/location/retrieve-current
Using
Location Manager