首先将通过GPS获取地理位置的权限添加到manifest中:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
支持GPS的核心API:locationmanager,locationprovider,location。
核心代码:
LocationManager lManager;
…..
lManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//***************条件筛选,criteria类似一个筛选器
Criteria criteria = new Criteria();
criteria.setCostAllowed(false);//功能必须免费
criteria.setAltitudeRequired(true);//可以获取高度信息
criteria.setBearingRequired(true);//可以获取方向信息
//获取所有可用(或者满足条件筛选的)locationprovider
List<String> strings = lManager.getAllProviders();
tView.setText(strings.toString());
//********************************
//获取指定的locationprovider
LocationProvider locationProvider = lManager.getProvider(LocationManager.GPS_PROVIDER);
//*******************************
Location location = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updaetView(location);
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
updaetView(null);
}
@Override
public void onProviderDisabled(String provider) {
updaetView(lManager.getLastKnownLocation(provider));
}
@Override
public void onLocationChanged(Location location) {
updaetView(location);
}
});
}
public void updaetView(Location newlocation){
if(newlocation != null){
tView1.setText("经度:"+newlocation.getLongitude());
tView2.setText("纬度:"+newlocation.getLatitude());
tView3.setText("高度:"+newlocation.getAltitude());
tView4.setText("速度:"+newlocation.getSpeed());
tView5.setText("方向:"+newlocation.getBearing());
}else {
tView1.setText("经度:");
tView2.setText("纬度:");
tView3.setText("高度:");
tView4.setText("速度:");
tView5.setText("方向:");
}
}
当然,上述代码在手机上偶尔并没有获取到自己的地理位置,可能是手机GPS的问题,具体情况不详