2012-05-29 39 views
0

我正在編寫一個需要用戶當前位置的Android應用程序。我註冊了位置更新均來自網絡,以及GPS使用下面的代碼(的LocationManager已被定義):何時註冊位置更新?

// Register the listener with the Location Manager to receive location updates. 
    locationManager.requestLocationUpdates(
      LocationManager.NETWORK_PROVIDER, 
      getResources().getInteger(R.integer.gps_min_time), 
      getResources().getInteger(R.integer.gps_min_dist), this); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
      getResources().getInteger(R.integer.gps_min_time), 
      getResources().getInteger(R.integer.gps_min_dist), this); 

我目前在onCreate這段代碼,但爲了節省電力,我刪除這兩個監聽器在並將它們再次添加到onResume

當應用程序啓動時,它將兩次偵聽器添加兩次,一次在onCreate中,一次在onResume中。我有兩個關於這個問題:

  1. 每個聽衆添加兩次是否意味着它實際上被添加兩次,或者第二次調用沒有效果?
  2. 我應該從onCreate中刪除requestLocationUpdate,並讓它們在onResume中,或者我應該先刪除所有聽衆,然後再添加它們,然後再刪除所有聽衆:onResume

回答

1
  1. 您的監聽器將作爲密鑰添加到Hashmap中。所以如果你插入this(你的活動)並且不覆蓋equals它應該被覆蓋,並且沒有效果,因爲它是相同的監聽器。

  2. 無論如何,我會刪除onCreate內部的寄存器,並將其留在onResume中,因爲您至少可以節省哈希偵聽器和方法調用的時間。

1

我只是將它們添加到onResume()。在onCreate()中創建管理器,然後在onResume()onPause()中添加和刪除偵聽器。

我沒有第一個問題的答案。

+1

答案對第一個問題可以[在源代碼中發現(http://gitorious.org/android-eeepc/base/blobs/56fe6be0c3e1eaa7d5d1ba96910008c504a6c362/services/java/com/android/server/ LocationManagerService.java) – Reno