Android位置侦听器经常调用

Vic*_*iuk 4 android locationlistener

我正在使用网络位置提供商.我需要每隔 1小时从我的LocationListener调用一次onLocationChanged方法.这是我的代码:

MyLocationListener locationListener = new MyLocationListener();   
locationMangaer.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3600000, 0,locationListener);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我onLocationChanged经常打电话.

我必须使用哪些参数?

Sam*_*Sam 11

LocationManager#requestLocationUpdates()文档:

在Jellybean之前,minTime参数只是一个提示,一些位置提供程序实现忽略了它.从Jellybean开始,Android兼容设备必须同时观察minTime和minDistance参数.

但是,您可以使用requestSingleUpdate()Looper和Handler一小时运行一次更新.


添加
要开始,您可以在此处阅读有关Loopers和Handlers的更多信息.

您正在使用API​​ 8,这是一个不错的选择,但这限制了我们可以调用的LocationManager方法,因为大多数是在API 9中引入的.API 8只有这三种方法:

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent)
Run Code Online (Sandbox Code Playgroud)

让我们使用第一种方法,它是最简单的.

首先,像往常一样创建LocationManager和LocationListener,但是onLocationChanged() 停止请求更多更新:

@Override
public void onLocationChanged(Location location) {
    mLocationManager.removeUpdates(mLocationListener);
    // Use this one location however you please
}
Run Code Online (Sandbox Code Playgroud)

其次,创建一些新的类变量:

private Handler mHandler = new Handler();
private Runnable onRequestLocation = new Runnable() {
    @Override
    public void run() {
        // Ask for a location
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
        // Run this again in an hour
        mHandler.postDelayed(onRequestLocation, DateUtils.HOUR_IN_MILLIS);
    }
};
Run Code Online (Sandbox Code Playgroud)

当然,您应该禁用所有回调onPause()并再次启用它们,onResume()以防止LocationManager通过在后台获取未使用的更新来浪费资源.


更技术性的观点:
如果您担心使用LocationManager阻止UI线程,那么您可以使用第二种requestLocationUpdates()方法从新线程(例如HandlerThread)提供特定的Looper.