Android - How to request location update in the new API?












0















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.










share|improve this question























  • use GPSTracker its very essay

    – suresh madaparthi
    Nov 15 '18 at 5:20











  • Check this url may be it will help's you javapapers.com/android/android-location-fused-provider

    – Rashpal Singh
    Nov 15 '18 at 5:21











  • Take a look here stackoverflow.com/questions/53300064/… and here stackoverflow.com/questions/53276698/…

    – Vadim Eksler
    Nov 15 '18 at 6: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 6:26
















0















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.










share|improve this question























  • use GPSTracker its very essay

    – suresh madaparthi
    Nov 15 '18 at 5:20











  • Check this url may be it will help's you javapapers.com/android/android-location-fused-provider

    – Rashpal Singh
    Nov 15 '18 at 5:21











  • Take a look here stackoverflow.com/questions/53300064/… and here stackoverflow.com/questions/53276698/…

    – Vadim Eksler
    Nov 15 '18 at 6: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 6:26














0












0








0








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.










share|improve this question














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.







java android






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 '18 at 5:17









bashbinbashbin

10510




10510













  • use GPSTracker its very essay

    – suresh madaparthi
    Nov 15 '18 at 5:20











  • Check this url may be it will help's you javapapers.com/android/android-location-fused-provider

    – Rashpal Singh
    Nov 15 '18 at 5:21











  • Take a look here stackoverflow.com/questions/53300064/… and here stackoverflow.com/questions/53276698/…

    – Vadim Eksler
    Nov 15 '18 at 6: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 6:26



















  • use GPSTracker its very essay

    – suresh madaparthi
    Nov 15 '18 at 5:20











  • Check this url may be it will help's you javapapers.com/android/android-location-fused-provider

    – Rashpal Singh
    Nov 15 '18 at 5:21











  • Take a look here stackoverflow.com/questions/53300064/… and here stackoverflow.com/questions/53276698/…

    – Vadim Eksler
    Nov 15 '18 at 6: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 6:26

















use GPSTracker its very essay

– suresh madaparthi
Nov 15 '18 at 5:20





use GPSTracker its very essay

– suresh madaparthi
Nov 15 '18 at 5:20













Check this url may be it will help's you javapapers.com/android/android-location-fused-provider

– Rashpal Singh
Nov 15 '18 at 5:21





Check this url may be it will help's you javapapers.com/android/android-location-fused-provider

– Rashpal Singh
Nov 15 '18 at 5:21













Take a look here stackoverflow.com/questions/53300064/… and here stackoverflow.com/questions/53276698/…

– Vadim Eksler
Nov 15 '18 at 6:24





Take a look here stackoverflow.com/questions/53300064/… and here stackoverflow.com/questions/53276698/…

– Vadim Eksler
Nov 15 '18 at 6: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 6:26





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 6:26












3 Answers
3






active

oldest

votes


















0














Use This Class



public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}

@SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);

// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
}

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}

/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
*
* @return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title
alertDialog.setTitle("GPS is settings");

// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

// Showing Alert Message
alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}


Use this method in Ur Activity Class



  double latitude, longitude;
private void getLocation() {
GPSTracker gps = new GPSTracker(this);
if (gps.canGetLocation()) {

latitude = gps.getLatitude();
longitude = gps.getLongitude();
Log.d("lat", "" + latitude);
Log.d("long", "" + longitude);


} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}





