簡體   English   中英

如何僅在某些異步執行完成后才執行代碼?

[英]how to execute code only after some asynchronous has finished executed?

我是編程和Android開發的新手。 我有3種異步方法從MainActivity中的服務器獲取數據,可以說它被稱為

getUserDataFromServer()
getProductsDataFromServer()
getBannersFromServer()

如果每個請求都花1秒鍾,那么完成這3個請求需要3秒鍾。如果我一個接一個地串聯(串聯)。

所以我想要的是...。我想異步(並行)發出這3個請求,然后如果這3個請求已經完成(失敗或成功),那么我想做其他事情,可以說來展示Toast信息。 所以我可以更快地完成它,也許只需要1,2 s,而不是3 s。

我不知道該怎么辦,或者不知道在Android中將其包裝的特殊方法是什么?

用Java或Kotlin怎么做?

以下代碼應幫助您開始使用。 它還說明了正在發生的事情。 您可以根據需要更改參數:

執行任務:

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.       
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM