Not able to get Location by GPS : Android

2019-09-02 02:19发布

问题:

I am new to android. I am trying to get my location using GPS. I have included the permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>

Whenever I am trying to get my Location from LocationManager using getLastKnownLocation I am getting null object. Also, GPS is enabled. Here is my code:

LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location location;
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    Log.d("ManualLog", "GPS_DISABLED");
    Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(settingsIntent);
} else {
    Log.d("ManualLog", "GPS_ENABLED");
    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

回答1:

Are you running it on emulator or device? If on emulator, you may need to send GPS data manually to emulator via "emulator control". In eclipse, you can find it Window>Open Perspective>DDMS.

If you are running on device, is it possible your device never received a GPS signal before?



回答2:

locationManager.getLastKnownLocation will return null if the GPS has not had time to get a fix yet. Android does not provide a 'give me the location now' method. When the GPS has got a fix, the onLocationChanged() will run. It is event driven, you have to be patient and wait for that event. Once onLocationChanged() has run, then getLastKnownLocation() will return a non null value.



回答3:

Try to replace the last line by:

List<String> providers = locationManager.getProviders(true);
if(!providers.isEmpty()) {
    location = locationManager.getLastKnownLocation(providers.get(0));
} else {
   Log.d("ManualLog", "No provider");
}