Android的位置服务

来源:互联网 发布:天佑为什么这么火 知乎 编辑:程序博客网 时间:2024/05/03 14:28

    今天公司项目用到了位置服务,在完成这部分功能的时候遇到了一些问题,总结一下。

 推荐大家读一下adnroid api中的这篇文章 http://developer.android.com/guide/topics/location/strategies.html

   Android的位置服务可以通过GPS或Cell Tower andWi-FiSiginals (信号基站和wifi信号)来获取经纬度坐标。主要区别读一下上面那篇文章就清楚了。

    主要注意有两点:

   一. 获取LocationManager与注册监听器一定要在onCreate函数中进行,不然在获取最后的位置时将总是null的。

如果你有一个Button,在点击Button的事件中获取LocationManager对象与注册监听器,那么你调用LocationManager的getLastKnownLocation()方法将总是返回null值。

下面的这段代码要在onCreate函数中执行,其中LocationManager.NETWORK_PROVIDER是使用信号基站和wifi信号,然后还可以使用 LocationManager.GPS_PROVIDER

LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);// Define a listener that responds to location updatesLocationListener 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 updateslocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
这段代码可以在Button的点击事件中执行
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

二.关于同时使用cell tower/wifi与gps

    在程序中这两者都可以使用。怎么样同时使用,在文章中有这么一段话

    To request location updates from the GPS provider, substitute GPS_PROVIDER for GPS_PROVIDER . You can also request location updates from both the GPS and the Network Location Provider by callingrequestLocationUpdates() twice—once for NETWORK_PROVIDER and once for GPS_PROVIDER.

   只要你同时调用requestLocationUpdates( GPS_PROVIDER )与requestLocationUpdates(  NETWORK_PROVIDER )就可以了。

   一般GPS定位精确度比较高,但在室内可能获取不到信号,可以这样:

         Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER );

       if(location==null){

           location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER );

       }

      这样两种位置的获取方式你都可以使用了。

     不要忘了加权限与移除监听器。