What is Fused Location?
Specifically, use the fused location provider to retrieve the device's last known location.
The fused location provider is one of the location APIs in Google Play services.
It manages the underlying location technology and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power.
It also optimizes the device's use of battery power.
The fused location provider is one of the location APIs in Google Play services.
It manages the underlying location technology and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power.
It also optimizes the device's use of battery power.
Set up Google Play services
To access the fused location provider, your app's development project must include Google Play services. Download and install the Google Play services component via the SDK Manager and add the library to your project. For details, see below images.
In above example choose yellow marked for SDK Manager and Blue selected Google Play services to install if it ins't.
Specify app permissions
Specify app permissions
Apps that use location services must request location permissions and other location.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
above location must be inside Manifest.xml. Outside the Application Tag.
Add Dependecies
Add below dependecies in your Module.app(build.gradle).
implementation "com.google.android.gms:play-services-location:17.0.0"
updated gradle version you will get for Google Location and Activity Recognition.
All the settings part done for your apps. Now we will jump on the actual code to get the current location.
All the settings part done for your apps. Now we will jump on the actual code to get the current location.
Initialize all variable in your Activity or Fragment.
private static final String TAG = "sushildlh";
private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final int LOCATION_PERMISSION = 1;
private final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
Call these things in your onCreate in Activity or onCreateView in Fragment.
mSettingsClient = LocationServices.getSettingsClient(this);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
getLastLocation();// this method will show your location
Here is the getLastLocation Method .
private void getLastLocation() {
getPackageManager().checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, getPackageName());
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
if (location != null) {
Toast.makeText(MainActivity.this, location.getLongitude() + "," + location.getLatitude(), Toast.LENGTH_SHORT).show();
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
} else {
Toast.makeText(MainActivity.this, "Location searching ...", Toast.LENGTH_SHORT).show();
startLocationUpdates();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error trying to get last GPS location", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
And Here is startLocationUpdates() method if location get null value. This method will call
requestLocationUpdates with Looper thread untill your device get the location.
value.
private void startLocationUpdates() {
// Begin by checking if the device has the necessary location settings.
mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i(TAG, "All location settings are satisfied.");
//noinspection MissingPermission
getPackageManager().checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, getPackageName());
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
getLastLocation();
}
})
.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
"location settings ");
try {
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(MainActivity.this, 0x1);
} catch (IntentSender.SendIntentException sie) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
// mRequestingLocationUpdates = false;
}
}
});
}
That is all. If any help related to this post please contact me.
Go through Git Hub Repo with above code Location Sample.
Go through Git Hub Repo with above code Location Sample.
Thank you, guys.
Enjoy coding.
No comments:
Post a Comment