Skip to content

Instantly share code, notes, and snippets.

@cartermp
Last active August 29, 2015 14:07
Show Gist options
  • Save cartermp/d523e54a722b805abeb9 to your computer and use it in GitHub Desktop.
Save cartermp/d523e54a722b805abeb9 to your computer and use it in GitHub Desktop.
Contains basic functionality for retrieving a location in latitude and longitude.
/*
* This class explicitly implements the ConnectionCallbacks and
* OnCorrectionFailedListener interfaces. What this means is that
* this class will implement what happens when a connection to
* Google Play Services fails, and what happens when a connection
* succeeds.
*/
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private LocationClient mLocationClient;
private Location mCurrentLocation;
/*
* Define a request code to send to Google Play services.
* This code is returned in Activity.onActivityResult.
*/
private final static int
CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
/*
* This method explicitly provies the implementation for
* when the phone connects to Google Play Services.
*/
@Override
public void onConnected(Bundle dataBundle) {
// At this point, you can request the current location,
// or start periodic location updates.
mCurrentLocation = mLocationClient.getLastLocation();
if (mCurrentLocation != null) {
Toast.makeText(this, "Current lat/long: "
+ mCurrentLocation.getLatitude()
+ ","
+ mCurrentLocation.getLongitude(),
Toast.LENGTH_SHORT).show();
} else {
// Should rarely happen, according to Google
Toast.makeText(this, "Couldn't get a location!", Toast.LENGTH_SHORT).show();
}
}
/*
* This method explicitly implements what should happen
* when the phone disconnects from Google Play Services.
*/
@Override
public void onDisconnected() {
Toast.makeText(this, "Disconnected. Reconnect.", Toast.LENGTH_SHORT).show();
// Perhaps something else which lets the user know more
// about the problem.
}
/*
* Explicitly implements what should happen on the phone
* if the attempt to access Location Service fails.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* GPlay services can resolve some errors it detects.
* If the error has resolution,
* try sending an Intent to start a GPlay services
* activity that can resolve the error.
*/
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Connection failed. Error Code: "
+ connectionResult.getErrorCode(),
Toast.LENGTH_SHORT).show();
}
}
/*
* Called when the application is first run
* (and other times ... see Activity Lifecycle for more details)
*
* Instantiates the Location Client, which will then call our
* callbacks asynchronously.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
if (servicesConnected()) {
mLocationClient = new LocationClient(this, this, this);
if (!mLocationClient.isConnected() || !mLocationClient.isConnecting() {
mLocationClient.connect();
}
}
}
/*
* Called when this activity is visible.
*/
@Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
}
/*
* Called when the activity is no longer visible.
*/
@Override
protected void onStop() {
mLocationClient.disconnect();
super.onStop();
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services.
*/
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK :
/*
* Try the request again
*/
break;
}
}
}
/*
* Utility method to check if it's possible to get Location info.
* Launches an error dialog if it can't.
*/
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode == ConnectionResult.SUCCESS) {
Log.d("Location Updates",
"Google Play services is available.");
return true;
// Google Play services was not available for some reason.
// resultCode holds the error code.
} else {
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (errorDialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(),"Location Updates");
}
return false;
}
}
/*
* Nested static class for displaying location-related error dialogs.
*
* Nested static classes which do one, simple thing, are commonly
* implemented in Java code. Personally, I prefer not to do this,
* but you will see this out in the world if you work with Java.
*/
public static class ErrorDialogFragment extends DialogFragment {
private Dialog mDialog;
// Default constructor. Required method in this case.
public ErrorDialogFragment() {
super();
mDialog = null;
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment