线程处理程序使监听器不起作用

时间:2013-06-20 06:05:58

标签: android listener handler

我试图通过代码获取用户的当前位置,基本想法是这样的:

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中等待 enter image description here 所以如果新的gps位置更新到来,那么听众就不再工作了。

有没有办法让听众再次工作?非常感谢你。

0 个答案:

没有答案