Run time location permission issue - android

Iam creating an app in which I have to show user current location on map.
SO for this firstly the problem I was facing was when user login in the app if his location is turned off I asked for the permission for turn on the location and even after user give me the permission I still get null lat long in my get location function and I get the location after user restart the app. Iam getting permission in splash so for this restart issue what I have done is in splash Iam restarting the activity in onActivityResult like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
displayLocationSettingsRequest();
}
private 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:
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(SplashActivity.this, 7);
} catch (IntentSender.SendIntentException e) {
Toast.makeText(SplashActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Toast.makeText(SplashActivity.this, "Location settings are inadequate, and cannot be fixed here. Dialog not created.", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 7 && resultCode == RESULT_OK && data != null) {
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
Toast.makeText(this, "entering", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "To continue please give permission for location", Toast.LENGTH_LONG).show();
displayLocationSettingsRequest();
}
}
#Override
protected void onRestart() {
super.onRestart();
if (ConnectivityReceiver.isNetworkConnected(this)) {
displayLocationSettingsRequest();
} else {
HelperClass.openAlertDialog(SplashActivity.this, Constants.alert, Constants.No_Internet_Msg, Constants.try_again, Constants.Dialog_cancel, this);
}
}
}
this method worked for some time but after 1 day Iam still getting the same issue and now I'm getting an extra edge case that if app is over wifi and I get the dialog to give location permission then every time I will get the same dialog even after restarting the app and giving permission and this issue will resolve after I turn my mobile data on run the app on mobile data one time and then get back to wifi again.
This is my Location class :
public class LocationUtil implements LocationListener {
private final Context mContext;
// flag for GPS status
private boolean isGPSEnabled = false;
// flag for network status
private boolean isNetworkEnabled = false;
// flag for GPS status
private boolean canGetLocation = false;
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
private android.location.LocationManager locationManager;
public LocationUtil() {
this.mContext = null;
}
public LocationUtil(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (android.location.LocationManager) mContext.getSystemService(LOCATION_SERVICE);
if (locationManager != null) {
isGPSEnabled = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
}
if (locationManager != null) {
isNetworkEnabled = locationManager.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER);
}
if (isGPSEnabled || isNetworkEnabled) {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this.mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
locationManager.requestLocationUpdates(android.location.LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude() ;
}
}
}
if (isGPSEnabled) {
if (location == null) {
if (locationManager != null) {
locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
if (locationManager != null) {
location = locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude() ;
longitude = location.getLongitude() ;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
stopUsingGPS();
return location;
}
private void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(LocationUtil.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude() ;
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public static boolean getLocationMode(Context context) {
try {
return Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE) == 3;
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
And here in my MainActivity Iam getting location :
protected void setupLocation() {
if (locManager == null)
locManager = new LocationUtil(MainActivity.this);
if (locManager.getLocation() != null) {
locationHelper = new LocationHelper(locManager.getLocation().getLatitude(), locManager.getLocation().getLongitude());
latitude = locationHelper.getLatitude();
longitude = locationHelper.getLongitude();
} else {
Toast.makeText(getApplicationContext(), "Please accept location improvement dialog or restart the application!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
NOTE : Iam getting the lat long but the issue is coming in permission if before running the app location is off and I turn on the app it will give me null and I have to restart the app .

Related

How to refresh marker in Android Google Maps view?

How can I refresh the marker position (for example, when user is moving) on Android maps?
I set up the refresh time for 3 seconds in locationManager.requestLocationUpdates but it seems that it's not working.
Here is my GPSTracker 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 = 50; // 3 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
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) {
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 void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
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;
}
}
And here is my Maps Activity where I create map and add a marker to it:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
checkPermissions();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mapsCreate();
}
public void mapsCreate() {
GPSTracker tracker = new GPSTracker(MapsActivity.this);
double lat = tracker.getLatitude();
double lng = tracker.getLongitude();
// Add a marker for current location and move the camera
LatLng currentLocation = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
}
protected boolean checkPermissions() {
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
return true;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
break;
}
}
Any help would be much appreciated! Thank you
Save the marker object after adding to maps.
myMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location Marker"));
After getting new location in location updates callback update marker's position.
.....
myMarker.setPosition(newLatLng);

getLastKnownLocation sometimes returns null

Let me start by acknowledging that there are many results when you search for this particular question. Yet, nothing I've tried, according to those answers, works. Sometimes I get the location, sometimes I don't. If I play with the Location enabling/disabling I always get null when calling getLastKnownLocation. If I sometimes manually revoke the Location permission and enable it again, it works. I've tried changing the LocationManager to location = locationManager .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); but it doesn't work.
Basically, I am doing the following:
public class GPSTracker implements LocationListener {
public static final int LOCATION_SETTINGS_REQUEST_CODE = 109;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60;
private static boolean isGpsStatusChanged = false;
private static AlertDialog.Builder alertDialog;
private LocationManager locationManager;
private boolean canGetLocation = false;
private Location location;
private double latitude;
private double longitude;
private NewLocationListener newLocationListener;
public interface NewLocationListener {
void onLocationChanges(Location location);
}
public GPSTracker() {
}
#SuppressWarnings("all")
public Location getLocation() {
try {
locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean 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("GPSTracker", "Network");
if (locationManager != null) {
Log.d("GPSTracker", "Network - location manager != null");
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d("GPSTracker", "Network - last known location != null");
latitude = location.getLatitude();
longitude = location.getLongitude();
newLocationListener.onLocationChanges(location);
}
}
}
// 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("GPSTracker", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d("LastKnownLocation", "Location: " + locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
newLocationListener.onLocationChanges(location);
}
}
}
}
}
} catch (Exception e) {
Log.e(Constants.TAG, e.getMessage(), e);
}
return location;
}
public static boolean isGpsEnabled() {
LocationManager locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context
.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
#SuppressWarnings("all")
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void setNewLocationListener(NewLocationListener newLocationListener) {
this.newLocationListener = newLocationListener;
}
public void removeLocationListener() {
this.newLocationListener = null;
}
#SuppressWarnings("InlinedApi")
public void showSettingsAlert(final Context context) {
if (alertDialog != null) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alertDialog = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
alertDialog = new AlertDialog.Builder(context);
}
alertDialog.setTitle(R.string.gps_window_title);
alertDialog.setMessage(R.string.gps_window_message);
alertDialog.setPositiveButton(R.string.gps_window_button_positive, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
((Activity) context).startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE);
}
});
alertDialog.setNegativeButton(R.string.gps_window_button_negative, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show().setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
alertDialog = null;
}
});
}
#Override
public void onLocationChanged(Location location) {
if (newLocationListener != null) {
newLocationListener.onLocationChanges(location);
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public static boolean isGpsStatusChanged() {
return isGpsStatusChanged;
}
public static void setIsGpsStatusChanged(boolean isGpsStatusChanged) {
GPSTracker.isGpsStatusChanged = isGpsStatusChanged;
}
}
And then in my fragment:
private void statGPSLocationTracking() {
Log.d(Constants.TAG, "start gps update");
// check if GPS enabled
gpsTracker = new GPSTracker();
gpsTracker.setNewLocationListener(newLocationListener);
gpsTracker.getLocation();
if (!gpsTracker.canGetLocation()) {
Log.d(Constants.TAG, "GPS not enabled, show enable dialog");
// stop the gps tracker(removes the location update listeners)
gpsTracker.stopUsingGPS();
// ask user to enable location
gpsTracker.showSettingsAlert(getActivity());
}
}
private GPSTracker.NewLocationListener newLocationListener = new GPSTracker.NewLocationListener() {
#Override
public void onLocationChanges(Location loc) {
if (getActivity() == null) {
return;
}
// GPS location determined, load the web page and pass the coordinates in the header location section
Log.d(Constants.TAG, "Location listener onLocationChanges: " + loc);
infoManager.setCurrentLocation(loc);
checkRadioInfoNeeded();
// stop the gps tracker(removes the location update listeners)
gpsTracker.stopUsingGPS();
}
};
Without this location permission android.Manifest.permission.ACCESS_FINE_LOCATION the getLastKnownLocation() will always return null.
getLastKnownLocation() does not return location immediately, it takes some time.
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60;
this to
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 5 * 1000;
Also remove your code which gets location from network. Go to Google maps and see if maps is able to detect your current location. If your map is able to get location then your code too should get location place breakpoints and see where the real issue is.

Getting Latitude and longitude in 30 seconds

I am trying to get location of user as longitude and latitude from GPS/network which ever is available and i want to get it fast , or else previous location coordinates will return if cannot get new one right now.
Here is my attempt:
public class GPSTracker extends Service{
// 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
private final Context mContext;
// Declaring a Location Manager
protected LocationManager locationManager;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location = null; // location
double latitude; // latitude
double longitude; // longitude
myLocationLitener locationLitener;
public GPSTracker(Context context) {
this.mContext = context;
locationLitener = new myLocationLitener();
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;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,locationLitener);
Log.d("Network", "Network Enabled");
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) {
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 null;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationLitener);
Log.d("GPS", "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) {
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;
}
locationManager.removeUpdates(locationLitener);
}
}
/**
* 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 arg0) {
return null;
}
private class myLocationLitener implements LocationListener{
#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) {
}
}
}
How i use this class?
Suppose i am running below function in async task (who don't have knowledge of android annotation #Background is doing this)
#Background
void getmyLocationAndSend(){
GPSTracker gps = new GPSTracker(context);
// check if GPS location can get Location
if (gps.canGetLocation()) {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.d("Your Location", "latitude:" + gps.getLatitude()
+ ", longitude: " + gps.getLongitude());
latitude = gps.getLatitude(); // set the globals
longitude = gps.getLongitude(); // set the globals
}else{
showToast("Network is connected..");
if (progress != null && progress.isShowing()) {
progress.dismiss();
}
}
}else{
showToast("Cannot get location from gps..");
if (progress != null && progress.isShowing()) {
progress.dismiss();
}
}
}
my goal is to get coordinates in less than 30 seconds , and never get 0.0 value , how can i achieve that any help appreciated ?
Please check how i'm using in my app and its working perfect.I'm using fused api for update location please follow few steps.Currently you using very old approach.So, there is no need now
and pass here your time in milliseconds what you want
UPDATE_INTERVAL_IN_MILLISECONDS
Step 1. Make this class
GoogleLocationService.java
public class GoogleLocationService {
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();
LocationUpdateListener locationUpdateListener;
Context activity;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;
public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {
this.locationUpdateListener = locationUpdateListener;
this.activity = activity;
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
//Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(activity)
.addConnectionCallbacks(callbacks)
.addOnConnectionFailedListener(callbacks)
.addApi(LocationServices.API)
.build();
createLocationRequest();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();
}
locationUpdateListener.cannotReceiveLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location.hasAccuracy()) {
if (location.getAccuracy() < 30) {
locationUpdateListener.updateLocation(location);
}
}
}
}
private static boolean locationEnabled(Context context) {
boolean gps_enabled = false;
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
return gps_enabled;
}
private boolean servicesConnected(Context context) {
return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context);
}
private boolean isPackageInstalled(String packagename, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return false;
}
}
public void startUpdates() {
/*
* Connect the client. Don't re-start any requests here; instead, wait
* for onResume()
*/
if (servicesConnected(activity)) {
if (locationEnabled(activity)) {
locationUpdateListener.canReceiveLocationUpdates();
startLocationUpdates();
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();
}
} else {
locationUpdateListener.cannotReceiveLocationUpdates();
Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();
}
}
//stop location updates
public void stopUpdates() {
stopLocationUpdates();
}
//start location updates
private void startLocationUpdates() {
if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks);
}
}
public void stopLocationUpdates() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks);
}
}
public void startGoogleApi() {
mGoogleApiClient.connect();
}
public void closeGoogleApi() {
mGoogleApiClient.disconnect();
}
}
Step2. Make this interface
LocationUpdateListener.java
public interface LocationUpdateListener {
/**
* Called immediately the service starts if the service can obtain location
*/
void canReceiveLocationUpdates();
/**
* Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and
*/
void cannotReceiveLocationUpdates();
/**
* Called whenever the location has changed (at least non-trivially)
* #param location
*/
void updateLocation(Location location);
/**
* Called when GoogleLocationServices detects that the device has moved to a new location.
* #param localityName The name of the locality (somewhere below street but above area).
*/
void updateLocationName(String localityName, Location location);
}
Step 3. Make this Location service class
LocationService.java
public class LocationService extends Service {
private GoogleLocationService googleLocationService;
#Override
public void onCreate() {
super.onCreate();
//start the handler for getting locations
//create component
updateLocation(getApplicationContext());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
//get current location os user
private void updateLocation(Context context) {
googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
#Override
public void canReceiveLocationUpdates() {
}
#Override
public void cannotReceiveLocationUpdates() {
}
//update location to our servers for tracking purpose
#Override
public void updateLocation(Location location) {
if (location != null ) {
Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());
}
}
#Override
public void updateLocationName(String localityName, Location location) {
googleLocationService.stopLocationUpdates();
}
});
googleLocationService.startUpdates();
}
IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
public LocationService getServerInstance() {
return LocationService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
//stop location updates on stopping the service
#Override
public void onDestroy() {
super.onDestroy();
if (googleLocationService != null) {
googleLocationService.stopLocationUpdates();
}
}
}
Edited Answer:
How to use service,
Start service in your main activity,like this
startService(new Intent(context, LocationService.class));
for stop,
stopService(new Intent(context, LocationService.class));
and declare in manifest like this,
<service
android:name=".service.location.LocationService"
android:enabled="true"></service>
Note: I have done this because i need location after killed the app.If you dont want service.Then,you can call directly below code in class where location need to be update and remove locationservice.
private GoogleLocationService googleLocationService;
googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {
#Override
public void canReceiveLocationUpdates() {
}
#Override
public void cannotReceiveLocationUpdates() {
}
//update location to our servers for tracking purpose
#Override
public void updateLocation(Location location) {
if (location != null ) {
Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());
}
}
#Override
public void updateLocationName(String localityName, Location location) {
googleLocationService.stopLocationUpdates();
}
});
googleLocationService.startUpdates();
and call this onDestroy
if (googleLocationService != null) {
googleLocationService.stopLocationUpdates();
}
Remember Locationservice should be declare in manifest as well.
According to me this is the best solution.I have done alot of work on location.
Thanks hope this will help you
Check out FusedLocationApi. It does a great job of that and it gives you options for minimizing battery performance.
You can take a look to RxGpsService (An Android service to retrieve GPS locations and route stats using RxJava). It retrieves a RouteStats object which contains the current speed, distance, time elapsed and waypoints.
Also is customizable, so you can set your interval by using .withInterval(30000) and .withFastestInterval(30000) .

