1

How do i use locationclient class along with requestLocationUpdates(LocationRequest, LocationListener) to get location updates in android? I've tried the following code, but its not working. can any one help me with this? Where's the mistake, Thanks in advance.

public class MainActivity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener {
private final static int  CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
LocationClient mLocationClient;
Location mCurrentLocation;
LocationRequest mLocationRequest;
ArrayList<Location> list = new ArrayList<Location>();
private static String msg;
private static final int MILLISECONDS_PER_SECOND = 1000; // Milliseconds per second
public static final int UPDATE_INTERVAL_IN_SECONDS = 300;// Update frequency in seconds
private static final long UPDATE_INTERVAL =  MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;  // Update frequency in milliseconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 60;  // The fastest update frequency, in seconds
// A fast frequency ceiling in milliseconds
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
//private EditText text; 
public static class ErrorDialogFragment extends DialogFragment {
    private Dialog mDialog;
    public ErrorDialogFragment() {
        super();
        mDialog = null;                                                 // Default constructor. Sets the dialog field to null
    }
       public void setDialog(Dialog dialog) {
        mDialog = dialog;                                        // Set the dialog to display
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return mDialog;                                                              // Return a Dialog to the DialogFragment.
    }
}
private final class MyLocationListener implements LocationListener {
     @Override
     public void onLocationChanged(Location location) {
         // Report to the UI that the location was updated
         mCurrentLocation =location;
         Context context = getApplicationContext();

         msg = Double.toString(location.getLatitude()) + "," +  Double.toString(location.getLongitude());
         list.add(mCurrentLocation);

         Toast.makeText(context, msg,Toast.LENGTH_LONG).show();

      }

        }
@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;
            }

    }

}



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
    mLocationClient = new LocationClient(this, this, this);   /* Create a new location client, using the enclosing class to handle callbacks     */
    mLocationClient.connect();
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);    // Use high accuracy
    mLocationRequest.setInterval(UPDATE_INTERVAL);  // Setting the update interval to  5mins
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);  // Set the fastest update interval to 1 min
    LocationListener locationListener = new MyLocationListener();
    mLocationClient.requestLocationUpdates(mLocationRequest,locationListener);

}

@Override
protected void onDestroy() {
    mLocationClient.disconnect();  
}

/* Called by Location Services when the request to connect the client finishes successfully. At this point, you can request the current location or start periodic updates */
@Override
public void onConnected(Bundle dataBundle) {

}

/* Called by Location Services if the connection to the location client drops because of an error.*/
@Override
public void onDisconnected() {
    Toast.makeText(this, "Disconnected. Please re-connect.",
            Toast.LENGTH_SHORT).show();

}

//Called by Location Services if the at tempt to Location Services fails. 
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.If the error has a resolution, try sending an Intent to start a Google Play services activity that can resolve
     * error. */
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this,CONNECTION_FAILURE_RESOLUTION_REQUEST);


            /*
             * Thrown if Google Play services canceled the original
             * PendingIntent
             */
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();

        }
    } else {
        /*  * If no resolution is available, display a dialog to the user with the error. */
        showErrorDialog(connectionResult.getErrorCode());
    }
}
private boolean showErrorDialog(int errorCode) {
    int resultCode =
            GooglePlayServicesUtil.
                    isGooglePlayServicesAvailable(this);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status

        // Continue
        return true;
    // Google Play services was not available for some reason
    } else {
            Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode,this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
            // If Google Play services can provide an error dialog
            if (errorDialog != null) {
                        // Create a new DialogFragment for the error dialog
                        ErrorDialogFragment errorFragment =  new ErrorDialogFragment();
                        // Set the dialog in the DialogFragment
                        errorFragment.setDialog(errorDialog);
                        // Show the error dialog in the DialogFragment
                        errorFragment.show(getSupportFragmentManager(),"Location Updates");

                        } return false;
            }
        }

}

Pete
  • 57,112
  • 28
  • 117
  • 166
gamma
  • 81
  • 1
  • 2
  • 10
  • check out [this link](http://stackoverflow.com/a/16393534/2345913) – CRUSADER May 24 '13 at 09:31
  • thanks for the reply crusader..but i would like to use location client as it gives me the best location using all the available providers.. – gamma May 24 '13 at 11:07
  • I'm sorry guyz..the above code does work perfectly.. i was making a mistake in my xml files...hope the code in my question helps someone in need.. – gamma May 27 '13 at 05:04
  • what code in you xml was the issue? I'm just curious. Thanks – lilott8 May 01 '14 at 00:17

2 Answers2

7

LocationClient.connect() is asynchronous. You can't immediately start using the client methods until connection is complete. You should call requestLocationUpdates inside the onConnected callback (or at least after the callback has been called).

David
  • 749
  • 5
  • 2
  • take care: LocationClient is deprecated. You should use LocationManager or new/latest Location Service API. Look this answer for more info: [link](http://stackoverflow.com/questions/24266362/android-google-maps-api-location/27195920#27195920) – MiguelHincapieC Nov 28 '14 at 21:35
0

You should request for location updates in onConnected() callback. You can see my code here for your reference. Hope it will be helpful.

Community
  • 1
  • 1
Vinayak
  • 523
  • 1
  • 9
  • 20