我正在尝试为我的应用程序使用 GPS 提供程序。
该应用程序使用 GPS 位置提供程序查找设备的当前位置。
该应用程序运行良好。但是,虽然我的 GPS_Provider 已启用,但geLastKnownLocation()
返回 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);
}
}
清单.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>