Alfonso Fernandez-Ocampo Alfonso Fernandez-Ocampo - 1 year ago 92
Android Question

Getting User location lat lng with API 22

Trying something as simple as the following code, does not seem to work:

I always get in the logs "No Location :("

Am I missing something?

public class MainActivity extends AppCompatActivity implements LocationListener {

LocationManager locationManager;
String provider;

protected void onCreate(Bundle savedInstanceState) {

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

provider = locationManager.getBestProvider(new Criteria(), false);

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Location location = locationManager.getLastKnownLocation(provider);

if(location != null){
Log.i("Location","Location achieved");
Log.i("Location","No location :(");

Answer Source

If you are running an emulator, make sure to send an location event from the emulator settings. Nevertheless, getLastKnownLocation can always return null. You could use LocationManager#requestLocationUpdates to listen to any location changes instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download