我在做的一个功能是过几分钟就提交一次坐标到服务器,进行保存,跟踪司机地理位置。
主线程:
private static final String CONTEXT = Context.LOCATION_SERVICE; // 环境
LocationManager locationManager;
/** 获得LocationManager实例 */
public LocationManager getLocationManager() {
return (LocationManager) getSystemService(CONTEXT);
}
onCreate方法:
{
Thread t = new Thread(new getLocation(provider));
t.setDaemon(true);// 设置为后台线程
t.start();
}
Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
LocationManager l = getLocationManager();
try {
String provider1 = getProvider(getLocationManager());
TimeUnit.MICROSECONDS.sleep(100);
l.requestLocationUpdates(provider1, 0, 0, locationListener);
Location location = l.getLastKnownLocation(provider1);
//打印效果。
System.out.println(location.getLatitude()
+ "{}{}{}{}{}{}{}{}___");
// 为绘制标志的类设置坐标,非常重要,刷新Location
mapOverlay.setLocation(location);
Thread t = new Thread(new getLocation(provider1));
t.start();
Thread.yield();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.handleMessage(msg);
}
};
private class getLocation implements Runnable {
@Override
public void run() {
Message m = new Message();
h.handleMessage(m); // Handler的实例
Thread.yield();
}
}
getLocation 和handler 这2个线程,让他们相互调用,形成死循环状态。
mapOverlay.setLocation(location); 这个方法太重要了。。。
程序总是出现在线程错误,不知道哪位大侠能够指点下原因:
下面是截图