2013-04-22 93 views
0

我想寫一個位置跟蹤服務,一旦應用程序啓動就立即啓動,一旦應用程序進入後臺就會停止,並在應用程序返回到應用程序後立即重新啓動前景。Android - 最佳位置跟蹤策略

服務應該每運行5分鐘輪詢一次新的位置(以節省電池),並且當找到新的位置(onLocationChanged())時,它會更新我可以從任何Activity檢索到的變量。

我已經嘗試綁定我的自定義應用程序類中的服務,但服務從未在我的初始活動加載之前被綁定 - 並且我的初始活動需要此服務,因此在嘗試訪問服務時不斷收到空指針異常。

但也許我會走錯方向 - 對此最好的策略是什麼?我不需要一個超級精確的位置,我不關心它是來自GPS還是網絡。

+0

你需要的onCreate的位置? – 2013-04-23 07:35:11

+0

我能夠改變我的代碼,以便它將等待某些事情,直到服務正式綁定,但現在我不能想出停止此服務時用戶離開應用程序的好方法 – shiznatix 2013-04-23 12:26:15

回答

0

下面的代碼爲我工作...

你會得到任何你想要的位置,只是用它明智地...

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

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

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

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network Enabled"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

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

    return location; 
} 
+0

我已經使用過但我想擺脫它,因爲它只在我即將使用它時獲取數據 - 可能會給不好的位置。我希望每5分鐘輪詢一次數據,並堅持到它,直到我需要它爲止。我通過在MyApplication類中綁定了一個服務來解決它,但是我沒有找到如何在按下home按鈕時停止服務(app在後臺)。 – shiznatix 2013-04-22 12:35:14

+0

嗨shiznatix,我也在尋找更新背景中的位置。你可以請分享一些代碼來獲取後臺位置更新嗎? – Karthick 2013-10-04 07:12:49