2011-12-11 52 views
0

由於某些原因,在requestLocationUpdates()方法之後添加removeUpdates()時,我根本沒有獲取任何位置數據。我沒有正確取消訂閱嗎?在獲取位置數據後從LocationManager中取消訂閱LocationListener

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
LocationListener mlocListener = new MyLocationListener(); 
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1, mlocListener); 
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, mlocListener); 
mlocManager.removeUpdates(mlocListener); 


public class MyLocationListener implements LocationListener 
    { 
     @Override 
     public void onLocationChanged(Location loc) 
     { 
      loc.getLatitude(); 
      loc.getLongitude(); 
      String text = "My current location is: " + 
      "Latitude = " + loc.getLatitude() + 
      "Longitude = " + loc.getLongitude(); 
      System.out.println("FINISHED:"); 
      Toast.makeText(getApplicationContext(), 
        text, 
        Toast.LENGTH_SHORT).show(); 

     } 
} 

回答

-1

我最終在LocationHandler的內部創建了一個Thread,嵌套的while保持循環,直到找到GPS位置。當發現我取消訂閱我的LocationListener

+0

我見過的最髒的東西之一:( – FlorianB

0

This可能會有所幫助。

您取消訂閱您獲取了位置數據,即在onLocationChanged方法中表示。

+0

我明白你的意思,但是我沒有訪問'onLocationChanged()'方法中的'removeUpdates()'方法 – Neeta

+0

聲明'mlocManager'作爲final,那麼你就可以通過' removeUpdates'。 – Jong

+0

我的意思是它在不同的類中聲明,將它公開是不好的做法。 – Neeta

1

您可以嘗試製作一種方法,並在其中執行removeUpdates()。並在獲得數據後從onLocationChanged()調用它。

+0

你的意思是將額外的方法放在'myLocationListener'或調用'myLocationListener'的類中? – Neeta

+0

我的意思是在你的活動或課堂上。使一個方法,並把mlocManager.removeUpdates(mlocListener);在方法的身體。現在獲得您的位置和數據後,從那裏調用該方法,並完成它:)。 –