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

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.

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

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

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

Related

want get curent Adresse Location

I am developing an application that allows to retrieve the current location address using Geocoder.
this is the step to get location adresse that i follow :
check if GPS is enable on device
if it is request Location permissionspermissions else if GPS is disable on device request enable it than request permission
initialise Geocoder and get adresse latitude and logitude the get Adresse
if the GPS is Enable before clicking on button to get Location EveryThing work fine .
but the problem is when the GPS is disable whene clicking on button to get Location even if the app request to enable it and it will be enable i get this error message
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
code that i used
Onclick Methode (test if GPS enabled than call getLocation Methode)
locationButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
//Check permissions
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(2000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(getApplicationContext())
.checkLocationSettings(builder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
Toast.makeText(HomeActivity.this, "GPS is already tured on" + response, Toast.LENGTH_SHORT).show();
getCurrentLocation();
} catch (ApiException e) {
switch (e.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException = (ResolvableApiException) e;
resolvableApiException.startResolutionForResult(HomeActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
//Device does not have location
break;
}
}
}
});
}
});
GetLocation methode
#RequiresApi(api = Build.VERSION_CODES.M)
private void getCurrentLocation() {
int picd = 0;
if (picd == 0) {
if (!checkLocationFinePermission() || !checkLocationCoarsePermission() ) {
requestLocationPermission();
} else {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
try {
//initialize geoCoder
Location location = task.getResult();
Geocoder geocoder = new Geocoder(HomeActivity.this
, Locale.getDefault());
//initialize adresse
List<Address> addresses = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1
);
//setAdresse
adresseEditText.setText(addresses.get(0).getAddressLine(0));
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "onComplete: " + e);
}
}
});
}
}

Location is null - Android

I'm creating an app, where I want to get my current location. I want to get location only once, when user opens the app. I don't need any updates, while app is open.
Here's my code.
public class MainActivity extends AppCompatActivity {
private LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
return;
}
fetchLocation();
}
private void fetchLocation() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(600);
mLocationRequest.setFastestInterval(300);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Log.d("MyTag", "Location is null");
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
Log.d("MyTag", location.getLatitude() + " " + location.getLongitude());
}
}
}
};
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.d("MyTag", "GoogleAPIClient connected");
Task<Location> task = LocationServices.getFusedLocationProviderClient(MainActivity.this).getLastLocation();
task.addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location == null) {
LocationServices.getFusedLocationProviderClient(MainActivity.this).requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
} else {
Log.d("MyTag", "My location is: " + location.getLatitude() + " : " + location.getLongitude());
}
}
}).addOnFailureListener(MainActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("MyTag", "Error message: " + e.getMessage());
}
});
}
#Override
public void onConnectionSuspended(int i) {
Log.d("MyTag", "GoogleAPIClient connection suspended");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(MainActivity.this, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
})
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
LocationServices.getFusedLocationProviderClient(MainActivity.this).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
Log.d("MyTag", "My locations is: " + location.getLatitude() + " : " + location.getLongitude());
} else {
Log.d("MyTag", "My locations is null");
}
}
});
}
}
I watched almost all stackoverflow answers, but nothing helped. I don't know where I'm doing wrong.
I read that the fused Location Provider will only maintain background location if at least one client is connected to it. I'm connecting GoogleApiClient. If you see logs, it connects successfully, but then nothing happens. Thank you.
My logs:
-- My locations is null
-- GoogleAPIClient connected

Wait for device to fetch location data

In my app I fetch GPS coordinates from the user. When the GPS was just activated my app continues even before the coordinates were fetched, so the location is null.
I noticed that the onLocationChanged method does as it should and might somehow be a key to it, but how do I make sure that the code in the main class doesn’t fetch empty values and waits until the location is not null?
The main code:
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
progressBar.setVisibility(View.VISIBLE);
GPSFetch t = new GPSFetch(getActivity().getApplicationContext());
Location location = t.getLocation();
if (location == null) {
//Toast
} else {
lat = location.getLatitude();
lon = location.getLongitude();
}
new GetContacts().execute();
}
The GPSFetch:
public Location getLocation(){
if (ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED)
{
return null;
}
try {
LocationManager lm = (LocationManager) context.getSystemService(LOCATION_SERVICE);
boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,10,this);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return loc;
}else{
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
public void onLocationChanged(Location location) {
Log.d("4", "changed");
}
The method is called onLocationChanged. Which means that there IS a value.
Note: You are actually fetching a GPS coordinate from the local play services api of the android device. Read more about location services here
First you check your gps is on or not, if gps is on then onlocation changed method give lat and lon.
you can check using following code
public static boolean checkGps(Activity mContext) {
LocationManager service = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
return enabled;
}
its return true then gps on otherwise not
if gps not on then on gps programatically using this code
public void displayLocationSettingsRequest() {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.e("LocationSetting.SUCCESS", "All location settings are satisfied.");
// openMap();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.e("LocationSetting.SUCCESS", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(HomeActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.e("LocationSetting.SUCCESS", "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.e("LocationSetting.SUCCESS", "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
break;
}
}
});
}
this ask you about gps on or cancel if you press ok then you can fetch result of its in onactivityresult method
like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
Log.e("RESULT_OK", result + "");
// now your gps is on you can handle your location code here
}
if (resultCode == Activity.RESULT_CANCELED) {
Utils.showToastPopup(this, "Please Turn On Gps");
// show custom popup when user denied this gps permission and check again
when click button or on resume
}
}
}
and then fetch your lat lon inside onlocationchanged
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}

