1.两种定位方式:GPS定位和android网络定位。其中android网络定位又包括信号塔和wifi。
2.易引起定位错误的几种情况:
- 多个位置信号来源
- 用户的移动
- 精度的区别
3.获取用户位置:
调用
LocationManager
的requestLocationUpdates()
方法来获得位置信息,并一个LocationListener
参数。LocationListener
需要实现一些用户位置改变时或者信号改变时会调用的方法。如:上边是使用网络来定位,也可以同时使用网络和GPS,只要调用两次// Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; // Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
requestLocationUpdates()
方法,一次GPS的,一次网络的。还需要添加下权限:
另外,最好<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
@Override public void onPause() { super.onPause(); //---remove the location listener--- lm.removeUpdates(locationListener); } @Override public void onResume() { super.onResume(); //---request for location updates--- lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locationListener); }
4.监控一个位置:
可以通过调用LocationManager的addProximityAlert()方法来监控位置(当用户接近在某个位置一定范围内就启动一个Intent)。
第一二个参数是指定坐标,第三个是范围,第4个是警报持续的时间,最后一个是要执行动作的相关信息。
如下面的代码就是在接近那个坐标点5米范围内打开百度:
PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, new Intent(android.content.Intent.ACTION_VIEW, Uri. parse(“http://www.baidu.com” )), 0); lm.addProximityAlert(37.422006, -122.084095, 5, -1, pendingIntent);
注意即使屏幕被关闭了,程序也会每四分中进行一次检测。