Search code examples
javaandroidbackground-task

Android Background Task - how to access return value


When a background task returns a value how can it be accesses from another class. Just using this as example code, but what I want is the background task to do something and return a value.

protected String doInBackground(String... params) {
    publishProgress("Sleeping..."); // Calls onProgressUpdate()
    try {
       // Do your long operations here and return the result
       int time = Integer.parseInt(params[0]);    

       // Sleeping for given time period
       Thread.sleep(time);
       resp = "Slept for " + time + " milliseconds";
   } catch (InterruptedException e) {
       e.printStackTrace();
       resp = e.getMessage();
   } catch (Exception e) {
       e.printStackTrace();
       resp = e.getMessage();
   }

   **return resp;**
}

Solution

  • For this you need to extend asynktask class like

    extends AsyncTask<String, String, String>
    
    @Override
    protected void onPostExecute(String result) {
        //heare result is value you return from doInBackground() method 
        //this is work on UI thread
    } 
    

    Classs look like

    public class AsyncTaskGetResult extends AsyncTask<String, String, String> {
    
        PrintListner mPrintListner ;      
        private AsyncTaskGetResult (PrintListner mPrintListner) {
            this.mPrintListner = mPrintListner;
    
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    
        }
        @Override
        protected String doInBackground(String... params) {
            return result;
        }
    
        @Override
        protected void onPostExecute(String result) {
        //heare result is value you return from doInBackground() method 
        //this is work on UI thread
        this.mPrintListner.getResult(result);
       }
    

    }

    public interface PrintListner {
        public void getResult(String receiptItem);
    }
    

    If you need to access it in another class you can write listner for that and implement in you activity

    public class MyActivity extends Activity implements PrintListner{
    
           @Override
           public void getResult(String receiptItem){
            //Do whatever you want
           }
        }   
    

    and call it like new AsyncTaskGetResult(this).execute(yourString);