因此,如果我理解您想要正确执行的操作,那么我会避免在onClick()
. 相反,onClick()
应该只请求一个位置,显示一个进度对话框,然后返回。由于您想要做的工作是在您收到新位置后发生的,所以我会在那里启动一个 AsyncTask。然后,当 AsyncTask 完成时,您最终会删除对话框(删除它会将控制权返回给用户)。
代码通常会有所帮助,因此,我会将其放入onCreate()
或放在任何地方:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.refresh();
}
});
并将其放入您的 LocationListener 中:
public void refresh() {
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
myDialog = new ProgressDialog(myContext);
myDialog.setIndeterminate(true);
myDialog.show();
}
@Override
public void onLocationChanged(Location location) {
// now do work with your location,
// which your probably want to do in a different thread
new MyAsyncTask().execute(new Location[] { location });
}
然后你需要一个 AsyncTask,它可能看起来像这样:
class MyAsyncTask extends AsyncTask<Location, Void, Void> {
@Override
protected Void doInBackground(Location... location) {
// start doing your distance/directions/etc work here
return null;
}
@Override
protected void onPostExecute(Void v) {
// this gets called automatically when you're done,
// so release the dialog box
myDialog.dismiss();
myDialog = null;
}
}