How run two AsyncTasks in one Activity?

前端 未结 4 452
名媛妹妹
名媛妹妹 2020-12-31 20:04

I have two Activitys (mainActivity & downloadActivity) and I have 2 AsyncTasks in downloadActivity

相关标签:
4条回答
  • 2020-12-31 20:45

    Make one class task like:

    Declare progress bar globally in main thread.

    Now what you have to do is start one async task in main thread like:

    public class myactivity extends Activity {
        private ProgressDialog _dialog;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.base_screen);
            new abc().execute();
        }
    
        class abc extends AsyncTask(String,String,String) {
            @Override
            protected void onPreExecute() {
                _dialog = new ProgressDialog(_ctx);
                _dialog.setCancelable(false);
                _dialog.setMessage("Loading");
                _dialog.show();
                super.onPreExecute();
            }
    
            @Override
            protected String doInBackground(String... params) {
                @Override
                protected void onPostExecute(String result) {
                    // in post execute of this class you can run a new thread of your downaloder thread. and in post execute of last thread you have to dismiss the progess bar.
                    new download activity.execute();
                    }
                } 
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-31 20:48

    you can make it in one asynk class that have two methodes first fetch json file wait response in doInBackground ... if it is ok call download file methode. Those methodes will return an httpResponse object

    0 讨论(0)
  • 2020-12-31 20:50

    You can override onBackPressed function in activity and finish the current activity before go to previous activity. When again you come to downloadActivity it call it's oncreate method and call first AsynctTask.

    0 讨论(0)
  • 2020-12-31 21:00

    If you want to run multiple AsyncTasks in parallel, you can call executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) instead of execute() on your task. By default, AsyncTasks run in serial, first come first serve.

    Be careful that the two threads do not interact on the same data, this can cause some strange and hard to trace errors.

    0 讨论(0)
提交回复
热议问题