在android系统提供两种定位方式,NETWORK和GPS。
NETWORK在移动网络中获取位置,精度较低但速度很快。原理:通过手机获取附近基站或wifi节点数据,然后把手机把数据发给第三方Location Service Provider,然后LSP把数据转化成位置数据,返回给手机。The protocol between the device and the location service provider is HTTP POST. The request and response are both formatted as JSON.
GPS使用GPS卫星进行定位,精度很高但一般需要10-60秒时间才能开始第1次定位,在室内则基本上无法定位,耗电量大。
NETWORK得到的位置精度一般在500-1000米,GPS得到的精度一般在5-50米。
一般来说,先使用NETWORK来得到1个精度较差的位置,再使用GPS来得到更准确的位置。
在Android官方提供的Dev Guide中,提供了一个关于GPS使用的时间线,如下:
概括起来就是2句话:“快速反应,渐进式精确”。在实际的使用中也要根据自己的情况画1个时间线,好决定何时开始监听,何时结束监听。
在程序当中打开GPS
方法一:
private void initGPS(){
LocationManager locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//判断GPS模块是否开启,如果没有则开启
if(!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is not open,Please open it!", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivityForResult(intent,0);
}
else {
Toast.makeText(this, "GPS is ready", Toast.LENGTH_SHORT);
}
}
方法二:
private void toggleGPS() {
Intent gpsIntent = new Intent();
gpsIntent.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
gpsIntent.setData(Uri.parse("custom:3"));
try {
PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
}
catch (CanceledException e) {
e.printStackTrace();
}
}
自定义精度获取位置信息
private Location getLocation() {
LocationManager locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider=locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
return location;
}