Android的停止的AsyncTask [英] Android stop asynctask
问题描述
我已经创建了一个AsyncTask的显示进度对话框,同时ghetting用户的位置。我想运行此AsyncTask的30秒,如果在这些30秒我还没有找到用户的位置,我想只杀任务,并显示错误信息。
I have created an asynctask to show progress dialog while ghetting the users location. I want to run this asynctask for 30 seconds and if in these 30 seconds I haven't found the users location I would like just to kill the task and show an error message.
我的code到目前为止是这样的:
My code so far is like this:
userLocation = new AsyncTask<Void, Void, Void>() {
private ProgressDialog locationDialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
locationDialog.setMessage(getResources().getString(R.string.getting_location));
locationDialog.setCancelable(false);
locationDialog.setIndeterminate(true);
locationDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
latitude = locationProvider.getLatitude();
longitude = locationProvider.getLongitude();
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// getLocation.cancel(true);
if (latitude != 0 && longitude != 0) {
locationDialog.dismiss();
getData();
} else {
locationDialog.dismiss();
alertDialog.show();
Log.d("Couldn't get location", "Couldn't get location");
}
}
};
userLocation.execute((Void[])null);
我应该如何修改我的code,这样,如果30秒后的经度和纬度为0,只杀AsyncTask的,并显示一些错误信息。任何想法?
How should I edit my code so that if the latitude and longitude after 30 seconds is 0, just kill the asynctask and show some kind of error message. Any ideas?
推荐答案
您应该使该取消AsyncTask的处理程序(<一个href=\"http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)\">http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean))
You should make a handler which cancels the Asynctask (http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean))
发送延迟的消息,该Handler这样的:
Send a delayed message to this Handler like:
Handler.sendMessageDelayed(msg, delayMillis)
private android.os.Handler mHandler = new android.os.Handler() {
@Override
public void handleMessage(Message msg) {
(Your AsyncTask object).cancel(true);
}
}
这篇关于Android的停止的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!