从异步任务的android返回值 [英] return value from Async task in android

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

问题描述

一个简单的问题:

是有可能在异步任务返回变量?

is it possible to return a variable in Async task?

//my async task is in outer class

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

    public myTask() {
        super();
    }

    protected Void doInBackground(Void... params) {

         //do stuff
         return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        //do stuff
        //how to return a variable here?
    }
}

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

编辑: 这是问了很久以前我在那里不熟悉Java,现在我与它更好的,我就做一个简单的总结:

This was asked a long time ago where I wasn't familiar with Java, now that I'm better with it, I 'll do a quick summary:

异步任务的一点是,任务是同步,这意味着您拨打后执行()上的任务,任务开始于它自己的线程中运行。从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 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返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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