GPS和Network定位各有优劣:
GPS定位精确,但耗电耗时;Network则相反,低能耗且定位迅速,但定位误差较大。
非导航类的,一般用Network定位已经足够了。
开启定位服务:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
设置一个监听:
LocationListener listener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("latitude", String.valueOf(latitude));
Log.i("longitude", String.valueOf(longitude));
locationText.setText("latitude:" + String.valueOf(latitude)
+ "\n" + "longitude:" + String.valueOf(longitude));
}
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
Register for location updates using the named provider, and a pending intent.
Parameters
provider | the name of the provider with which to register |
---|---|
minTime | minimum time interval between location updates, in milliseconds |
minDistance | minimum distance between location updates, in meters |
listener | a LocationListener whose onLocationChanged(Location) method will be called for each location update |
最后添加权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
这个代表获取设备的大概位置,如果使用GPS定位或两者结合定位,则用下面的精确定位权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)