Toast message shows 0 for both latitude and longitude

I am trying to build an app from here, where the user clicks on a button and get the current latitude and longitude but the problem is that I am getting 0.0 for both latitude and longitude. I have one activity and one service in my application. The code for activity and service is given below :
GpsActivity.java
public class GpsActivity extends AppCompatActivity {
Button show;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{mPermission},
REQUEST_CODE_PERMISSION);
// If any permission above not allowed by user, this condition will
// execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}
show=(Button)findViewById(R.id.showLocation);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gps=new GPSTracker(GpsActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
+ latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private 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
protected LocationManager locationManager;
public GPSTracker() {
//mContext = null;
}
public GPSTracker(Context mContext) {
this.mContext = mContext;
getLocation();
}
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) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#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 ActivityCompat#requestPermissions for more details.
return location;
}
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 IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
I have mentioned all the permissions required for the location updates in the manifest file. The only problem here is that latitude and longitude shows 0.0 on clicking the button.
Can anone help? Thank you :)
you didn't call getLocation() method
if(gps.canGetLocation())
{
gps.getLocation();
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
+ latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
The function getLastKnownLocation() is returning null. I would recommend waiting for a fresh location to get called in onLocationChanged() and use that location object.
Also, you aren't properly using the Service class. You basically created a wrapper around the LocationManager. If you want to know how to use a Service properly, check out this tutorial.

Android Location return null after Enabling GPS in dialog

When I enter a screen, I check for if GPS is turned on, if not, the dialog to enable GPS is shown. When user clicks Yes, onActivityResult -> GPS is turned on and I try to get the location but this always returns null
When I enter the screen with GPS already on, location is retrieved properly. I have been struggling with this for few days now and can't seem to find any resources.
UserLocationUtilities.java
public class UserLocationUtilities implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{
GoogleApiClient googleApiClient;
Activity activity;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Location location;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
// 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 = 1 * 1000 * 60; // 1 minute
public UserLocationUtilities(Activity activity){
this.activity = activity;
}
public void settingsRequest()
{
if(googleApiClient == null){
googleApiClient = new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
}
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
public Location getLocation() {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
try {
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
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;
}
public boolean isLocationEnabled() {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(activity.getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locationProviders = Settings.Secure.getString(activity.getApplicationContext().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
After user selects Yes in Settings Dialog, onActivityResult, I do location = userlocationutilities.getLocation(); and always returns null. If switch screens and come back, location is retrieved.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK: //location settings dialog, user selected YES to enabling location
location = userLocationUtilities.getLocation();
if(location != null){
//location of user FOUND
Toast.makeText(getActivity(), "Lat: "+location.getLatitude()+" Long: "+location.getLongitude(), Toast.LENGTH_LONG).show();
getRingsNearMeCall();
}else{
//location of user NOT FOUND
Toast.makeText(getActivity(), "null location", Toast.LENGTH_LONG).show();
}
break;
case Activity.RESULT_CANCELED: //location settings dialog, user selected NO to enabling location
userLocationUtilities.settingsRequest(); //ask user again with Location Settings Dialog
break;
}
break;
}
}
Editted: I make the requestPermission in the fragment, the permission is granted
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[] { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION },
PERMISSION_ACCESS_FINE_LOCATION);
}else{
checkLocationSettingsGetRings();
}
LocationSettingsRequest is used just make location settings adequate, for example you want receive more accurate (HIGH_ACCURACY) locations, then you need GPS is enabled. So in that case, LocationSettingsRequest prompts the dialog to allow api change settings.
After pressing OK, you can see that GPS is enabled. But it does not mean you are granted to make location request yet.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
// Here means required settings are adequate.
// We can make location request.
// But are we granted to use request location updates ?
break;
}
break;
}
}
}
Thats okay, but you are checking the permission, but you did never make requestPermissions. This is the first possible reason of getting null.
public Location getLocation() {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
...
}
return location;
}
Even you are previously granted to make location request
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
getLastKnownLocation() method could return null, this is not unexpected behaviour. This is the second possible reason of getting null
You are making location request, but the global location variable is never assigned in onLocationChanged callback.
#Override
public void onLocationChanged(Location location) {
// global location variable is not assigned ?
// getLocation() method will return null if getLastKnownLocation()
// did not return null previously.
}
This is third possible reason of getting null.
Finally, I find a solution:
I create a thread and wait for my location available.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case REQUEST_LOCATION:
switch (resultCode){
case Activity.RESULT_OK:
mHandler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
mHandler.postDelayed(this,1000);
checkLocationAvailable();
}
};
mHandler.postDelayed(runnable,1000);
break;
case Activity.RESULT_CANCELED:
break;
}
}
}
Create a function to stop the thread when my location available.
private void checkLocationAvailable(){
if (mMap.getMyLocation() != null) {
mHandler.removeCallbacks(runnable);
// do stuff
}
}
It is not a good solution, but hope it will help.
Add this override method for me its worked fine--
#Override
public void onLocationChanged(Location location) {
getLocation("onLocationChanged");
}

Categories

Resources