我是编程和Android开发的新手。我在MainActivity中有3种异步方法从服务器获取数据,可以说它叫做
getUserDataFromServer()
getProductsDataFromServer()
getBannersFromServer()
如果每个请求都花1秒钟,那么完成这3个请求需要3秒钟。如果我一个接一个地串联(串联)。
所以我想要的是...。我想异步地(并行)发出这3个请求,然后如果这3个请求已经完成(失败或成功),那么我想做其他事情,可以说表明吐司消息。所以我可以更快地完成它,也许只需要1,2 s,而不是3 s。
我不知道该怎么做,或者不知道在Android中将其包装的特殊方法是什么?
如何用Java或Kotlin做到这一点?
答案 0 :(得分:1)
以下代码应帮助您开始使用。它还说明了正在发生的事情。您可以根据需要更改参数:
执行任务:
MyTask myTask = new MyTask();
myTask.execute(String1);
//OR:
new MyTask().execute(String1, String2, String3...);
创建任务:
//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.
}
}