所需权限:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
/**
*
* @author Administrator 获取定位信息
*/
public class LocationDemoActivity extends Activity {
private TextView tv;
//位置管理服务
private LocationManager locManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationdemo);
tv = (TextView) findViewById(R.id.tv);
//拿到位置管理服务
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//从GPS获取最近的定位信息
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateView(location);
//5000:每隔5s获取一次GPS位置信息
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 8, new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
//当GPS可用时,更新位置
updateView(locManager.getLastKnownLocation(provider));
}
@Override
public void onProviderDisabled(String provider) {
//当GPS不可用时
updateView(null);
}
@Override
public void onLocationChanged(Location location) {
//当GPS定位信息改变时,更新位置
updateView(location);
}
});
}
private void updateView(Location location) {
if (location != null) {
StringBuilder sb = new StringBuilder();
sb.append("经度:" + location.getLongitude());
sb.append("\n纬度:" + location.getLatitude());
tv.setText(sb.toString());
} else {
tv.setText("GPS 不可用,请打开GPS");
}
}
}