Returning data from AsyncTask without blocking UI

前端 未结 3 1529
逝去的感伤
逝去的感伤 2021-02-05 12:32

I have a conceptual problem related to AsyncTask class. We use AsyncTask so that the main UI is not blocked. But suppose, I want to retrieve some data

3条回答
  •  孤街浪徒
    2021-02-05 12:45

    When an asynchronous task is executed, the task goes through 4 steps:

    1.onPreExecute(), invoked on the UI thread before the task is executed. use this to diaply progress dialog.
    
    2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. Can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
    
    3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). Used to publish progress.
    
    4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
    

    In your activity onCreate()

        TextView tv;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);
        tv= (TextView)findViewById(R.id.textView);
        new TheTask().execute();
    
      }
    class TheTask extends AsyncTask {
    
      protected void onPreExecute() {
      //dispaly progress dialog
     }
    
     protected String doInBackground(Void... params) {
       //do network operation
         return "hello"; 
     }
    
     protected void onPostExecute(String result) {  
      //dismiss dialog. //set hello to textview
          //use the returned value here.
         tv.setText(result.toString());
     }
     }
    

    Consider using robospice (An alternative to AsyncTask. https://github.com/octo-online/robospice.

    Make asynchronous calls, Notifies on the ui thread.

提交回复
热议问题