2014-12-19 109 views
1

我想通過GPS獲取用戶位置,如果GPS無法在30秒內連接到衛星,那麼我想通過LocationManager.getLastKnownLocation()獲取位置。Android獲取位置

我可以完成這兩項工作(即通過GPS獲取位置和從最後一個已知位置獲取位置),但我不知道如何使用計時器(即在30秒內)完成此操作。我聽說可以通過使用Handler s或Java Timer類來完成。但我不明白這一點。

回答

2

設置一個布爾gotLocation = true當你從GPS獲得位置:

public void onLocationChanged(Location location){ 
    if(location != null){ 
     gotLocation = true; 
    } 
} 

當你做出這樣requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

您的要求添加低於Handler 30秒的延遲是這樣的:

new Handler().postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      if(!gotLocation){ 
       // get your last known location... 
      } 
     } 
}, 30000); 
+0

簡單,有用。謝謝Carnal – theapache64 2014-12-19 10:12:51

+0

任何時間隊友! :) – Carnal 2014-12-19 10:14:06

0

您可以使用處理程序的postdelay方法來執行計時器。 嘗試

final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    final LocationListener listener = new LocationListener() { 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
     } 

     @Override 
     public void onLocationChanged(Location location) { 
     } 
    }; 

    HandlerThread handlerThread = new HandlerThread("getLocation"); 
    handlerThread.start(); 
    Handler handler = new Handler(handlerThread.getLooper()); 

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, listener, handlerThread.getLooper()); 
    handler.postDelayed(new Runnable() { 

     @Override 
     public void run() { 
      locationManager.removeUpdates(listener); 
     } 
    }, 30 * 1000);