Alfonso Fernandez-Ocampo Alfonso Fernandez-Ocampo - 8 days ago 8
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;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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) {
return;
}
Location location = locationManager.getLastKnownLocation(provider);

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

Answer

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.