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

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

问题描述

一个简单的问题:是否有可能返回的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?
    }
}

然后我的活动中的 / 片段

// 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;
    }
}

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

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