1.User Location
- 获取用户的位置
- 追踪用户的移动
2.User Location的API
1.LocationManager :用于管理android的用户定位服务
2.LocationProvider :提供多种定位方式给开发者选择
3.LocationListener : 监听位置是否改变,provider是否可用或改变等信息
4.LocationProvider(定位方式的分类)
1.GPS定位:
使用GPS卫星进行定位,需要在清单文件中添加权限:android.permission.ACCESS_FINE_LOCATION
2.NetWork定位:
使用信号接收塔和WI-FI介入点进行定位,需要在清单文件中添加权限:上面那个(推荐)或
android.permission.ACCESS_COARSE_LOCATION
3.LocationManager类
构造方法:Activity.this.getSystemService(LOCATION_SERVICE);
静态成员变量:String provider="GPS_PROVIDER";//Name of the GPS location provider
String provider="NETWORK_PROVIDER";//Name of the network location provider
5.代码步骤
1.在清单文件中添加权限:android.permission.ACCESS_FINE_LOCATION
2.获取LocationManager对象:
LocationManager locationManager = (LocationManager)MainActivity.this.getSystemService(Context.LOCATION_SERVICE);
3.选择LocationProvider:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener());
4.绑定LocationListener对象:
LocationListener接口:
onLocationChanged(Location location);
onProviderDisabled(String provider);
onProviderEnabled(String provider);
onStatusChanged(String provider, int status, Bundle extras) ;
public class MainActivity extends Activity { /** Called when the activity is first created. */ private Button button = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button)findViewById(R.id.locationButtonId); button.setOnClickListener(new ButtonListener()); } private class ButtonListener implements OnClickListener{ @Override public void onClick(View v) { //得到LocationManager对象 LocationManager locationManager = (LocationManager)MainActivity.this.getSystemService(Context.LOCATION_SERVICE); //1.定义当前所使用的Location Provider locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new TestLocationListener()); } } private class TestLocationListener implements LocationListener{ @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub System.out.println(location.getLongitude()); System.out.println(location.getLatitude()); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } }
6.Criteria
//生成一个Criteria对象 Criteria criteria = new Criteria(); //设置查询条件 criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setAltitudeRequired(false); criteria.setSpeedRequired(false); criteria.setCostAllowed(false); //false是指不能该provider是否已启用都返回出来 String provider = locationManager.getBestProvider(criteria, false);
7.