Skip to content Skip to sidebar Skip to footer

Get Location Updates After Gps Enabled By User

I have a simple App which currently simply asks for necessary permissions and in case GPS is OFF, you get an AlertDialog asking you if you want to switch it ON. After accepting, be

Solution 1:

I've developed fused location api demo application and utility pack here.

General Utilities

Try it if useful for you. To get location using fused location api, you just have to write following snippet...

newLocationHandler(this)
    .setLocationListener(newLocationListener() {
    @OverridepublicvoidonLocationChanged(Location location) {
        // Get the best known location
    }
}).start();

And if you want to customise it, simply find documentation here...

https://github.com/abhishek-tm/general-utilities-android/wiki/Location-Handler

I've written a sample code according to your need, this will handle GPS enable/disable dialog internally, try this one...

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;

import in.teramatrix.utilities.service.LocationHandler;
import in.teramatrix.utilities.util.MapUtils;

/**
 * Lets see how to use utilities module by implementing location listener.
 *
 * @author Khan
 */publicclassMainActivityextendsAppCompatActivityimplementsOnMapReadyCallback, LocationListener {

    private GoogleMap map;
    private Marker marker;
    private LocationHandler locationHandler;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Obtaining an instance of mapFragmentManagermanager= getSupportFragmentManager();
        SupportMapFragmentmapFragment= (SupportMapFragment) manager.findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        this.locationHandler = newLocationHandler(this)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(5000)
                .setFastestInterval(10000)
                .setLocationListener(this);
    }

    @OverridepublicvoidonMapReady(GoogleMap map) {
        this.map = map;
        this.locationHandler.start();
    }

    @OverridepublicvoidonLocationChanged(Location location) {
        LatLnglatLng=newLatLng(location.getLatitude(), location.getLongitude());
        if (marker == null) {
            marker = MapUtils.addMarker(map, latLng, R.drawable.ic_current_location);
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 500, null);
        } else {
            marker.setPosition(latLng);
        }
    }

    @OverrideprotectedvoidonDestroy() {
        super.onDestroy();
        if (locationHandler != null) {
            locationHandler.stop();
        }
    }

    @OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationHandler.REQUEST_LOCATION) {
            locationHandler.start();
        }
    }
}

Hope it will help you.

Solution 2:

Your current code doesn't wait for the user to make a choice before calling getLatLon() in the case where GPS is disabled.

You will need to add a onActivityResult() override that will be called when the user goes back to your app.

First, remove the call to getLatLon() in the checkGPS() method for the case where GPS is disabled:

privatevoidcheckGPS() {
    manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        final AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
        builder.setMessage(R.string.GPS_error)
                .setCancelable(false)
                .setPositiveButton(R.string.confirm, newDialogInterface.OnClickListener() {
                    publicvoidonClick(@SuppressWarnings("unused")final DialogInterface dialog, @SuppressWarnings("unused")finalint id) {
                        Intentgps=newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(gps, 1);
                        //Remove this://getLatLon();
                    }
                })
                .setNegativeButton(R.string.deny, newDialogInterface.OnClickListener() {
                    publicvoidonClick(final DialogInterface dialog, @SuppressWarnings("unused")finalint id) {
                        dialog.cancel();
                    }
                });
        finalAlertDialogalert= builder.create();
        alert.show();
    } else {
        getLatLon();
    }
}

Then, add the onActivityResult() override, check the setting again, and if it's now enabled then call getLatLon():

@OverridepublicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        getLatLon();
    }
}

Solution 3:

after some time busy with other projects, got back to this one and I removed the getLatLon(); function from the checkGPS(); function and that's it, code is fine. I was using the emulator to check if this was working, but I forgot that the emulator has a fixed value for the latitude and longitude, so you get no updates like a real mobile phone, and thus it looked as if it was not working properly.

Sort of a newby mistake. Regardless, thanks for your offers. Was interesting looking at different ways of doing the same thing.

Sartox

Post a Comment for "Get Location Updates After Gps Enabled By User"