onActivityResult resultCode is always zero for GoogleApiClient Location request - android

Why is resultCode from onActivityResult for Location Request using Google API Client always zero?
Android Mobile Application connecting to the API Client:
final static int REQUEST_LOCATION =2001;
private void getGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
Defining location request:
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(30000);
mLocationRequest.setFastestInterval(10000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Loc_Update();
}
Requesting Location using Google APi Client
private void Loc_Update() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest)
.setAlwaysShow(true);
Task<LocationSettingsResponse> task = LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
//Do what you want with location
//like update camera
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16f));
}
}
},null);
}
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(MainActivity.this, 2001);
break;
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible 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;
}
}}
});
task.addOnCanceledListener(new OnCanceledListener() {
#Override
public void onCanceled() {
}
});
}
//GoogleApiClient.ConnectionCallbacks
public void onConnected(Bundle bundle) {
createLocationRequest();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(getApplicationContext(),"Failed to connect ",Toast.LENGTH_SHORT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
switch (requestCode)
{
case REQUEST_LOCATION:
switch (resultCode)
{
case Activity.RESULT_OK:
{
Toast.makeText(getApplicationContext(),"user responded yes ",Toast.LENGTH_SHORT);
break;
}
case Activity.RESULT_CANCELED:
{
Toast.makeText(getApplicationContext(),"user responded No ",Toast.LENGTH_SHORT);
break;
}
default:
{
break;
}
}
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
When clicking on "ok", the resultCode should be -1 and "No Thanks", the resultCode should be 0

Related

Prompt user with a popup for turning on GPS

So I notice Google Map was able to prompt the user to enable the GPS. I tried this method below and I got the prompt once and then nothing... Why aren't the onActivityResult() method isn't called anymore?
public void checkLocationEnable() {
Log.e(TAG, "Here");
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
final PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
final LocationSettingsStates state = locationSettingsResult.getLocationSettingsStates();
Log.e(TAG, "state:" + state);
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.e(TAG, "HERE-1");
// All location settings are satisfied. The client can
// initialize location requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.e(TAG, "REQUIRED");
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
getActivity(),
GenericActivity.REQUEST_LOCATION);
} 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.
Log.e(TAG, "UNAVALAIBLE");
break;
}
}
});
}
As far as I understand you try to enable the location.
Step by step process.
First you need to set a GoogleApiClient and implements GoogleApiClient CallBackMethods.
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
CallBack Methods
#Override
public void onConnected(Bundle bundle) {
Log.d("OnConnected", "Connection successful");
settingsrequest();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
As soon as the googleapiclient connects, onconnected method will invoke and settingsRequest method will call.
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
LocationRequest locationRequest;
public void settingsrequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setNumUpdates(1);
locationRequest.setExpirationDuration(20000);
locationRequest.setFastestInterval(500);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, 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: {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
}
// 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(MainTab.this, 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;
}
}
});
}
status.startResolutionForResult(MainTab.this, REQUEST_CHECK_SETTINGS) will show a dialog requesting location.
#Override
protected 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:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
break;
case Activity.RESULT_CANCELED:
break;
}
break;
}
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this) will set a listener for the location cahnged.
As the location changed onLocationChanged method will invoke.
#Override
public void onLocationChanged(Location location) {
prevLocation = location;
//Do you work
}
Hope this will helps you.

Fused Location Provider : getLastKnowLocation is returning null and onLocationChange is not getting called?