share|improve this answer































    0














    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






    share|improve this answer































      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;
      }
      }
      }
      });
      }





      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312874%2fandroid-how-to-request-location-update-in-the-new-api%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        Use This Class



        public class GPSTracker extends Service implements LocationListener {

        private final Context mContext;

        // flag for GPS status
        boolean isGPSEnabled = false;

        // flag for network status
        boolean isNetworkEnabled = false;

        // flag for GPS status
        boolean canGetLocation = false;

        Location location; // location
        double latitude; // latitude
        double longitude; // longitude

        // The minimum distance to change Updates in meters
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

        // The minimum time between updates in milliseconds
        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

        // Declaring a Location Manager
        protected LocationManager locationManager;

        public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
        }

        @SuppressLint("MissingPermission")
        public Location getLocation() {
        try {
        locationManager = (LocationManager) mContext
        .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
        .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
        // no network provider is enabled
        } else {
        this.canGetLocation = true;
        // First get location from Network Provider
        if (isNetworkEnabled) {
        locationManager.requestLocationUpdates(
        LocationManager.NETWORK_PROVIDER,
        MIN_TIME_BW_UPDATES,
        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
        Log.d("Network", "Network");
        if (locationManager != null) {
        location = locationManager
        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        }
        }
        }
        // if GPS Enabled get lat/long using GPS Services
        if (isGPSEnabled) {
        if (location == null) {
        locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER,
        MIN_TIME_BW_UPDATES,
        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
        Log.d("GPS Enabled", "GPS Enabled");
        if (locationManager != null) {
        location = locationManager
        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        }
        }
        }
        }
        }

        } catch (Exception e) {
        e.printStackTrace();
        }

        return location;
        }

        /**
        * Stop using GPS listener
        * Calling this function will stop using GPS in your app
        */
        public void stopUsingGPS() {
        if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
        }
        }

        /**
        * Function to get latitude
        */
        public double getLatitude() {
        if (location != null) {
        latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
        }

        /**
        * Function to get longitude
        */
        public double getLongitude() {
        if (location != null) {
        longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
        }

        /**
        * Function to check GPS/wifi enabled
        *
        * @return boolean
        */
        public boolean canGetLocation() {
        return this.canGetLocation;
        }

        /**
        * Function to show settings alert dialog
        * On pressing Settings button will lauch Settings Options
        */
        public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mContext.startActivity(intent);
        }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
        });

        // Showing Alert Message
        alertDialog.show();
        }

        @Override
        public void onLocationChanged(Location location) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public IBinder onBind(Intent arg0) {
        return null;
        }
        }


        Use this method in Ur Activity Class



          double latitude, longitude;
        private void getLocation() {
        GPSTracker gps = new GPSTracker(this);
        if (gps.canGetLocation()) {

        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        Log.d("lat", "" + latitude);
        Log.d("long", "" + longitude);


        } else {
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
        }





        share|improve this answer




























          0














          Use This Class



          public class GPSTracker extends Service implements LocationListener {

          private final Context mContext;

          // flag for GPS status
          boolean isGPSEnabled = false;

          // flag for network status
          boolean isNetworkEnabled = false;

          // flag for GPS status
          boolean canGetLocation = false;

          Location location; // location
          double latitude; // latitude
          double longitude; // longitude

          // The minimum distance to change Updates in meters
          private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

          // The minimum time between updates in milliseconds
          private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

          // Declaring a Location Manager
          protected LocationManager locationManager;

          public GPSTracker(Context context) {
          this.mContext = context;
          getLocation();
          }

          @SuppressLint("MissingPermission")
          public Location getLocation() {
          try {
          locationManager = (LocationManager) mContext
          .getSystemService(LOCATION_SERVICE);

          // getting GPS status
          isGPSEnabled = locationManager
          .isProviderEnabled(LocationManager.GPS_PROVIDER);

          // getting network status
          isNetworkEnabled = locationManager
          .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

          if (!isGPSEnabled && !isNetworkEnabled) {
          // no network provider is enabled
          } else {
          this.canGetLocation = true;
          // First get location from Network Provider
          if (isNetworkEnabled) {
          locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER,
          MIN_TIME_BW_UPDATES,
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
          Log.d("Network", "Network");
          if (locationManager != null) {
          location = locationManager
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
          if (location != null) {
          latitude = location.getLatitude();
          longitude = location.getLongitude();
          }
          }
          }
          // if GPS Enabled get lat/long using GPS Services
          if (isGPSEnabled) {
          if (location == null) {
          locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER,
          MIN_TIME_BW_UPDATES,
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
          Log.d("GPS Enabled", "GPS Enabled");
          if (locationManager != null) {
          location = locationManager
          .getLastKnownLocation(LocationManager.GPS_PROVIDER);
          if (location != null) {
          latitude = location.getLatitude();
          longitude = location.getLongitude();
          }
          }
          }
          }
          }

          } catch (Exception e) {
          e.printStackTrace();
          }

          return location;
          }

          /**
          * Stop using GPS listener
          * Calling this function will stop using GPS in your app
          */
          public void stopUsingGPS() {
          if (locationManager != null) {
          locationManager.removeUpdates(GPSTracker.this);
          }
          }

          /**
          * Function to get latitude
          */
          public double getLatitude() {
          if (location != null) {
          latitude = location.getLatitude();
          }

          // return latitude
          return latitude;
          }

          /**
          * Function to get longitude
          */
          public double getLongitude() {
          if (location != null) {
          longitude = location.getLongitude();
          }

          // return longitude
          return longitude;
          }

          /**
          * Function to check GPS/wifi enabled
          *
          * @return boolean
          */
          public boolean canGetLocation() {
          return this.canGetLocation;
          }

          /**
          * Function to show settings alert dialog
          * On pressing Settings button will lauch Settings Options
          */
          public void showSettingsAlert() {
          AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

          // Setting Dialog Title
          alertDialog.setTitle("GPS is settings");

          // Setting Dialog Message
          alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

          // On pressing Settings button
          alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
          Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
          mContext.startActivity(intent);
          }
          });

          // on pressing cancel button
          alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
          dialog.cancel();
          }
          });

          // Showing Alert Message
          alertDialog.show();
          }

          @Override
          public void onLocationChanged(Location location) {
          }

          @Override
          public void onProviderDisabled(String provider) {
          }

          @Override
          public void onProviderEnabled(String provider) {
          }

          @Override
          public void onStatusChanged(String provider, int status, Bundle extras) {
          }

          @Override
          public IBinder onBind(Intent arg0) {
          return null;
          }
          }


          Use this method in Ur Activity Class



            double latitude, longitude;
          private void getLocation() {
          GPSTracker gps = new GPSTracker(this);
          if (gps.canGetLocation()) {

          latitude = gps.getLatitude();
          longitude = gps.getLongitude();
          Log.d("lat", "" + latitude);
          Log.d("long", "" + longitude);


          } else {
          // can't get location
          // GPS or Network is not enabled
          // Ask user to enable GPS/network in settings
          gps.showSettingsAlert();
          }





          share|improve this answer


























            0












            0








            0







            Use This Class



            public class GPSTracker extends Service implements LocationListener {

            private final Context mContext;

            // flag for GPS status
            boolean isGPSEnabled = false;

            // flag for network status
            boolean isNetworkEnabled = false;

            // flag for GPS status
            boolean canGetLocation = false;

            Location location; // location
            double latitude; // latitude
            double longitude; // longitude

            // The minimum distance to change Updates in meters
            private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

            // The minimum time between updates in milliseconds
            private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

            // Declaring a Location Manager
            protected LocationManager locationManager;

            public GPSTracker(Context context) {
            this.mContext = context;
            getLocation();
            }

            @SuppressLint("MissingPermission")
            public Location getLocation() {
            try {
            locationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
            } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
            locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER,
            MIN_TIME_BW_UPDATES,
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "Network");
            if (locationManager != null) {
            location = locationManager
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            }
            }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
            if (location == null) {
            locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MIN_TIME_BW_UPDATES,
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("GPS Enabled", "GPS Enabled");
            if (locationManager != null) {
            location = locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            }
            }
            }
            }
            }

            } catch (Exception e) {
            e.printStackTrace();
            }

            return location;
            }

            /**
            * Stop using GPS listener
            * Calling this function will stop using GPS in your app
            */
            public void stopUsingGPS() {
            if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
            }
            }

            /**
            * Function to get latitude
            */
            public double getLatitude() {
            if (location != null) {
            latitude = location.getLatitude();
            }

            // return latitude
            return latitude;
            }

            /**
            * Function to get longitude
            */
            public double getLongitude() {
            if (location != null) {
            longitude = location.getLongitude();
            }

            // return longitude
            return longitude;
            }

            /**
            * Function to check GPS/wifi enabled
            *
            * @return boolean
            */
            public boolean canGetLocation() {
            return this.canGetLocation;
            }

            /**
            * Function to show settings alert dialog
            * On pressing Settings button will lauch Settings Options
            */
            public void showSettingsAlert() {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

            // Setting Dialog Title
            alertDialog.setTitle("GPS is settings");

            // Setting Dialog Message
            alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

            // On pressing Settings button
            alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
            }
            });

            // on pressing cancel button
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
            });

            // Showing Alert Message
            alertDialog.show();
            }

            @Override
            public void onLocationChanged(Location location) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public IBinder onBind(Intent arg0) {
            return null;
            }
            }


            Use this method in Ur Activity Class



              double latitude, longitude;
            private void getLocation() {
            GPSTracker gps = new GPSTracker(this);
            if (gps.canGetLocation()) {

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            Log.d("lat", "" + latitude);
            Log.d("long", "" + longitude);


            } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
            }





            share|improve this answer













            Use This Class



            public class GPSTracker extends Service implements LocationListener {

            private final Context mContext;

            // flag for GPS status
            boolean isGPSEnabled = false;

            // flag for network status
            boolean isNetworkEnabled = false;

            // flag for GPS status
            boolean canGetLocation = false;

            Location location; // location
            double latitude; // latitude
            double longitude; // longitude

            // The minimum distance to change Updates in meters
            private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

            // The minimum time between updates in milliseconds
            private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

            // Declaring a Location Manager
            protected LocationManager locationManager;

            public GPSTracker(Context context) {
            this.mContext = context;
            getLocation();
            }

            @SuppressLint("MissingPermission")
            public Location getLocation() {
            try {
            locationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
            } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
            locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER,
            MIN_TIME_BW_UPDATES,
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "Network");
            if (locationManager != null) {
            location = locationManager
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            }
            }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
            if (location == null) {
            locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MIN_TIME_BW_UPDATES,
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("GPS Enabled", "GPS Enabled");
            if (locationManager != null) {
            location = locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            }
            }
            }
            }
            }

            } catch (Exception e) {
            e.printStackTrace();
            }

            return location;
            }

            /**
            * Stop using GPS listener
            * Calling this function will stop using GPS in your app
            */
            public void stopUsingGPS() {
            if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
            }
            }

            /**
            * Function to get latitude
            */
            public double getLatitude() {
            if (location != null) {
            latitude = location.getLatitude();
            }

            // return latitude
            return latitude;
            }

            /**
            * Function to get longitude
            */
            public double getLongitude() {
            if (location != null) {
            longitude = location.getLongitude();
            }

            // return longitude
            return longitude;
            }

            /**
            * Function to check GPS/wifi enabled
            *
            * @return boolean
            */
            public boolean canGetLocation() {
            return this.canGetLocation;
            }

            /**
            * Function to show settings alert dialog
            * On pressing Settings button will lauch Settings Options
            */
            public void showSettingsAlert() {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

            // Setting Dialog Title
            alertDialog.setTitle("GPS is settings");

            // Setting Dialog Message
            alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

            // On pressing Settings button
            alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
            }
            });

            // on pressing cancel button
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
            });

            // Showing Alert Message
            alertDialog.show();
            }

            @Override
            public void onLocationChanged(Location location) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public IBinder onBind(Intent arg0) {
            return null;
            }
            }


            Use this method in Ur Activity Class



              double latitude, longitude;
            private void getLocation() {
            GPSTracker gps = new GPSTracker(this);
            if (gps.canGetLocation()) {

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            Log.d("lat", "" + latitude);
            Log.d("long", "" + longitude);


            } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 15 '18 at 5:25









            suresh madaparthisuresh madaparthi

            25219




            25219

























                0














                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






                share|improve this answer




























                  0














                  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






                  share|improve this answer


























                    0












                    0








                    0







                    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






                    share|improve this answer













                    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







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 15 '18 at 8:42









                    Utkarsh SrivastavaUtkarsh Srivastava

                    130111




                    130111























                        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;
                        }
                        }
                        }
                        });
                        }





                        share|improve this answer






























                          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;
                          }
                          }
                          }
                          });
                          }





                          share|improve this answer




























                            0












                            0








                            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;
                            }
                            }
                            }
                            });
                            }





                            share|improve this answer















                            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;
                            }
                            }
                            }
                            });
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 17 '18 at 8:51









                            halfer

                            14.6k758113




                            14.6k758113










                            answered Nov 15 '18 at 5:49









                            AthiraAthira

                            470118




                            470118






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312874%2fandroid-how-to-request-location-update-in-the-new-api%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Xamarin.iOS Cant Deploy on Iphone

                                Glorious Revolution

                                Dulmage-Mendelsohn matrix decomposition in Python