2

I was playing a bit around the new location API from google (to get latitude and longitude values):

private void getLastLocation(){
    FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    try {
        mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    Toast.makeText(getApplicationContext(), String.valueOf(latitude) + "/" + String.valueOf(longitude), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Cannot get location", Toast.LENGTH_LONG).show();
                }
            }
        })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d("LocationFetch", "Error trying to get last GPS location");
                        e.printStackTrace();
                    }
                });
    } catch (SecurityException e){
        Log.d("LocationFetch", "Permission missing");
    }
}

When I first tested this code, the location was always returning null. However, after opening Instagram (which did a location update on my phone - the geo icon appeared briefly), the location was returning my relevant longitude and latitude values.

How do I request a location update on my app using the new API to prevent location from being null or retrieve very old locations? (getLastLocation() is not enough, possibly LocationRequest?)

It is worth noting that I do not want interval updates, I want for it to happen within an Android Service when invoked once.

bashbin
  • 415
  • 1
  • 7
  • 21
  • use GPSTracker its very essay – suresh madaparthi Nov 15 '18 at 05:20
  • Check this url may be it will help's you https://javapapers.com/android/android-location-fused-provider/ – Rashpal Singh Nov 15 '18 at 05:21
  • Take a look here https://stackoverflow.com/questions/53300064/how-to-get-current-location-and-not-last-location/53300121#53300121 and here https://stackoverflow.com/questions/53276698/android-my-app-can-get-location-information-until-opening-google-maps-although/53276863#53276863 – Vadim Eksler Nov 15 '18 at 06:24
  • Basically you need to create your own location request. Because getLastLocation tries to get location from other apps, and if it exist you will get null. – Vadim Eksler Nov 15 '18 at 06:26

3 Answers3

2

Firstly add this implementation in your build.gradle file

implementation 'com.google.android.gms:play-services-location:11.2.0'//include the latest version of play services

After that implement, (implements LocationListener) in your activity or fragment and after that implement its function and then

call this method in your onCreate() getLocation(); and then in this function add these lines

protected void getLocation() {
    if (isLocationEnabled(MainActivity.this)) {
        locationManager = (LocationManager)  this.getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();

        //You can still do this if you like, you might get lucky:
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            Log.e("TAG", "GPS is on");
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
            searchNearestPlace(voice2text);
        }
        else{
            //This is what you need:
            locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
        }
    }
    else
    {
        //prompt user to enable location....
        //.................
    }
}

After that in your onLocationChanged(Location location) add these lines of code

@Override
public void onLocationChanged(Location location) {
    //Hey, a non null location! Sweet!

    //remove location callback:
    locationManager.removeUpdates(this);

    //open the map:
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
    searchNearestPlace(voice2text);
}

and you are set to go!!!! Cheers Happy Coding

2

It's work for me. Based on Official docs, every 10 seconds updates the Toast and shows your location:

private FusedLocationProviderClient fusedLocationClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;



@Override
protected void onResume() {
    super.onResume();
    startLocationUpdates();

}

private void startLocationUpdates() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }
    }
    fusedLocationClient.requestLocationUpdates(locationRequest,
            locationCallback,
            Looper.getMainLooper());
}

@Override
protected void onPause() {
    super.onPause();
    stopLocationUpdates();
}

private void stopLocationUpdates() {
    fusedLocationClient.removeLocationUpdates(locationCallback);
}

add bellow codes to onCreate method:

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(2*5000);

    locationCallback=new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
               // if (location != null) {


                    String Lat = String.valueOf(location.getLatitude());
                    String Lon = String.valueOf(location.getLongitude());

                    Toast.makeText(getApplicationContext(), Lat + " - " + Lon, Toast.LENGTH_SHORT).show();
            //    }
            }
        }
    };
vahid sabet
  • 485
  • 1
  • 6
  • 16
0

Try this code.

In gradle

implementation 'com.google.android.gms:play-services-location:16.0.0'

In code

 private void turnGPSOn() {
    LocationRequest mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)
            .setFastestInterval(1 * 1000);

    LocationSettingsRequest.Builder settingsBuilder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    settingsBuilder.setAlwaysShow(true);

    Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
            .checkLocationSettings(settingsBuilder.build());

    result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
        @Override
        public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
            try {
                LocationSettingsResponse response =
                        task.getResult(ApiException.class);

                if (gps.canGetLocation()) {
                    lat = String.valueOf(gps.getLatitude());
                    lon = String.valueOf(gps.getLongitude());
                }

            } catch (ApiException ex) {
                switch (ex.getStatusCode()) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            ResolvableApiException resolvableApiException =
                                    (ResolvableApiException) ex;
                            resolvableApiException
                                    .startResolutionForResult(SignupActivity.this,
                                            REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {

                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                        break;
                }
            }
        }
    });
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Athira
  • 1,177
  • 3
  • 13
  • 35