我试图通过代码获取用户的当前位置,基本思路是这样的:
public class LocationProducer extends Thread {
// Timer timer1;
LocationManager lm;
boolean gps_enabled = false;
UpdateInterface mUpdateInterface;
private Looper mThreadLooper;
private Handler mHandler;
public LocationProducer(Context context, UpdateInterface updateInterface,
String name) {
super(name);
mContext = context;
mUpdateInterface = updateInterface;
}
public void run() {
Looper.prepare();
if (lm == null)
lm = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
}
Log.d(TAG, "requestLocationUpdates int thread:"
+ Thread.currentThread().getName());
// timer1 = new Timer();
// timer1.schedule(new GetLastLocation(), MAXWAITTIME);
mThreadLooper = Looper.myLooper();
mHandler = new Handler();
mHandler.postDelayed(GetLastLocation, MAXWAITTIME);
Looper.loop();
}
public void quitLooper() {
lm.removeUpdates(locationListenerGPSLongTimeRun);
lm.removeUpdates(locationListenerNetworkLongTimeRun);
mThreadLooper.quit();
// mHandler.getLooper().quit();
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
Log.d(TAG,
"get location int short time run locationlistenerGPS, in thread"
+ Thread.currentThread().getName());
// timer1.cancel();
mHandler.removeCallbacks(GetLastLocation);
mUpdateInterface.update(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINUPDATETIME, MINUPDATEDISTANCE,
locationListenerGPSLongTimeRun);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MINUPDATETIME, MINUPDATEDISTANCE,
locationListenerNetworkLongTimeRun);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
基本思想是获取用户位置。我必须使用 looper 在非 UI 线程中注册一个监听器,但是当我得到这个循环的处理程序时。我发现线程只是等待,在 nativePollOnce 中, 所以如果新的 gps 位置更新到来,监听器就不再工作了。
有什么办法让听众再次工作?非常感谢您。