android asynctask向ui发送回调 [英] android asynctask sending callbacks to ui

查看:30
本文介绍了android asynctask向ui发送回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下不在活动内的 asynctask 类.在活动中,我正在初始化异步任务,并且我希望异步任务将回调报告回我的活动.是否可以?还是异步任务必须与活动在同一个类文件中?

I have the following asynctask class which is not inside the activity. In the activity I'm initializing the asynctask, and I want the asynctask to report callbacks back to my activity. Is it possible? Or does the asynctask must be in the same class file as the activity?

protected void onProgressUpdate(Integer... values) 
{
    super.onProgressUpdate(values);
    caller.sometextfield.setText("bla");
}

这样的?

推荐答案

你可以创建一个interface,将它传递给AsyncTask(在构造函数中),然后调用方法在 onPostExecute()

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

例如:

你的界面:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

您的活动:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

还有你的 AsyncTask:

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

编辑

由于这个答案很受欢迎,我想补充一些东西.

Since this answer got quite popular, I want to add some things.

如果您是 Android 开发新手,AsyncTask 是一种在不阻塞 UI 线程的情况下快速运行的方法.它确实解决了一些问题,类本身的工作方式没有任何问题.但是,它带来了一些影响,例如:

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • 内存泄漏的可能性.如果您继续引用您的 Activity,即使在用户离开屏幕(或旋转设备)后,它也会保留在内存中.
  • 如果 Activity 已被销毁,则
  • AsyncTask 不会将结果传递给 Activity.您必须添加额外的代码来管理所有这些东西,否则您需要进行两次操作.
  • Activity
  • 中执行所有操作的复杂代码
  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

当您觉得自己成熟到可以继续使用 Android 时,请查看 这篇文章,我认为,这是使用异步操作开发 Android 应用程序的更好方法.

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

这篇关于android asynctask向ui发送回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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