I am new in programming and in Android development. I have 3 asynchronous method to get data from server in my MainActivity, let say it is called
getUserDataFromServer()
getProductsDataFromServer()
getBannersFromServer()
if every request takes 1 second, then it needs 3 seconds to complete those 3 request If I chain it one after the other (in series).
so what I want is.... I want to make those 3 request asynchronously (in parallel) then if those 3 request has been done (either failed or success) then I want to do something else, let say to show up the Toast message. so I can finish it faster, maybe it just need around 1,2 s, not 3 s.
I don't know how to do it or what the special method called to wrap it in Android ?
how to do that in Java or Kotlin ?
The following code should help you get started for your purposes. It also has explanations of what is happening. You can change the parameters as required:
Executing the Task:
MyTask myTask = new MyTask();
myTask.execute(String1);
//OR:
new MyTask().execute(String1, String2, String3...);
Creating the Task:
//The first type in AsyncTask<> is for specifying the type of input given.
//Second parameter: Type of data to give to onProgressUpdate.
//Third parameter: Type of data to give to onPostExecute.
private class MyTask extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
@Override
protected String doInBackground(String... params) {
publishProgress("Processing ..."); // Calls onProgressUpdate()
//params is the input you've given that can be used for processing.
getUserDataFromServer()
getProductsDataFromServer()
getBannersFromServer()
//Result is the String to give onPostExecute when the task is done executing.
String result = "Done Processing";
return result;
}
@Override
protected void onPostExecute(String result) {
// Get the result from your task after it is done running.
progressDialog.dismiss();
//IMPORTANT: As you asked in your question, you can now execute whatever code you
//want since the task is done running.
}
@Override
protected void onProgressUpdate(String... text) {
//Progress has been updated. You can update the proggressDialog.
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.