Reputation: 51
I'm trying to get the location of the user, every little while, and I need to always have something in the variable, so that I can check if the user is near the door he/she is trying to unlock.
This is the code I'm trying to run. I'm extending AppCompatActivity and implementing LocationListener.
protected LocationManager locationManager;
protected double currentLatitude, currentLongitude;
protected double storeLatitude, storeLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Utils.showMessage(StoreActivity.this, "You must allow GPS services, so that we can make sure that you're near the store you're trying to unlock.");
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
}
@Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
I do get the location, sometimes. So the code works. But sometimes I can wait for a very long time without getting any updates at all, so something must be wrong here. I'm sure that GPS services are allowed on the phone as well.
Any ideas how I can improve it? I need to always have some sort of location in the variable, and not null.
Thanks in advance!
Upvotes: 0
Views: 298
Reputation: 703
So, I did something like that just some days ago. It also depends on how many seconds you have set for the updates.
This is my code inside my class:
public static LocationRequest locationRequest;
private static final long DEFAULT_INTERVAL=10*1000;
private static final long FAST_INTERVAL=5*1000;
public static void setGPS(){
locationRequest= LocationRequest.create();
locationRequest.setInterval(DEFAULT_INTERVAL);
locationRequest.setFastestInterval(FAST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
As you can see, there are two intervals, one for Default mode, which is for PRIORITY_BALANCED_POWER_ACCURACY
, already set to 30 seconds by default, and one for
PRIORITY_HIGH_ACCURACY
But, you can change those seconds as I did (10 for default, 5 for fast). So by changing these you can update your position faster.
Upvotes: 1