How can you pass multiple primitive parameters to AsyncTask?

后端 未结 6 674
情歌与酒
情歌与酒 2020-11-27 10:36

There are related questions, such as How can I pass in 2 parameters to a AsyncTask class? , but I ran into the difficulty of trying in vain to pass multiple primitives as pa

6条回答
  •  执笔经年
    2020-11-27 10:46

    This is solved via subclassing. Google has an example for solving this problem (subclassing) in the official Android AsyncTask Documentation:

    http://developer.android.com/reference/android/os/AsyncTask.html

    Example:

    private class DownloadFilesTask extends AsyncTask {
        protected Long doInBackground(URL... urls) {
            int count = urls.length;
            long totalSize = 0;
            for (int i = 0; i < count; i++) {
                totalSize += Downloader.downloadFile(urls[i]);
                publishProgress((int) ((i / (float) count) * 100));
                     // Escape early if cancel() is called
                if (isCancelled()) break;
            }
            return totalSize;
        }
    
        protected void onProgressUpdate(Integer... progress) {
            setProgressPercent(progress[0]);
        }
    
        protected void onPostExecute(Long result) {
            showDialog("Downloaded " + result + " bytes");
        }
    }
    

提交回复
热议问题