문제

I'm struggling with this Looper in Android. I have a timer that runs every minute. This sends a message to the server with the user's 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) {
        }
    };

The first time the timer fires, everything works perfectly. The second time, the timer freezes and the GPS icon on the phone says it has a lock but does not go away. It's as if the Looper is not looping to handle the messages the second time around, even though I tell it to loop. If I call Looper.prepare() every time, the second time the timer executes I get the exception saying only one Looper per thread.

Surely this shouldn't be so hard!

도움이 되었습니까?

해결책

Not the best way, but when the timer ticks, it creates a new Thread on which to get the current location and then send that info to the server. In this way each thread will will gets its own Looper which fixes my problem. As I said, not the best, but the timer does have other work to do.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top