Java Android TimerTask将冻结gps位置
我在安卓系统中与这个活套搏斗。我有一个每分钟运行的计时器。这将向服务器发送一条包含用户位置的消息Java Android TimerTask将冻结gps位置,java,android,timer,gps,locationmanager,Java,Android,Timer,Gps,Locationmanager,我在安卓系统中与这个活套搏斗。我有一个每分钟运行的计时器。这将向服务器发送一条包含用户位置的消息 private Looper looper; public boolean getLocation(Context context, LocationResult result) { locationResult = result; lm = (LocationManager) context.getSystemService(Context.LOCATION
private Looper looper;
public boolean getLocation(Context context, LocationResult result) {
locationResult = result;
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled)
return false;
if(Looper.myLooper() == null)
Looper.myLooper().prepare();
looper = Looper.myLooper();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
looper.loop();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
looper.quit();
lm.removeUpdates(this);
locationResult.gotLocation(location); // broadcast location
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
计时器第一次启动时,一切正常。第二次,计时器冻结,手机上的GPS图标显示它有锁,但不会消失。这就好像循环器在第二次处理消息时没有循环,即使我让它循环。如果每次调用Looper.prepare(),第二次执行计时器时,会出现异常,表示每个线程只有一个Looper
当然这不应该这么难 这不是最好的方法,但当计时器计时时,它会创建一个新线程,在该线程上获取当前位置,然后将该信息发送到服务器。通过这种方式,每个线程都将获得自己的循环器,从而解决我的问题。正如我所说,这不是最好的,但计时器还有其他工作要做