There is a lot of similar question and blogs but non of those help me to solve my problem. I have written the code below but the location returning by the getLastKnowLocation is null it's okay sometimes getLastKnowLocation can return null with some conditions. In my code, I requested new updated location if getLastKnowLocation method return null but the onLocationChanged method is not getting called.
Here is the code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_provider_layout);
Intent intent = getIntent();
checkPlayServices();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
mLocationRequest= LocationRequest.create()
.setInterval(10000)
.setFastestInterval(5000)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else
finish();
return false;
}
return true;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (mGoogleApiClient.isConnected())
Log.d(LOCATION_TAG, "Google api is connected");
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
boolean isLocationOn = ActivityCompat.checkSelfPermission(LocationProviderClass.this, Manifest.permission_group.LOCATION) != PackageManager.PERMISSION_GRANTED;
if (!(isLocationOn)) {
String [] runTimePermission=new String[]{Manifest.permission_group.SMS};
requestPermissions(runTimePermission, LOCATION_REQUESTCODE);
}
else
computeLocation();
} else
computeLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(LocationProviderClass.this, STATUS_INT);
} catch (IntentSender.SendIntentException e) {
Log.d(LOCATION_TAG, "error in startResolutionForResult");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.d(LOCATION_TAG, "Location setting is canceled");
break;
default:
Log.d(LOCATION_TAG,"Location setting enters into default");
}
}
});
computeLocation();
}
#Override
public void onConnectionSuspended(int i) {
Log.d("PERMISSION_TAG","connection suspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (!mGoogleApiClient.isConnected())
Log.d(PERMISSION_TAG, "ON connection failed error");
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
private void computeLocation() {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Fine access location is not granted", Toast.LENGTH_LONG).show();
}
}
location=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(location==null) {
Toast.makeText(getApplicationContext(), "getLastLocation return null", Toast.LENGTH_LONG).show();
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
Toast.makeText(getApplicationContext(), "getLastLocation return"+location.getLatitude()+" "+location.getLongitude(), Toast.LENGTH_LONG).show();
//do what ever you want here
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_REQUESTCODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
computeLocation();
}
else {
Log.d(RUNTIME_PERMISSION_ERROR,"Error in runtime error");
Toast.makeText(getApplication(),"The app need location permission", Toast.LENGTH_LONG).show();
}
break;
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == STATUS_INT) {
switch (resultCode) {
case Activity.RESULT_OK: {
Toast.makeText(getApplicationContext(), "User enabled location permission", Toast.LENGTH_LONG).show();
computeLocation();
break;
}
case Activity.RESULT_CANCELED: {
Toast.makeText(getApplication(), "You canceled the permission the app is not going to work", Toast.LENGTH_LONG).show();
break;
}
default:
Toast.makeText(getApplication(), "Permission error", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onLocationChanged(Location location) {
Log.d(LOCATION_TAG, "onLocationChanged method called");
Toast.makeText(getApplicationContext(), "onLocationChanged method called"+location.getLongitude()+" "+location.getLatitude(), Toast.LENGTH_LONG).show();
}
#Override
public void onStart() {
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
this.mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (this.mGoogleApiClient.isConnected())
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
this.mGoogleApiClient.disconnect();
}
}
you have to add Listener in order to tell the device you have an action when you got a change location.
do something like that
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
...
}
locationManager.requestLocationUpdates(GPS_PROVIDER, intervall, distance, listener);

Constant location request on startup

So I am trying to make an app in Android Studio which needs location settings turned on and therefor I wanted to make that window pop up in onCreate that asks if you would like to turn on location settings. But after you press Abort I dont know how to bring that window back again...
Is there a way to do so? Because I have seen in some apps like Tinder, that they won't start until you have pressed a few times on the Abort button.
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
PendingResult<LocationSettingsResult> result;
final static int REQUEST_LOCATION = 199;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
Log.d("Status: ", result.toString());
//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(
MainActivity.this,
REQUEST_LOCATION);
} 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;
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d("onActivityResult()", Integer.toString(resultCode) + "," + Integer.toBinaryString(requestCode));
switch (requestCode)
{
case REQUEST_LOCATION:
switch (resultCode)
{
case Activity.RESULT_OK:
{
// All required changes were successfully made
Toast.makeText(MainActivity.this, "Location enabled by user!", Toast.LENGTH_LONG).show();
break;
}
case Activity.RESULT_CANCELED:
{
// The user was asked to change settings, but chose not to
Toast.makeText(MainActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
break;
}
default:
{
break;
}
}
break;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
Create methode
private void mGoogleApiClientConnect(){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
and call it here :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClientConnect();
}
and here :
case Activity.RESULT_CANCELED:
{
Toast.makeText(MainActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
mGoogleApiClient.connect();
break;
}

How to disable location in android?

i want to switched on location like OLA cab so i am using this code:
private GoogleApiClient googleApiClient;final static int REQUEST_LOCATION = 199;public boolean noLocation() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// buildAlertMessageNoGps();
enableLoc();
return true;
}
return false;
}private void enableLoc() {if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Timber.v("Location error " + connectionResult.getErrorCode());
}
}).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);
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.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
(Activity) context, REQUEST_LOCATION);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_LOCATION:
switch (resultCode) {
case Activity.RESULT_CANCELED: {
finish();
break;
}
default: {
break;
}
}
break;
}
}
now it is working fine but i want to disable location using dialog, don't want to use intent for open setting screen.How is it possible?

Requesting for Location Services Android

I am using this code to for user to activate the location services. I want to show user dialog to accept to enable location services then redirect them to the LOCATION_SETTINGS Page. But Without the user accepting it from user it redirects to location settings.
if(lm==null)
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try{
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){}
if(!gps_enabled && !network_enabled){
dialog = new AlertDialog.Builder(this);
dialog.setMessage(this.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(this.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(this.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
finish();
}
});
dialog.show();
}
As far as I understand you try to enable the location.
You can show a dialog to enable the location instead of redirect them to LOCATION_SETTING page.
Step by step process.
First you need to set a GoogleApiClient and implements GoogleApiClient CallBackMethods.
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
CallBack Methods
#Override
public void onConnected(Bundle bundle) {
Log.d("OnConnected", "Connection successful");
settingsrequest();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
As soon as the googleapiclient connects, onconnected method will invoke and settingsRequest method will call.
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
LocationRequest locationRequest;
public void settingsrequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setNumUpdates(1);
locationRequest.setExpirationDuration(20000);
locationRequest.setFastestInterval(500);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, 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: {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
}
// 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(MainTab.this, 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;
}
}
});
}
status.startResolutionForResult(MainTab.this, REQUEST_CHECK_SETTINGS) will show a dialog requesting location.
#Override
protected 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:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
break;
case Activity.RESULT_CANCELED:
break;
}
break;
}
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this) will set a listener for the location cahnged.
As the location changed onLocationChanged method will invoke.
#Override
public void onLocationChanged(Location location) {
prevLocation = location;
//Do you work
}
Hope this will helps you.

Resources