Reputation: 3846
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);
}
Upvotes: 0
Views: 1193
Reputation: 23873
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.
Upvotes: 2
Reputation: 740
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?
Upvotes: 0
Reputation: 3895
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");
}
Upvotes: 0