Skip to content Skip to sidebar Skip to footer

Android Onlocationchanged And Mainactivity Class

I have the following code: public class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { // called when the listener i

Solution 1:

You may use the following sample code:

publicclassLocationGetter {
    privatefinal Context context;
    privateLocationlocation=null;
    privatefinalCordinategotLocationLock=newCordinate();
    privatefinalLocationResultlocationResult=newLocationResult() {
        @OverridepublicvoidgotLocation(Location location) {
            synchronized (gotLocationLock) {
                LocationGetter.this.location = location;
                gotLocationLock.notifyAll();
                Looper.myLooper().quit();
            }
        }
    };

    publicLocationGetter(Context context) {
        if (context == null)
            thrownewIllegalArgumentException("context == null");

        this.context = context;
    }

    publicvoidgetLocation(int maxWaitingTime, int updateTimeout) {
        try {
            finalintupdateTimeoutPar= updateTimeout;
            synchronized (gotLocationLock) {
                newThread() {
                    publicvoidrun() {
                        Looper.prepare();
                        LocationResolverlocationResolver=newLocationResolver();
                        locationResolver.prepare();
                        locationResolver.getLocation(context, locationResult, updateTimeoutPar);
                        Looper.loop();
                    }
                }.start();

                gotLocationLock.wait(maxWaitingTime);
            }
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        gteAddress ();
    }


publicdoublegetLatitude() {
    return location.getLatitude();
}

publicdoublegetLongitude() {
    return location.getLongitude();
}

In your activity use:

_locationGetter=newLocationGetter(context);

_locationGetter.getLocation(200000000, 10000000);

_locationGetter.getLongitude();

_locationGetter.getLatitude();

Solution 2:

You can also use LocationManager.removeUpdates after obtining the coordinates (and possibly checking if the coordinates are sufficient for your needs):

@Overridepublic void onLocationChanged(Location loc) {
        // called when the listener is notified with a location update from the GPS
        Log.d("Latitude", Double.toString(loc.getLatitude()));
        Log.d("Longitude", Double.toString(loc.getLongitude()));
        lm.removeUpdates(this);
    }

Post a Comment for "Android Onlocationchanged And Mainactivity Class"