从 Android 中的 AsyncTask 返回一个值 [英] Return a value from AsyncTask in Android

查看:38
本文介绍了从 Android 中的 AsyncTask 返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题:是否可以在 AsyncTask 中返回一个值?

One simple question: is it possible to return a value in AsyncTask?

//AsyncTask is a member class
private class MyTask extends AsyncTask<Void, Void, Void>{

    protected Void doInBackground(Void... params) {
         //do stuff
         return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        //do stuff
        //how to return a value to the calling method?
    }
}

然后在我的 Activity/Fragment 中:

// The task is started from activity
myTask.execute()
// something like this?
myvalue = myTask.getvalue() 

这个是很久以前不熟悉Java的地方问的,现在熟练了,做个简单的总结:

异步任务的重点在于任务是异步,意思是在你对任务调用execute()之后,任务开始运行在它的线程上.自己的.从 asynctask 返回一个值将毫无意义,因为原始调用线程已经在做其他事情(因此任务是异步的).

The point of async task is that the task is asynchronous, meaning that after you call execute() on the task, the task starts running on a thread of its own. returning a value from asynctask would be pointless because the original calling thread has already carried on doing other stuff (thus the task is asynchronous).

想想时间:在某个时间点,您启动了一个与主线程并行运行的任务.当并行运行的任务完成时,主线程上的时间也过去了.并行任务不能及时返回给主线程返回一个值.

Think of time: At one point of time, you started a task that will run in parallel with the main thread. When the parallel-running task completed, time has also elapsed on the main thread. The parallel task cannot go back in time to return a value to the main thread.

我来自 C,所以我对此了解不多.但似乎很多人都有同样的问题,所以我想我会澄清一下.

I was coming from C so I didn't know much about this. But it seems that lots of people are having the same question so I thought I would clear it up a bit.

推荐答案

为什么不调用一个处理值的方法?

Why not call a method that handles the value?

public class MyClass extends Activity {

    private class myTask extends AsyncTask<Void, Void, Void> {

        //initiate vars
        public myTask() {
            super();
            //my params here
        }

        protected Void doInBackground(Void... params) {
            //do stuff
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //do stuff
            myMethod(myValue);
        }
    }

    private myHandledValueType myMethod(Value myValue) {
        //handle value 
        return myHandledValueType;
    }
}

这篇关于从 Android 中的 AsyncTask 返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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