机器人等待的AsyncTask完成 [英] android wait asynctask to finish
问题描述
我有一个函数, AppHelper.isOnline(上下文的背景下)
,我在我的应用程序的各个部分调用检查会话没有超时作出HTTP前请求。
I have a function, AppHelper.isOnline(Context context)
, I call in various parts of my application to check that a session didn't timeout before making an HTTP request.
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.buttonPagamenti:
if (AppHelper.isOnline(this))
{
//here AppHelper.isOnline should have finished it's async task
intent = new Intent(this, OrdineCreaActivity.class);
this.startActivityForResult(intent, R.id.buttonPagamenti);
}
break;
...
在 AppHelper.isOnline()
,我执行异步任务登录,从而使网络请求,不能在用户界面,否则运行我得到一个异常。我需要等待它完成,然后用,如果里面的code恢复。我怎样才能做到这一点?
Inside AppHelper.isOnline()
, I am executing an async task that logs in, thus making a network request, which can't be run on UI because otherwise I get an exception. I need to wait for it to finish BEFORE resuming with the code inside the if. How can I do this ?
问题是活动开始首创,然后异步执行,所以当活动需要一个有效的记录的会话,它打破了。
Problem is the activity starts firsts, then the async executes, so when the activity expects a valid logged in session, it breaks.
推荐答案
您有两种选择:
既可以使用的AsyncTask
的方法获取(长期超时的TimeUnit单位)
这样的:
Either use the AsyncTask
's method get(long timeout, TimeUnit unit)
like that:
task.get(1000, TimeUnit.MILLISECONDS);
这会使你的主线程等待的的AsyncTask
至多1000毫秒(根据@ user1028741评论结果:居然还有infinetly等方法 - <一个href="http://developer.android.com/reference/android/os/AsyncTask.html#get%28%29"><$c$c>AsyncTask#get()$c$c>这可能也是做在某些情况下,你的工作)。
This will make your main thread wait for the result of the AsyncTask
at most 1000 milliseconds (as per @user1028741 comment: actually there is also infinetly waiting method - AsyncTask#get()
which might also do the work for you in some cases).
另外,您可以显示进度的异步任务对话框,直到它完成。看到这个线程(不用我复制过去code)。主要是显示一个进度对话框,而异步任务运行和隐藏,当它完成。
Alternatively you can show a progress dialog in the async task until it finishes. See this thread (No need for me to copy past the code). Basically a progress dialog is shown while the async task runs and is hidden when it finishes.
您甚至有第三个选择:如果发
是足以满足你的需要,你可以只使用它的加入
方法但是,如果任务花费很长一段时间,你仍然需要显示进度对话框,否则你会得到,因为主线程处于非活动状态的时间太长的一个例外。
You have even third option:" if Thread
is sufficient for your needs you can just use its join
method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.
这篇关于机器人等待的AsyncTask完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!