Using LocationClient to get Location updates

一曲冷凌霜 提交于 2019-12-02 12:17:45

问题


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

}


回答1:


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).




回答2:


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



来源:https://stackoverflow.com/questions/16731717/using-locationclient-to-get-location-updates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!