AsyncTask return value

前端 未结 4 1578
死守一世寂寞
死守一世寂寞 2020-12-05 06:47

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

相关标签:
4条回答
  • 2020-12-05 07:23
    public class RunWebScript {
    String mString;
    public RunWebScript(String url){
        try {   
            URL updateURL = new URL(url);  
            URLConnection conn = updateURL.openConnection(); 
            // now read the items returned...
            InputStream is = conn.getInputStream();  
            BufferedInputStream bis = new BufferedInputStream(is);  
            ByteArrayBuffer baf = new ByteArrayBuffer(50);  
            int current = 0;  
            while((current = bis.read()) != -1){  
                baf.append((byte)current);  
            }   
            String s = new String(baf.toByteArray());
             mString = s;
        } catch (Exception e) {  
            Log.e("ANDRO_ASYNC", "exception in callWebPage",e); 
            mString = "error";
        }
    }
    public String getVal(){
        return mString;
    }   
    

    }

    this is executed as... (showing teh end of a method in teh calling class

            asyncWebCall (url1,CONSTANT);
    }
    private void asyncWebCall(String url,int actionPostExecute){
        new WebCall().execute(url,String.format("%d",actionPostExecute));
    }   
    

    The Async part of the business is ... Note the case statement in onPostExecute this is the key to getting the returned value ito your program again. Note that the call new WebCall().execute(url,String.format("%d",actionPostExecute)); is the last thing done in a thread, no further statements can be executed, control returns through the onPostExecute.

    class WebCall extends AsyncTask<String, String, String>{
        int chooser = -1;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override   
        protected String doInBackground(String... params) {
            try {
                chooser = Integer.parseInt(params[1]);
            } catch(NumberFormatException nfe) {
                Log.d("ANDRO_ASYNC",String.format("asyncReturn() mString numberformatexception = %s",params[1]));
                chooser = 0;
            }
            return(new RunWebScript(params[0])).getVal();           
        }
        protected void onProgressUpdate(String... progress) {       
        }
        @Override
        protected void onPostExecute(String gotFromDoInBkgnd) {
            Log.d("ANDRO_ASYNC",String.format("chooser = %s",chooser));
            switch (chooser){
            case CONSTANT:
                printStringx(gotFromDoInBkgnd);
                asyncWebCall(url2,5); 
                break;
            case 0:
                Log.d("ANDRO_ASYNC",String.format("case 0 = %s",gotFromDoInBkgnd));
                break;
            case 5:
                Log.d("ANDRO_ASYNC",String.format("case 5 = %s",gotFromDoInBkgnd));
                asyncWebCall(url3,7);
    
                break;
    
            default:
                Log.d("ANDRO_ASYNC",String.format("man we got problems = %s",gotFromDoInBkgnd));
                break;
            }
        }
    

    } // end of class

    0 讨论(0)
  • 2020-12-05 07:24

    Handler is the best way to do this in onPostExcecute() method simply do

    @Override
        protected void onPostExecute(Boolean bool) {
            super.onPostExecute(bool);
               Message msg=new Message();
                msg.obj=bool;
                mHandler.sendMessage(msg);
            }
        }
    

    and your message handler will be

    mHandler = new Handler() { 
        @Override 
        public void handleMessage(Message msg) { 
            bool i=(String)msg.obj;
        }
     };
    
    0 讨论(0)
  • 2020-12-05 07:38

    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).

    0 讨论(0)
  • 2020-12-05 07:41

    Here is a complete example of the issue of returning values from an async task. It may occur that there are many tasks to be done one after the other asynchronously.

    Basics. 1. get a return value from a class.

    public class Snippet {
    int computVal;
    public Snippet(){
        computVal = 17*32; 
    }
    public int getVal(){
        return computVal;
    }   
    

    }

    this is called as...

    int hooray = (new Snippet()).getVal();
    
    0 讨论(0)
提交回复
热议问题