如何在 AsyncTask 中调用返回值函数 [英] How to call a returning value function in AsyncTask
问题描述
我是 andorid 编程的新手我刚刚遇到了在 AsyncTask 的 doInBackground()
中调用返回值函数的问题简单的问题是如何在不冻结 UI 的情况下等待 AsyncTask 完成然后执行 return 语句,我也研究了 onPostExecute()
但它没有解决问题.以下是示例代码
I am new to andorid programming I've just stucked into a problem to call returning value function inside AsyncTask's doInBackground()
Simple question is How to wait for AsyncTask to complete and then execute return statement without freezing UI, i've also studied onPostExecute()
but it doesn't solve problem.
following is sample code
public String hello() {
String result = null;
//calling asynctaske execute method
retrun result;
}
推荐答案
就我自己而言,我使用回调函数来完成此操作,我在 onPostExecute 之后调用该函数.
For myself i do this with a callback Function, that i invoke after onPostExecute.
public AsyncUnzip(Activity ctx, Observer callback) {
this.ctx = ctx;
this.callback = callback;
}
和
@Override
protected void onPreExecute() {
super.onPreExecute();
dia = new ProgressDialog(ctx);
dia.setTitle("Bitte warten");
dia.setMessage("Geodatenpaket wird entpackt...");
dia.setCancelable(false);
dia.show();
}
和
@Override
public void onPostExecute( Boolean result ) {
super.onPostExecute(result);
dia.dismiss();
callback.update(null, returnFolder);
System.out.println("Unzipped to: " + returnFolder.getName() );
}
<小时>
在这种情况下,您对 Async Task 的调用将如下所示:
In that case your call of Async Task would look like that:
AsyncUnzip unzipThread = new AsyncUnzip(ImportActivity.this, new Observer() {
@Override
public void update( Observable observable, Object data ) {//your code invoked after Async Task
} });
unzipThread.execute(selectedFile); //Start Unzip in external Thread.
<小时>
注意:这是一个快速而枯燥的解决方案,使用匿名 Observer 实现并且没有 observable.
Note: This is a quick and diry solution with a annonymous Observer implementation and without an observable.
这篇关于如何在 AsyncTask 中调用返回值函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!