Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

android - AsyncTask return value

My android app connects to my website to retrieve and upload information so I use an AsyncTask thread.

In one instance, I need my thread to return a true or a false value to my main thread.

Is there a way to get this return value from an AsyncTask execute function?

When I do the following:

Toast.makeText(Locate.this, "Testing : "+locationUpdate.execute(location), Toast.LENGTH_LONG).show();

I just get alot of gibberish.

I think what I need is a means to pause the main thread until the second thread completes. The second thread calls a function in the main thread to set my return value. So when the second thread completes, the main thread can unpause and access the return value as set by the second thread If this logic is sound, please offer suggestions ... thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use AsyncTask get() method for this. It waits if necessary for the computation to complete, and then retrieves its result:

Toast.makeText(Locate.this, "Testing : " + locationUpdate.execute(location).get(), Toast.LENGTH_LONG).show();

But be sure to not block the main thread for a long period of time, as this will lead to unresponsive UI and ANR.

UPDATE
I missed the point that question was about async web download/upload. Web/network operation should considered as a long one and thus the approach "pause UI thread and wait till download finishes" is always a wrong one. Use usual result publishing approach intstead (e.g.: AsyncTask.onPostExecute, Service + sendBroadcast, libraries like Volley, RoboSpice, DataDroid etc).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...