Android LocationManager 使用

前一陣子,老大安排我寫一個GPS的程序。大體就是用Android 提供的Location 服務,來得到當前的位置信息和衛星信息。這裏就用到了LocationManager類,要使用它,先得得到系統所提供的location_serviceide

private LocationManager locationManager;rem

locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);get

 

要實時的獲得位置信息,得註冊一個location的listener。it

private LocationListener locationListener;io

locationManager.requestLocationUpdates(「gps」, 1000, 0, locationListener); 每秒更新位置信息,不考慮距離變化。event

locationManager.removeUpdates(locationListener); 移除listenerast

在使用這個locationListener以前,還得先new一下,在位置信息更新時要作的操做均可以在這裏實現date

locationListener = new LocationListener()List

{
       // implement necessary methods
       public void onLocationChanged(Location location) 
       {
            // TODO Auto-generated method stubservice

            位置信息更新
        }

       public void onProviderDisabled(String provider) 
       {
        // called when the provider be disabled by user


       }

       public void onProviderEnabled(String provider) 
       {
        // called when the provider be enabled
        }

       public void onStatusChanged(String provider, int status, Bundle extras) 
       {
        // TODO Auto-generated method stub

         provider狀態改變
        }
      };

 

要獲得位置信息,也能夠單獨調用getLastKnownLocation

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

位置信息中包含着 經緯度,高度,速度,UTC時間,定位精度等有用的信息。

 

獲得了位置信息,下面來看衛星信息。Android下提供了GpsStatus這個類,經過調用此類的一個method  getSatellites() ,能夠獲得接收到的衛星的信息列表Iterable<GpsSatellite> 。固然這些操做也是在一個listener當中來作的:GpsStatus.Listener。GpsStatus的listener也是註冊於locationManager:
private GpsStatus.Listener statusListener;

locationManager.addGpsStatusListener(statusListener);

locationManager.removeGpsStatusListener(statusListener);

 

初始化並實現更新時相應的操做:

private GpsStatus gpsStatus;

statusListener = new GpsStatus.Listener() 

{
    public void onGpsStatusChanged(int event) 
    {
     // TODO Auto-generated method stub
     gpsStatus= locationManager.getGpsStatus(null);
     
     switch(event)
     {
     case GPS_EVENT_FIRST_FIX:
              //第一次定位時間UTC

              gpsStatus.getTimeToFirstFix();     

      break;
      
     case GPS_EVENT_SATELLITE_STATUS:

             //獲得全部收到的衛星的信息,包括 衛星的高度角、方位角、信噪比、和僞隨機號(及衛星編號)
      Iterable<GpsSatellite> allSatellites;
      allSatellites = gpsStatus.getSatellites();
     
      break;
      
     case GPS_EVENT_STARTED:
             //Event sent when the GPS system has started.

     break;
      
     case GPS_EVENT_STOPPED:
            //Event sent when the GPS system has stopped. 
      break;
      
     default :
      break;
     }
    }

};

相關文章
相關標籤/搜索