问题描述
我如何使用 locationclient
类和 requestLocationUpdates(LocationRequest, LocationListener)
在 android 中获取位置更新?我已经尝试了以下代码,但它不起作用.谁能帮我这个?哪里错了,先谢谢了.
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;
}
}
}
推荐答案
LocationClient.connect() 是异步的.在连接完成之前,您不能立即开始使用客户端方法.您应该在 onConnected 回调中调用 requestLocationUpdates(或至少在回调被调用之后).
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).
这篇关于使用 LocationClient 获取位置更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!