I have created the below code to simply get the most recent latitude and longitude without needing the user to turn on GPS but simply rely on wifi or network for positioning. Upon running the app, it simply returns the toast "The Lat is 0.0 and Long is 0.0". I know this should work because I have downloaded the sample code here: https://github.com/googlesamples/android-play-location/tree/master/BasicLocationSample, and adapted to work in my code.
How can I get this to work?
public class MainActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, OnConnectionFailedListener {
public static double lat;
public static double lng;
ViewPager viewPager = null;
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
String text = "The Lat is " + lat
+ " and Long is " + lng;
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG).show();
};
// Assign list to actionbar
actionBar.setListNavigationCallbacks(aAdpt, null); // DEPRACATED
}
/**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
} else {
Toast.makeText(this,"No location detected", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
mGoogleApiClient.connect();
}
}
}
"lat", "lng", and "mLastLocation" isn't set or valid until onConnected() has been executed. You need to understand that this operation is asynchronous -- that is, the location doesn't come back immediately but is provided later on. This would have been obvious if you tested whether "mLastLocation" was null or not when you made that toast.
Related
So, I have a JobService that is being called on background. However I need it to get the current location and send it to the webservice. The webservice is working great when I send static data. However getting the location is being a problem. The location object is always null. This is what I've been trying.
public class GPSBackgroundJobService extends JobService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private String LOGSERVICE = "GPS";
private InspectorsLogic mInspectorsLogic;
ParsoContext mContext;
private GoogleApiClient mGoogleApiClient;
ParsoLocationListener mLocationListener;
Location mLastLocation;
Double longitude;
Double latitude;
#Override
public void onCreate() {
super.onCreate();
Log.i(LOGSERVICE, "onCreate");
mContext = (ParsoContext) getApplicationContext();
mInspectorsLogic = new InspectorsLogic(mContext);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
#Override
public boolean onStartJob(JobParameters job) {
Log.i(LOGSERVICE, "onStartJob called");
mGoogleApiClient.connect();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation!=null) {
latitude = mLastLocation.getLatitude();
longitude =mLastLocation.getLongitude();
sendGPSTask mSendGPSTask = new sendGPSTask();
mSendGPSTask.execute(Double.toString(latitude), Double.toString(longitude));
}else{
Log.e(LOGSERVICE, "Lat and Long are null");
}
return false;
}
#Override
public boolean onStopJob(JobParameters job) {
mGoogleApiClient.disconnect();
return false;
}
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
getLastLocation returns null if it doesn't have a location fix yet- which means unless you're using GPS elsewhere, it almost always returns null. To make sure you get a location use getLocationUpdates and wait for the location to fix (this will not be instant, depending on atmospheric conditions, whether you're inside or out, etc this could take a few seconds to a minute or so- or just never happen).
Apparently the code is fine, to make it work this is what I did:
check the permissions of the app (the location one needs to be activated)
change your GPS settings to (mobile data and wifi one)
making this with the current code posted on the question, made it.
This question may be asked many time but I couldn't find any solution for it.
I need to get the user's location in background for ever 15 min.
It works fine when the GPS is turned on but when the GPS is turned off, the app is not getting location updates. I need it to get at least the network location or wifi location.
How can I achieve this with fused location API.?
Location manager has this functionality but in fused location. Because Google suggests developers use Location from the play services API, I don't want to use location manager.
How can I achieve this so let me post what I tried so far:
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* Created by 4264 on 14-10-2016.
*/
public class Locationlistener implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener {
private Location mlocation; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
private FusedLocationProviderApi fusedLocationProviderApi;
private LocationRequest locationRequest;
public Locationlistener(Context c)
{
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
locationRequest.setInterval(1);
locationRequest.setFastestInterval(1);
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double getLatitude(){
if(mlocation != null){
latitude = mlocation.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (mlocation != null) {
longitude = mlocation.getLongitude();
}
// return longitude
return longitude;
}
public Location GetLocationBlocking() throws InterruptedException {
// String lat=String.valueOf(moCurrentLocation.getLatitude());
// String longt=String.valueOf(moCurrentLocation.getLongitude());
// Toast.makeText(oContext,"Lat"+lat+"long"+longt,Toast.LENGTH_SHORT).show();
return mlocation;
}
#Override
public void onConnected(Bundle bundle) {
Location oLocation = LocationServices.FusedLocationApi.getLastLocation(mGAC);
if (mGAC != null) {
mlocation = oLocation;
getLatitude();
getLongitude();
if (oLocation != null){
Log.d("lat",String.valueOf(mlocation.getLatitude()));
Log.d("long",String.valueOf(mlocation.getLongitude()));
}
else{
LocationServices.FusedLocationApi.requestLocationUpdates(mGAC, locationRequest, this);
} }}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mlocation=location;
}
}
i don't understand when you saying you don't want use location manager and GPS...look at this Location Strategies... based on this doc we have 3 strategy to access location:
Gps
Network Location Provider
or using both
but for your location problem this is my offer:
Inside an Activity, put the following to connect and start receiving location updates:
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the location client to start receiving updates
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
protected void onStart() {
super.onStart();
// Connect the client.
mGoogleApiClient.connect();
}
protected void onStop() {
// Disconnecting the client invalidates it.
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
// only stop if it's connected, otherwise we crash
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
public void onConnected(Bundle dataBundle) {
// Get last known recent location.
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
}
// Begin polling for new location updates.
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(this, "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
}
// Trigger new location updates at interval
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
and then register for location updates with onLocationChanged:
public void onLocationChanged(Location location) {
// New location has now been determined
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
// You can now create a LatLng Object for use with maps
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
For more information on the Fused Location API, refer to Make ypur app Location Aware
Troubleshooting Location Updates
Location updates should always be done using the GoogleApiClient leveraging the LocationServices.API as shown above. Do not use the older Location APIs which are much less reliable. Even when using the correct FusedLocationApi, there are a lot of things that can go wrong. Consider the following potential issues:
Did you add the necessary permissions? Make sure your app has
INTERNET and ACCESS_COARSE_LOCATION permissions to ensure that
location can be accessed as illustrated in the guide above.
Are you getting null when calling
LocationServices.FusedLocationApi.getLastLocation? This is normal
since this method only returns if there is already a location
recently retrieved by another application. If this returns null, this
means you need start receiving location updates with
LocationServices.FusedLocationApi.requestLocationUpdates before
receiving the location as shown above.
Are you trying to get location on the genymotion emulator? Ensure
you've enabled GPS and configured a lat/lng properly. Try restarting
the emulator if needed and re-enabling GPS or trying a device (or the
official emulator) instead to rule out genymotion specific issues.
I want to make a service (background operation) in Android to track the location of a device every now and then and store it on SharedPreference or send it to my server when location changes. I came accross this code from Get current location name of user without using gps or internet but by using Network_Provider in android and Android Developers - Getting the Last Known Location.
This is the code:
public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
protected static final String TAG = "MainActivity";
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
protected String mLatitudeLabel;
protected String mLongitudeLabel;
protected TextView mLatitudeText;
protected TextView mLongitudeText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mLatitudeLabel = getResources().getString(R.string.latitude_label);
mLongitudeLabel = getResources().getString(R.string.longitude_label);
mLatitudeText = (TextView) findViewById((R.id.latitude_text));
mLongitudeText = (TextView) findViewById((R.id.longitude_text));
buildGoogleApiClient();
}
/**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
Log.e("Location", "not null");
makeUseOfNewLocation(mLastLocation);
} else {
Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
// should request new one
// location should be enabled
Log.i(TAG,
"No location data previously acquired.. should request!");
Toast.makeText(this,
"Requesting location data ..",
Toast.LENGTH_SHORT).show();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient,
locationRequest,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.e("Location", "not null");
makeUseOfNewLocation(location);
}
});
// TODO: use result to retrieve more info
Toast.makeText(this, result.toString(),Toast.LENGTH_LONG);
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
private void makeUseOfNewLocation(Location location) {
// do your stuff here
mLatitudeText.setText(String.format("%s: %f", mLatitudeLabel,
location.getLatitude()));
mLongitudeText.setText(String.format("%s: %f", mLongitudeLabel,
location.getLongitude()));
}
}
My question is can this code be a Service by just extending Service on this class. Will this work and be able to track the device's location every now and then on the background
As per Google's documentation, you will need to use a PendingIntent in onConnected to make sure you have a background service running even when the app is off the screen.
https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi
public abstract PendingResult requestLocationUpdates (GoogleApiClient client, LocationRequest request, PendingIntent callbackIntent)
Requests location updates with a callback on the specified PendingIntent.
This method is suited for the background use cases, more specifically for receiving location updates, even when the app has been killed by the system. In order to do so, use a PendingIntent for a started service. For foreground use cases, the LocationListener version of the method is recommended, see requestLocationUpdates(GoogleApiClient, LocationRequest, LocationListener).
My previous method is create an intent which is included in your pendingIntent, then indicates in the intent to pass from your current activity to a Handler class. In the handler class which extends the IntentService, you will be able to get whatever location information in the onHandle method.
You can take a look at one of my previous questions for reference:
FusedLocationProvider using intentservice for background location update: location update does not work when pendingintent has a bundle added
I'm developing an Android app, and I need to get latitude and longitude of the user.
I googled and found that Google API is the best for this, and I found a tutorial on this link: http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/
How I don't need location updates (just click in a button, and get the location), I just copied this piece of code from tutorial:
public class MainActivity1 extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// UI elements
private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblLocation = (TextView) findViewById(R.id.lblLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
}
// Show location button click listener
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
}
/**
* Method to display the location on UI
* */
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation
.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
/**
* Creating google api client object
* */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Method to verify google play services on the device
* */
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
}
and it worked!!!
But I want to create a method (in another class) that get the current location and return it (instead of doing this inside activity).
So, I modified what I did above, and finished with the following:
public class UserLocation implements ConnectionCallbacks, OnConnectionFailedListener {
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
public HashMap<String, Double> getUserLocation(Activity act) {
HashMap<String, Double> getLocation = new HashMap<>();
if (checkPlayServices(act)) {
buildGoogleApiClient(act);
}
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
getLocation.put("latitude", latitude);
getLocation.put("longitude", longitude);
return getLocation;
} else {
Log.i("FAIL: ", "(Couldn't get the location. Make sure location is enabled on the device)");
return null;
}
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient(Activity act) {
mGoogleApiClient = new GoogleApiClient.Builder(act)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices(Activity act) {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(act);
if (resultCode != ConnectionResult.SUCCESS) {
return false;
}
return true;
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i("Fail: ", "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
}
And I call it from the main Activity this way:
HashMap<String, Double> userLoc = ul.getUserLocation(this);
ul.getUserLocation(getActivity());
But with this new class, I don't get the location... I debuged, and saw that mLastLocation is always null...
Can somebody tell me what I'm doing wrong?
In the activity you get last location after Google API client connected and it is right. In UserLocation class you are trying to get location before connection established and it is wrong.
From the docs:
If not connected null will be returned.
You need to move getting location in onConnected() method and somehow notify the activity. You can create callback for it or simply let the activity implement ConnectionCallbacks instead of UserLocation.
I am going in circles to just get the current location in android SDk ..
i used this repository from android training site
https://github.com/googlesamples/android-play-location/tree/master/BasicLocationSample
but i receive no location found error when i start app on emulator
i used the DDMS send,
and i went to settings on emulator and the location settings is on .
.. what have i missed ??
Update: The code :
ublic class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
protected static final String TAG = "basic-location-sample";
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
protected TextView mLatitudeText;
protected TextView mLongitudeText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mLatitudeText = (TextView) findViewById((R.id.latitude_text));
mLongitudeText = (TextView) findViewById((R.id.longitude_text));
buildGoogleApiClient();
}
/**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
} else {
Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
public void getLoc (View view){
mGoogleApiClient.connect();
}
}