2017-03-02 74 views
1

我必須在退出時更新geoFence。爲此,我需要當前的位置。獲取Geofence上的當前位置.GEOFENCE_TRANSITION_EXIT

當我的應用程序被關閉我沒有偵聽onLocationChanged。並且爲了 更新geoFence我需要我的位置。是他們的任何方式MainActivity

private BroadcastReceiver receiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Bundle bundle = intent.getExtras(); 
      if (bundle != null) { 
       int resultCode = bundle.getInt("done"); 
       if (resultCode == 1) { 

        if(!MainActivity.isGeoFenceAdded){ 
         updateGeoFencesOnCurrentExit();//I need current location here 
        } 
       } 
      } 
     } 
    }; 

每一件事做工精細,以獲得當前位置在Geofence.GEOFENCE_TRANSITION_EXIT

public void broadcastUpdateGeoFences() { 
     MainActivity.isGeoFenceAdded = false;//It tells to update geoFence 
     Intent intent = new Intent(Constants.RECEIVER_GEOFENCE); 
     intent.putExtra("done", 1); 
     sendBroadcast(intent); 
    } 

廣播接收器。但是當應用程序關閉時,無法找到在退出時通過currentLocation的方法。

private void updateGeoFencesOnCurrentExit(Location currentLocation){ 
      locationHandler.updateGeoFences(currentLocation); 
} 
+0

您是否在使用Intent服務? – mechdon

+0

是的,我知道它應該是廣播接收器 – Nepster

+0

您的實際添加地理位置請求在哪裏? –

回答

0

可以實現LocationListener的界面在你的廣播和使用覆蓋的方法OnLocationChanged這樣

@Override 
public void onLocationChanged(Location location) { 
    location.getLongitude(); 
    location.getLatitude(); 
} 
0

我不建議使用IntentService或廣播接收器內的LocationListener的,因爲它們可以一次被銷燬函數(onHandleIntent或onReceive)已退出。我將使用LocationManager中的PendingIntent在獲取地理圍欄事件後請求單個更新。我有示例應用程序來演示如何使用github上的PendingIntent請求位置更新(https://github.com/pablobaxter/AndroidLocationExamples)。

編輯:

僅供參考,IntentService沒有錯。您只是在後臺線程中運行onHandleIntent邏輯,而在主線程上運行onReceive