2014-12-19 150 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);