Skip to content

Instantly share code, notes, and snippets.

@rakesh1988
Created July 4, 2016 11:44
Show Gist options
  • Save rakesh1988/03cd9f909542f7b078c921093ef9ade9 to your computer and use it in GitHub Desktop.
Save rakesh1988/03cd9f909542f7b078c921093ef9ade9 to your computer and use it in GitHub Desktop.
Get user location via fusedlocation API
package com.example.rakesh.navigation_example;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
public class LocationTest extends AppCompatActivity
implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener
{
GoogleApiClient mGoogleApiClient = null;
LocationRequest mLocationRequest = null;
PendingResult<LocationSettingsResult> result = null;
protected static final int REQUEST_CHECK_SETTINGS = 9001;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_test);
Button buttonLocation = (Button) findViewById(R.id.buttonLocation);
buttonLocation.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
checkLocationSetting();
}
});
buildGoogleApiClient();
setupLocationRequestVariable();
}
private synchronized void buildGoogleApiClient()
{
if (mGoogleApiClient == null)
{
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
requestNewLocationBySettingLocationReq();// here api client will make a connection
}
}
private void requestNewLocationBySettingLocationReq()
{
if (!mGoogleApiClient.isConnected())
{
mGoogleApiClient.connect();
}
else
{
setupLocationRequest();
//setupLocationRequest();
}
}
private void setupLocationRequestVariable()
{
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 20 seconds, in milliseconds
.setFastestInterval(5 * 1000) // 10 second, in milliseconds
;
}
public void setupLocationRequest()
{
LocationServices.FusedLocationApi.
requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnected(@Nullable Bundle bundle)
{
getLocationIfAvailable();
}
public void getLocationIfAvailable()
{
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (lastLocation != null)
{
updateMapWithCurrentLocation(lastLocation);
}
// if not available, then check if the gps et al is enabled via settings api
else
{
checkLocationSetting();
}
}
public void checkLocationSetting()
{
setupLocationRequestVariable();
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();
switch (status.getStatusCode())
{
case LocationSettingsStatusCodes.SUCCESS:
requestNewLocationBySettingLocationReq();// since all the connections are positive, try to get location
// even if GPS is enabled this should be called
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(
LocationTest.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;
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
switch (requestCode)
{
case REQUEST_CHECK_SETTINGS:
{
final LocationSettingsStates states = LocationSettingsStates.fromIntent(intent);
switch (resultCode)
{
case Activity.RESULT_OK:
// All required changes were successfully made
requestNewLocationBySettingLocationReq();
break;
case Activity.RESULT_CANCELED:
{// The user was asked to change settings, but chose not to
if (!states.isLocationUsable())
{
if (!states.isGpsUsable())
{
Log.d("", "Please enable GPS and try again.");
}
}
break;
}
default:
break;
}
break;
}
}
}
private void updateMapWithCurrentLocation(Location lastLocation)
{
TextView textViewLocation = (TextView) findViewById(R.id.textViewLocation);
textViewLocation.setText(lastLocation.getLatitude() + "," + lastLocation.getLongitude());
}
@Override
public void onConnectionSuspended(int i)
{
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location)
{
if (location != null)
{
stopLocationUpdates();
updateMapWithCurrentLocation(location);
}
}
protected void stopLocationUpdates()
{
if (mGoogleApiClient.isConnected())
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment