我对编程非常陌生,我对此有些怀疑。
我有一个AsyncTask,我称之为RunInBackGround。
我开始像这样的过程:
new RunInBackGround().execute();
但是我希望等到此调用完成执行之后,再继续执行其他代码语句。
我怎样才能做到这一点?
有什么办法吗?
我对编程非常陌生,我对此有些怀疑。
我有一个AsyncTask,我称之为RunInBackGround。
我开始像这样的过程:
new RunInBackGround().execute();
但是我希望等到此调用完成执行之后,再继续执行其他代码语句。
我怎样才能做到这一点?
有什么办法吗?
Answers:
等到此调用完成执行
您将需要调用AsyncTask.get()方法以返回结果,并等待直到doInBackground执行完成。但这会冻结Main UI线程,如果您不调用Thread内部的get方法。
要在UI Thread中返回结果,请启动AsyncTask为:
String str_result= new RunInBackGround().execute().get();
AsyncTask无get方法和的AsyncTaskonPostExecute方法称为U导致对主UI线程,其提供
awaitin c#,并且当然不会锁定主线程
尽管最佳的方式是代码可以并行运行,但这可能是您只使用线程的情况,因此即使应用程序的使用流程必须等待它也不会阻塞UI线程。
您这里有2种选择;
您可以在AsyncTask本身中执行要等待的代码。如果它与更新UI(thread)有关,则可以使用onPostExecute方法。完成后台工作后,系统会自动调用此方法。
如果由于某种原因您被迫在“活动” /“片段” /“无论如何”中执行此操作,则还可以使自己成为自定义侦听器,并通过AsyncTask进行广播。通过使用此方法,您可以在Activity / Fragment / Whatever中有一个仅在需要时才被调用的回调方法:aka当您的AsyncTask完成后,您需要等待的所有内容。
AsyncTask有四种方法。
onPreExecute -- for doing something before calling background task in Async
doInBackground -- operation/Task to do in Background
onProgressUpdate -- it is for progress Update
onPostExecute -- this method calls after asyncTask return from doInBackground.
onPostExecute()从回来后,您可以呼叫您的工作doInBackground()
onPostExecute是您需要实现的。
我认为最简单的方法是创建一个接口以从onpostexecute获取数据并从interface运行Ui:
创建一个接口:
public interface AsyncResponse {
void processFinish(String output);
}
然后在asynctask中
@Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
然后在您的主要活动中
@Override
public void processFinish(String data) {
// do things
}