So there are many similar questions asked based on this, and I have also got a working solution. However, this seems to only work on my physical Android device. If I were to use it with the emulator, the method returns a null value and I don't know why. Many sources mention that there is a better alternative to the code that I am currently using but they don't mention what/how exactly. This is the code that I am using to get the current location of my device:
@SuppressWarnings("MissingPermission")
private LatLng getCurrentLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
assert locationManager != null;
android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
return new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
}
I also don't like the fact that I have to suppress warnings. Sources that I have looked at include:
https://developer.android.com/training/location/retrieve-current.html#java
What is the simplest and most robust way to get the user's current location on Android?
The first one doesn't work, I get a null value. The second one looks overly complicated for a simple result that I am seeking.