How to get a string back from AsyncTask?

前端 未结 8 1995
Happy的楠姐
Happy的楠姐 2020-12-03 04:01

I have the following class:

public class getURLData extends AsyncTask{

@Override
protected String doInBackground(String... pa         


        
相关标签:
8条回答
  • 2020-12-03 04:59

    The method execute returns the AynscTask itself, you need to call get:

    output =
        new getURLData()
            .execute("http://www.example.com/call.php?locationSearched=" + locationSearched)
            .get();
    

    This will start a new thread (via execute) while blocking the current thread (via get) until the work from the new thread has been finished and the result has been returned.

    If you do this, you just turned your async task into a sync one.

    However, the problem with using get is that because it blocks, it needs to be called on a worker thread. However, AsyncTask.execute() needs to be called on the main thread. So although this code could work, you may get some undesired results. I also suspect that get() is under-tested by Google, and it is possible that they introduced a bug somewhere along the line.

    Reference: AsyncTask.get

    0 讨论(0)
  • 2020-12-03 05:02

    This ONE LINER worked for me:

    String result = MyasyncTask.execute(type, usrPhoneA, usrPWDA).get();
    
    0 讨论(0)
提交回复
热议问题