GPS provider enabled but getLastKnownLocation(provider) returns null
I'm trying to use a GPS Provider for my app.
The app finds the device's current location, using the GPS Location Provider.
The app works just fine. But, although my GPS_Provider is enabled, geLastKnownLocation()
returns null.
MainActivity.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
Log.v("BEFORE", "Location is: " + location);
updateWithNewLocation(location);
Log.v("AFTER", "LOCATION FOUND");
}
private void updateWithNewLocation(Location location){
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "nLong:" + lng;
}
else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:n" + latLongString);
}
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.paad.whereami"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
/>
</manifest>
Accoding to the documentation, it returns null, if the device is not aware of the last known location. Probably the GPS can not locate you. It takes about a minute, anyway. So try to go outside, under the clear sky, away from tall buildings, and wait until GPS can locate you. Probably this helps. And don't forget the permissions. If you try to use GPS_PROVIDER
, you don't need internet access, nor network state.
EDIT:
To get the GPS work on the emulator, see this link.
For whom is still trying to understand the stupid function "getLastKnownLocation".
This function only returns something while the GPS is being used by another application. Therefore, it will return null 90% of the time unless you constantly use GPS for other apps. I have been testing this on an emulator and my own Android phone. I start getting results while using a mock location app to change the coordinates every 5 seconds but as soon as i stop the mock location app I start getting the null result.
链接地址: http://www.djcxy.com/p/90642.html