2013-09-24 68 views
0

此代碼:LocationManager,GPS和網絡提供商..都被觸發了嗎?

ServiceListener mlistener = new SosServiceListener(getApplicationContext()); 

manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

manager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlistener, null); 
manager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, mlistener, null); 

連接監聽器一次兩個事件。事實是:如果兩個事件都被觸發,那麼這個監聽器會被調用兩次?如果是的話,你會如何預防它?

謝謝!

+0

僅用於if-else循環創建... – WISHY

+0

爲網絡提供者和其他GPS提供者創建兩個diff偵聽器,並讀取兩個結果。根據您的興趣,您可以取消/停止列出GPS或網絡提供商。 – user755

回答

1

這是我用我的項目之一,是完美的工作:

public Location getLocation() { 
     try { 
      mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
        if (mLocationManager != null) { 
         location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          lat = location.getLatitude(); 
          lng = location.getLongitude(); 
         } 
        } 
       } 
       //get the location by gps 
       if (isGPSEnabled) { 
        if (location == null) { 
         mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (mLocationManager != null) {location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           lat = location.getLatitude(); 
           lng = location.getLongitude(); 
          } 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return location; 
    } 
+0

感謝您的答案:) – Filnik

+0

是這些常量定義的地方,或者我可以設置我的價值,因爲我認爲合適?如果是這種情況,我應該給他們分配什麼樣的價值? – Libathos

+0

這裏沒有常量,lat和lng是雙變量,isGPSEnabled和isNetworkEnabled是初始設置爲false的布爾變量,mLocationManager是LocationManager的實例。 – TharakaNirmana

相關問題