如何在下载文件时在android中增加进度计数百分比

时间:2018-12-24 06:35:34

标签: android

在这里,我发布了我的AssyncTask方法调用DownloadFile

 @Override
    protected Boolean doInBackground(String... strings) {

            
             String tMainFolder = String.valueOf(BaseApplication.getInstance().getAppContext().getDir("FileDownload", Context.MODE_PRIVATE));
             tMainFolder += "/File" + mBookDetails.getBookId(); //Book download
             Log.i(TAG, "Assynctask Ma" + tMainFolder);
             Log.i(TAG, "book id and book name" + mBookDetails.getBookId() + mBookDetails.getBookName());
             downloadBookDetails(tMainFolder, ContentfulConstants.BOOK_MAIN_IMAGE + ".png", mBookDetails.getBookMainImage());
             downloadBookDetails(tMainFolder, ContentfulConstants.BOOK_MAIN_AUDIO + ".mp3", mBookDetails.getBookSound());

             for (PageDetailProperties pageDetails : mBookDetails.getPageDetail()) {

                 String tPageNumber = pageDetails.getPageNumber().toString();
                 downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_IMAGE + tPageNumber + ".png", pageDetails.getPageImage());
                 downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_AUDIO + tPageNumber + ".mp3", pageDetails.getPageAudio());
                 downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_TEXT + tPageNumber + ".txt", pageDetails.getPageText());

             }


        return true;

    }

  1. 下载文件时我无法创建进度计数
  2. 作为我的波纹管代码,我在Assyntask doInbackround中调用的该方法中创建了一个名为“ DownloadFile”的方法,因此当我尝试创建Dialog的显示错误时
  3. 那么我该如何实现

private void downloadFile(String pMaolder, String pFileName, String pDowURL) {
        Log.i(TAG, "Coming to this downloadBookDetails ");
        try {
            URL url = new URL(pDowURL);
            Log.i(TAG, "pDownload URL"+  url);
            URLConnection ucon = url.openConnection();
            ucon.setReadTimeout(5000);
            ucon.setConnectTimeout(10000);

            int lenghtOfFile = ucon.getContentLength();
            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

            File directory = new File(pMainFolder, pFileName);
            Log.i(TAG, "File Name dir" + directory);
            FileOutputStream outStream = new FileOutputStream(directory);
            byte[] buff = new byte[5 * 1024];

            int len;
            long total = 0;
            while ((len = inStream.read(buff)) != -1) {
                total += len;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total * 100)/lenghtOfFile));  //Got Error here Cannot resole publishProgress

                outStream.write(buff, 0, len);

            }
            outStream.flush();
            outStream.close();
            inStream.close();
        } catch (Exception e) {
            //Add Network Error.
            Log.i(TAG, "Download Error Exception " + e.getMessage());

            e.printStackTrace();
        }
    }

2 个答案:

答案 0 :(得分:2)

这对我有用

final DownloadManager dm;
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(listModel.videourl));
                   
                    request.setDestinationInExternalPublicDir("downloads/Video",listModel.name).setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED).setVisibleInDownloadsUi(true);
                    final long downloadId = dm.enqueue(request);

                    Thread t = new Thread(new Runnable() {

                        @Override
                        public void run() {

                            boolean downloading = true;


                            while (downloading) {

                                DownloadManager.Query q = new DownloadManager.Query();
                                q.setFilterById(downloadId);

                                Cursor cursor = dm.query(q);
                                cursor.moveToFirst();
                                int bytes_downloaded = cursor.getInt(cursor
                                        .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                                int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                                if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                                    downloading = false;
                                }

                                final int dl_progress = (int) ((double)bytes_downloaded / (double)bytes_total * 100f);
  
      //dl_progress is your percentage value
                               

                               final boolean finalDownloading = downloading;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        
                                        if(!finalDownloading)
                                        {
                                            Toast.makeText(PlayActivity.this, "Downloading complete", Toast.LENGTH_LONG).show();
                                        }

                                    }

                                });
     
                                cursor.close();

                            }


                        }


                    });
                    t.start();

答案 1 :(得分:0)

在调用AsyncTask之前,请先编写:

progressDialog = new ProgressDialog(activity);
        progressDialog.setMessage(activity.getResources().getString(R.string.file_downloading));
        progressDialog.setIndeterminate(true);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setProgressNumberFormat(null);
        progressDialog.setCancelable(false);  

以及您的Asynctask

@Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        progressDialog.setIndeterminate(false);
        progressDialog.setProgress(progress[0]);

    }

    @Override
    protected void onPostExecute(String result) {
        progressDialog.dismiss();
       }