结果
<uses-permission android:name="android.permission.INTERNET" />
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
private static final String TAG = "Main";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String serviceString = Context.LOCATION_SERVICE;
LocationManager locationManager = (LocationManager)getSystemService(serviceString);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
getLocationInfo(location);
locationManager.requestLocationUpdates(provider,2000,0,locationListener);
}
private void getLocationInfo(Location location){
String locationInfo;
TextView locationText = (TextView)findViewById(R.id.locationInfoText);
if(location != null){
double latitude = location.getLatitude(); //获取经纬度
double longitude = location.getLongitude();
locationInfo = "Latitude:" + latitude + "\nLongitude:" + longitude;
}else {
locationInfo = "No location found";
}
locationText.setText("Your currentPosition is :\n" + locationInfo);
}
private final LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
getLocationInfo(location);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
};
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/locationInfoText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>