使用LocationClient获取位置更新

时间:2013-05-24 09:28:21

标签: android gps

如何使用locationclient类和requestLocationUpdates(LocationRequest, LocationListener)来获取android中的位置更新?我已经尝试了以下代码,但它无法正常工作。谁能帮我这个?哪里是错误,提前谢谢。

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

}

2 个答案:

答案 0 :(得分:7)

LocationClient.connect()是异步的。在连接完成之前,您无法立即开始使用客户端方法。你应该在onConnected回调中调用requestLocationUpdates(或至少在调用回调之后)。

答案 1 :(得分:0)

您应该在onConnected()回调中请求位置更新。您可以看到我的代码here供您参考。希望它会有所帮助。