如何在 AsyncTask 中调用返回值函数 [英] How to call a returning value function in AsyncTask

查看:16
本文介绍了如何在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