Android “gps requires ACCESS_FINE_LOCATION” error

I am using SDK-23, and every time I run the application, my SecurityException gets thrown and the error from the debugger reads as so:
java.lang.SecurityException: "gps" location provider requires
ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.
This seems like a simple mistake, however, my manifest file is completely correct. Here it is, and here is my MapActivity code as well:
package com.buahbatu.salesmonitoring;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
final static String TAG = "MainActivity";
SwitchCompat switchTracked;
MyService service;
private GoogleMap googleMap;
Context mContext;
private TextView textAddress;
/* Google Fused Location Service */
public static GoogleApiClient mGoogleApiClient;
public static LocationRequest mLocationRequest;
public static GoogleApiClient.ConnectionCallbacks connectionCallbacks;
public static GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener;
public final static int REQUEST_LOCATION = 199;
public final static int REQUEST_CONNECTION = 11;
public final static int NOTIFICATION_ID = 2;
private static final String[] INITIAL_PERMS={
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_CONTACTS
};
private static final String[] LOCATION_PERMS={
Manifest.permission.ACCESS_FINE_LOCATION
};
boolean checkPermission() {
String location_fine = "android.permission.ACCESS_FINE_LOCATION";
String location_coarse = "android.permission.ACCESS_COARSE_LOCATION";
int permission_fine = mContext.checkCallingOrSelfPermission(location_fine);
int permission_coarse = mContext.checkCallingOrSelfPermission(location_coarse);
return permission_fine == PackageManager.PERMISSION_GRANTED && permission_coarse == PackageManager.PERMISSION_GRANTED;
}
public void startTracking(Activity activity) {
if (checkPermission()) {
Log.i(TAG, "startTracking");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
} else {
int permissionCheck = ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_FINE_LOCATION);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
service.setUpdateView(null);
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkLoggedStatus();
setSupportActionBar((Toolbar) findViewById(R.id.top_toolbar));
((TextView) findViewById(R.id.username_text)).setText(AppConfig.getUserName(this));
switchTracked = (SwitchCompat) findViewById(R.id.tracked_switch);
switchTracked.setOnCheckedChangeListener(onCheckedChangeListener);
switchTracked.setChecked(AppConfig.getOnTracked(this));
findViewById(R.id.test_but).setOnClickListener(this);
textAddress = (TextView) findViewById(R.id.txtAddress);
}
CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
switchTracked.setText(R.string.untracked);
service.stopTracking();
AppConfig.saveOnTracked(MainActivity.this, false);
} else {
switchTracked.setText(R.string.tracked);
service = AcaciaX.createService(getApplicationContext(), MyService.class);
service.startTracking(MainActivity.this);
service.setUpdateView((TextView) findViewById(R.id.location_text));
AppConfig.saveOnTracked(MainActivity.this, true);
}
}
};
void checkLoggedStatus() {
if (!AppConfig.getLoginStatus(this)) {
moveToLogin();
}
}
void moveToLogin() {
Intent move = new Intent(this, LoginActivity.class);
startActivity(move);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, Integer.toString(resultCode));
//final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case ServiceImpl.REQUEST_CONNECTION:
switch (resultCode) {
case Activity.RESULT_OK: {
switchTracked.setChecked(true);
break;
}
case Activity.RESULT_CANCELED: {
Toast.makeText(this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
break;
}
default: {
break;
}
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
AppConfig.saveLoginStatus(this, false);
AppConfig.storeAccount(this, "", "");
switchTracked.setChecked(false);
moveToLogin();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
NetHelper.login(MainActivity.this, "Tester", "pasu", new PostWebTask.HttpConnectionEvent() {
#Override
public void preEvent() {
}
#Override
public void postEvent(String... result) {
}
});
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
setUpMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
if (googleMap != null) {
//setUpMap();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
//googleMap.setMyLocationEnabled(true);
setUpMap();
}
public void setUpMap() {
if(checkPermission()) {
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knowName = addresses.get(0).getFeatureName();
String addressfull = address + " " + city + " " + state + " " + country + " " + postalCode + " " + knowName;
Intent intent = new Intent();
intent.putExtra("addressfull", addressfull);
textAddress.setText(addressfull);
}
} catch (IOException e) {
e.printStackTrace();
}
}else{
requestPermissions(INITIAL_PERMS, 2);
}
}
}
If you are targeting Android M, you need to ask users permission to access device GPS. Here is a not so clean code, but might help u a little bit. A better way to do it would be to create your own permission manager class to handle requests and a alertDialog ativity.
Whats happening below is
1) You are checking if permissions are granted.
2) If not, you are checking if the permissions have been denied previously, In that case, you are showing a rationale, to explain to the user why you need the permissions.
3) You show the request permission popup using ActivityCompat.
4) If user declines, show a snackbar with a view button to take the user to the app info screen, whenever u need to access the GPS but notice that permissions are not granted.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
showRationale();
} else {
// do request the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 8);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ){
//Start your code
} else {
//Show snackbar
}
}
}
private void showRationale(){
String strDeleteMessage = getResources().getString(R.string.rationale_message11) ;
final View dialogView = LayoutInflater.from(this.getActivity()).inflate(R.layout.dialog_fragment, null);
final AlertDialog storageRationaleAlert = new AlertDialog.Builder(this.getActivity()).create();
storageRationaleAlert.setView(dialogView, 0, 0, 0, 0);
storageRationaleAlert.setCanceledOnTouchOutside(false);
TextView mDialogTitle = (TextView) dialogView.findViewById(R.id.dialog_title);
TextView mDialogDetails = (TextView) dialogView.findViewById(R.id.dialog_details);
mDialogDetails.setVisibility(View.VISIBLE);
Button mCancelButton = (Button) dialogView.findViewById(R.id.cancel_btn);
Button mOkButton = (Button) dialogView.findViewById(R.id.ok_btn);
mOkButton.setText(getString(R.string.dialog_continue));
mDialogDetails.setText(Html.fromHtml(strDeleteMessage));
final Activity activity = this.getActivity();
mOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
storageRationaleAlert.dismiss();
//Ask for GPS permission
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
storageRationaleAlert.dismiss();
//Show permission snackbar
}
});
storageRationaleAlert.show();
}
This is my code that works for me:
private void askForGeoPermissions(boolean _askGeo) throws InterruptedException {
if (_askGeo) {
for (int i = 0; i < 5; i++)
{
if (!String.valueOf(latitude).equals("0.0")) {
break;
}
new SdkTrackingLocationUtils().checkGeolocationPermissions(this.context, getCurrentActivity());
TimeUnit.SECONDS.sleep(2);
}
}
}
protected void checkGeolocationPermissions(Context context, Activity activity)
{
try
{
if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
getLocation(context);
}
else
{
ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, 1);
}
}
catch (Exception e)
{
Log.e("SDK_TRACKING_ERROR", e.getMessage());
}
}
#SuppressLint("MissingPermission")
protected Location getLocation(Context context)
{
try
{
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled == false && isNetworkEnabled == false)
{
Log.e("SDK_TRACKING_ERROR", "No network provider is enabled");
}
else
{
this.canGetLocation = true;
if (isNetworkEnabled)
{
location = null;
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)
{
location = null;
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;
}

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

I am using this given below code to get locations:
public Location getLocation() {
try {
mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
// First get location from Network Provider
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (mLocationManager != null) {
location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
//get the location by gps
if (isGPSEnabled) {
if (location == null) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (mLocationManager != null) {location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
It is working properly, but I would like to get GPS location first, and in case if it is unavailable , location manager should query for Network provider, in which I am getting trouble.
Please, recommend me the good way to do this.
You're saying that you need GPS location first if its available, but what you did is first you're getting location from network provider and then from GPS. This will get location from Network and GPS as well if both are available. What you can do is, write these cases in if..else if block. Similar to-
if( !isGPSEnabled && !isNetworkEnabled) {
// Can't get location by any way
} else {
if(isGPSEnabled) {
// get location from GPS
} else if(isNetworkEnabled) {
// get location from Network Provider
}
}
So this will fetch location from GPS first (if available), else it will try to fetch location from Network Provider.
EDIT:
To make it better, I'll post a snippet. Consider it is in try-catch:
boolean gps_enabled = false;
boolean network_enabled = false;
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy())
finalLoc = net_loc;
else
finalLoc = gps_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
Now you check finalLoc for null, if not then return it.
You can write above code in a function which returns the desired (finalLoc) location. I think this might help.
The recommended way to do this is to use LocationClient:
First, define location update interval values. Adjust this to your needs.
private static final int MILLISECONDS_PER_SECOND = 1000;
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
Have your Activity implement GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, and LocationListener.
public class LocationActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {}
Then, set up a LocationClientin the onCreate() method of your Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
}
Add the required methods to your Activity; onConnected() is the method that is called when the LocationClientconnects. onLocationChanged() is where you'll retrieve the most up-to-date location.
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.w(TAG, "Location client connection failed");
}
#Override
public void onConnected(Bundle dataBundle) {
Log.d(TAG, "Location client connected");
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
#Override
public void onDisconnected() {
Log.d(TAG, "Location client disconnected");
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d(TAG, "Updated Location: " + Double.toString(location.getLatitude()) + "," + Double.toString(location.getLongitude()));
} else {
Log.d(TAG, "Updated location NULL");
}
}
Be sure to connect/disconnect the LocationClient so it's only using extra battery when absolutely necessary and so the GPS doesn't run indefinitely. The LocationClient must be connected in order to get data from it.
public void onResume() {
super.onResume();
mLocationClient.connect();
}
public void onStop() {
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(this);
}
mLocationClient.disconnect();
super.onStop();
}
Get the user's location. First try using the LocationClient; if that fails, fall back to the LocationManager.
public Location getLocation() {
if (mLocationClient != null && mLocationClient.isConnected()) {
return mLocationClient.getLastLocation();
} else {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocationGPS != null) {
return lastKnownLocationGPS;
} else {
return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} else {
return null;
}
}
}
Main Class:
public class AndroidLocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnNWShowLocation;
AppLocationService appLocationService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appLocationService = new AppLocationService(
AndroidLocationActivity.this);
btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (GPS): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("GPS");
}
}
});
btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AndroidLocationActivity.this);
alertDialog.setTitle(provider + " SETTINGS");
alertDialog.setMessage(provider
+ " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
AndroidLocationActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Next Class:
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#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;
}
}
Don't forget to add in your manifest.
<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />
use the fusion API that google developer have developed with fusion of GPS Sensor,Magnetometer,Accelerometer also using Wifi or cell location to calculate or estimate the location. It is also able to give location updates also inside the building accurately.
package com.example.ashis.gpslocation;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Location sample.
*
* Demonstrates use of the Location API to retrieve the last known location for a device.
* This sample uses Google Play services (GoogleApiClient) but does not need to authenticate a user.
* See https://github.com/googlesamples/android-google-accounts/tree/master/QuickStart if you are
* also using APIs that need authentication.
*/
public class MainActivity extends Activity implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final long ONE_MIN = 500;
private static final long TWO_MIN = 500;
private static final long FIVE_MIN = 500;
private static final long POLLING_FREQ = 1000 * 20;
private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
private static final float MIN_ACCURACY = 1.0f;
private static final float MIN_LAST_READ_ACCURACY = 1;
private LocationRequest mLocationRequest;
private Location mBestReading;
TextView tv;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!servicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv1);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(POLLING_FREQ);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onPause() {d
super.onPause();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
tv.setText(location + "");
// Determine whether new location is better than current best
// estimate
if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {
mBestReading = location;
if (mBestReading.getAccuracy() < MIN_ACCURACY) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
#Override
public void onConnected(Bundle dataBundle) {
// Get first reading. Get additional location updates if necessary
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
//Schedule a runnable to unregister location listeners
#Override
public void run() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);
}
}, ONE_MIN, TimeUnit.MILLISECONDS);
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
private Location bestLastKnownLocation(float minAccuracy, long minTime) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
// Get the best most recent location currently available
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//tv.setText(mCurrentLocation+"");
if (mCurrentLocation != null) {
float accuracy = mCurrentLocation.getAccuracy();
long time = mCurrentLocation.getTime();
if (accuracy < bestAccuracy) {
bestResult = mCurrentLocation;
bestAccuracy = accuracy;
bestTime = time;
}
}
// Return best reading or null
if (bestAccuracy > minAccuracy || bestTime < minTime) {
return null;
}
else {
return bestResult;
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private boolean servicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
}
else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0).show();
return false;
}
}
}
If you want to run inside a background service and take the data in foreground use the below one, it is tested and verified.
public class MyService extends Service
implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private static final int ASHIS = 1234;
Intent intentForPendingIntent;
HandlerThread handlerThread;
Looper looper;
GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRrequest;
private static final int UPDATE_INTERVAL = 1000;
private static final int FASTEST_INTERVAL = 100;
private static final int DSIPLACEMENT_UPDATES = 1;
;
private Handler handler1;
private Runnable runable1;
private Location mLastLocation;
private float waitingTime;
private int waiting2min;
private Location locationOld;
private double distance;
private float totalWaiting;
private float speed;
private long timeGpsUpdate;
private long timeOld;
private NotificationManager mNotificationManager;
Notification notification;
PendingIntent resultPendingIntent;
NotificationCompat.Builder mBuilder;
// Sets an ID for the notification
int mNotificationId = 001;
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "speedExceeded";
private final Handler handler = new Handler();
Intent intentforBroadcast;
int counter = 0;
private Runnable sendUpdatesToUI;
#Nullable
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(MyService.this, "binder", Toast.LENGTH_SHORT).show();
return null;
}
#Override
public void onCreate() {
showNotification();
intentforBroadcast = new Intent(BROADCAST_ACTION);
Toast.makeText(MyService.this, "created", Toast.LENGTH_SHORT).show();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
createLocationRequest();
mGoogleApiClient.connect();
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void showNotification() {
mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_media_play)
.setContentTitle("Total Waiting Time")
.setContentText(totalWaiting+"");
Intent resultIntent = new Intent(this, trackingFusion.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
startForeground(001, mBuilder.getNotification());
}
#Override
public void onLocationChanged(Location location) {
//handler.removeCallbacks(runable);
Toast.makeText(MyService.this, "speed" + speed, Toast.LENGTH_SHORT).show();
timeGpsUpdate = location.getTime();
float delta = (timeGpsUpdate - timeOld) / 1000;
if (location.getAccuracy() < 100) {
speed = location.getSpeed();
distance += mLastLocation.distanceTo(location);
Log.e("distance", "onLocationChanged: " + distance);
//mLastLocation = location;
//newLocation = mLastLocation;
Log.e("location:", location + "");
//speed = (long) (distance / delta);
locationOld = location;
mLastLocation = location;
diaplayViews();
}
diaplayViews();
/*if (map != null) {
map.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}*/
}
private void createLocationRequest() {
mLocationRrequest = new LocationRequest();
mLocationRrequest.setInterval(UPDATE_INTERVAL);
mLocationRrequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRrequest.setSmallestDisplacement(DSIPLACEMENT_UPDATES);
}
private void methodToCalculateWaitingTime() {
if (handler1 != null) {
handler1.removeCallbacks(runable1);
}
Log.e("Here", "here1");
handler1 = new Handler(Looper.getMainLooper());
runable1 = new Runnable() {
public void run() {
Log.e("Here", "here2:" + mLastLocation.getSpeed());
if (mLastLocation != null) {
diaplayViews();
if ((mLastLocation.getSpeed() == 0.0)) {
increaseTime();
} else {
if (waitingTime <= 120) {
waiting2min = 0;
}
}
handler1.postDelayed(this, 10000);
} else {
if (ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyService.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;
}
locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastLocation = locationOld;
}
}
};
handler1.postDelayed(runable1, 10000);
}
private void diaplayViews() {
float price = (float) (14 + distance * 0.5);
//textDistance.setText(waitingTime);a
}
private void increaseTime() {
waiting2min = waiting2min + 10;
if (waiting2min >= 120)
{
if (waiting2min == 120) {
waitingTime = waitingTime + 2 * 60;
} else {
waitingTime = waitingTime + 10;
}
totalWaiting = waitingTime / 60;
showNotification();
Log.e("waiting Time", "increaseTime: " + totalWaiting);
}
}
#Override
public void onDestroy() {
Toast.makeText(MyService.this, "distroyed", Toast.LENGTH_SHORT).show();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(Bundle bundle) {
Log.e("Connection_fusion", "connected");
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
private void startLocationUpdates() {
Location location = plotTheInitialMarkerAndGetInitialGps();
if (location == null) {
plotTheInitialMarkerAndGetInitialGps();
} else {
mLastLocation = location;
methodToCalculateWaitingTime();
}
}
private Location plotTheInitialMarkerAndGetInitialGps() {
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 null;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRrequest, this);
locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if ((locationOld != null)) {
mLastLocation = locationOld;
timeOld = locationOld.getTime();
} else {
startLocationUpdates();
}
return mLastLocation;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
Toast.makeText(MyService.this, "start command", Toast.LENGTH_SHORT).show();
sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 10000); // 5 seconds
}
};
handler.postDelayed(sendUpdatesToUI, 10000); // 1 second
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
#Override
public void onStart(Intent intent, int startId) {
sendUpdatesToUI = new Runnable() {
public void run() {
Log.e("sent", "sent");
DisplayLoggingInfo();
handler.postDelayed(this, 5000); // 5 seconds
}
};
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
Log.i("LocalService", "Received start id " + startId + ": " + intent);
super.onStart(intent, startId);
}
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intentforBroadcast.putExtra("distance", distance);
LocalBroadcastManager.getInstance(this).sendBroadcast(intentforBroadcast);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
I made some changes in above code to look for a location fix by both GPS and Network for about 5sec and give me the best known location out of it.
public class LocationService implements LocationListener {
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
final static long MIN_TIME_INTERVAL = 60 * 1000L;
Location location;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
protected LocationManager locationManager;
private CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
stopUsingGPS();
}
};
public LocationService() {
super(R.id.gps_service_id);
}
public void start() {
if (Utils.isNetworkAvailable(context)) {
try {
timer.start();
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
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 tempLocation = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (tempLocation != null
&& isBetterLocation(tempLocation,
location))
location = tempLocation;
}
}
if (isGPSEnabled) {
locationManager.requestSingleUpdate(
LocationManager.GPS_PROVIDER, this, 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 tempLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (tempLocation != null
&& isBetterLocation(tempLocation,
location))
location = tempLocation;
}
}
} catch (Exception e) {
onTaskError(e.getMessage());
e.printStackTrace();
}
} else {
onOfflineResponse(requestData);
}
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(LocationService.this);
}
}
public boolean canGetLocation() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return isGPSEnabled || isNetworkEnabled;
}
#Override
public void onLocationChanged(Location location) {
if (location != null
&& isBetterLocation(location, this.location)) {
this.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 Object getResponseObject(Object location) {
return location;
}
public static boolean isBetterLocation(Location location,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > MIN_TIME_INTERVAL;
boolean isSignificantlyOlder = timeDelta < -MIN_TIME_INTERVAL;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location,
// use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must
// be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return true;
}
return false;
}
}
In the above class, I am registering a location listener for both GPS and network, so an onLocationChanged call back can be called by either or both of them multiple times and we just compare the new location fix with the one we already have and keep the best one.
there are better ways to do it as mentioned on android developer sites
http://developer.android.com/guide/topics/location/strategies.html

Categories

Resources