【问题标题】:How to Show download progress in progress bar in Android?如何在 Android 的进度条中显示下载进度?
【发布时间】:2013-03-21 08:33:42
【问题描述】:

我正在使用 .net 网络服务,我可以下载 sd 卡中的文件,但我想在特定文件开始下载并完成时显示进度条,然后我想显示查看和取消等选项。

点击事件类:

public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
    LazyAdapter ca = (LazyAdapter)parent.getAdapter();
    FolderList item_name = (FolderList)ca.getItem(position);
    FolderList DocumentID = (FolderList)ca.getItem(position);
    FolderList type = (FolderList)ca.getItem(position);

    Intent mIntent = new Intent();  
    mIntent.putExtra("item_name", item_name.folder_name);
    mIntent.putExtra("item_id", DocumentID.ID);
    mIntent.putExtra("item_type", type.type);

    mIntent.getStringExtra("item_name");

    String Type = mIntent.getStringExtra("item_type");

    Log.i("Type", Type);

    if {
       // Some code here...
    } else {
        Intent i = new Intent(getApplicationContext(), Display_image.class);
        i.putExtra("item_name", item_name.folder_name);
        i.putExtra("ID", DocumentID.ID);
        i.putExtra("item_type", type.type);
        i.putExtra("User_ID",User_ID);

        i.getStringExtra("item_name");
        Id = i.getStringExtra("ID");
        i.getStringExtra("item_type");
        startActivity(i);
    }
}

我的代码:我想使用下载管理器

    SoapPrimitive DocumentResponse = (SoapPrimitive)Envelope.getResponse();
        Log.i("DocumentResponse", DocumentResponse.toString());

        String DocAsString = DocumentResponse.toString();

        byte[] decodedString = Base64.decode(DocAsString, Base64.DEFAULT);

         File direct = new File(Environment.getExternalStorageDirectory() + "/MyFolder");

         if(!direct.exists())
         {
           direct.mkdir();
         }
        File photo = new File(Environment.getExternalStorageDirectory() + "/MyFolder", Name);

         if (photo.exists())
         {
           photo.delete();
         }
     try {

         DownloadManager.Request request = new DownloadManager.Request(Uri.parse(Name));
         request.setDescription("Have Fun ;)");
         request.setTitle("Downloading...");
         // in order for this if to run, you must use the android 3.2 to compile your app
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
             request.allowScanningByMediaScanner();
             request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
         }

       FileOutputStream fos=new FileOutputStream(photo.getPath());
       fos.write(decodedString);
       fos.close();

       DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
       manager.enqueue(request);

       ContentValues values= new ContentValues();

       System.out.println(values);

     }
     catch (java.io.IOException e) 
     {
       Log.e("PictureDemo", "Exception in photoCallback", e);
     }
    } 

请建议如何使用下载管理器进去???谢谢

【问题讨论】:

    标签: android android-progressbar download-manager


    【解决方案1】:

    您可以使用 ProgressBar 来完成此操作。

    首先,在您的界面中添加一个进度条,如下所示:

    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Small"/>
    

    然后在您的代码中更新您的方法,如下所示:

    protected ProgressBar mProgressBar;
    protected long downloadId;
    protected DownloadManager manager;
    
    public void startdownload() {
        //<SET UP DOWNLOAD MANAGER HERE>
        downloadId = manager.enqueue(request);
        mProgressBar = findViewById(R.id.progress_bar);
        Timer myTimer = new Timer();
        myTimer.schedule(new TimerTask() {          
            @Override
                public void run() {
                DownloadManager.Query q = new DownloadManager.Query();
                q.setFilterById(downloadId);
                Cursor cursor = manager.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));
                cursor.close();
                int dl_progress = (bytesDownloaded * 1f / bytesTotal) * 100;
                runOnUiThread(new Runnable(){
                    @Override
                    public void run(){
                        mProgressbar.setProgress((int) dl_progress);
                    }
                });    
            }
        }, 0, 10);
    }
    

    【讨论】:

    • 不,它不工作..无法理解..请详细说明..谢谢
    • dl_progress 它始终为 0,最后为 100,尽管 bytes_downloadedbytes_total 具有离散值...
    • 我必须在int dl_progress = (bytes_downloaded * 100 / bytes_total); 中更改double dl_progress = (bytes_downloaded / bytes_total) * 100; 以及在COLUMN_TOTAL_SIZE_BYTES 中的COLUMN_TOTAL_BYTES。现在可以了。
    • Dentex 是对的,计算返回 0 直到我改成他的
    • 我用long for,我的大文件下载:long bytes_downloaded = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); long bytes_total = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
    【解决方案2】:

    使用跟随方法

    私有 NotificationManager mNotifyManager;

    case R.id.btnSubmit:
    mNotifyManager = (NotificationManager)            context.getSystemService(Context.NOTIFICATION_SERVICE);
                mBuilder = new NotificationCompat.Builder(context);
                mBuilder.setContentTitle("BuyMixTapes")
                        .setContentText("Download in progress")
                        .setSmallIcon(R.drawable.appiconmain);
    
    new DownloadFile().execute(vv);
    public class DownloadFile extends AsyncTask<String, String, String> {
    
        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //context.showDialog(progress_bar_type);
    
            mBuilder.setProgress(100, 0, false);
            mNotifyManager.notify(id, mBuilder.build());
        }
    
    
        protected String doInBackground(String... f_url) {
            int count;
            try {
                for (int i = 0; i < f_url.length; i++) {
                    Log.e("0url",""+f_url[0]);
                    Log.e("1url",""+f_url[1]);
                   // Log.e("1url",""+f_url[1]);
                    URL url = new URL(f_url[i]);
                    URLConnection conection = url.openConnection();
                    conection.connect();
                    // getting file length
                    int lenghtOfFile = conection.getContentLength();
    
                    // input stream to read file - with 8k buffer
                    InputStream input = new         BufferedInputStream(url.openStream(), 8192);
    
                    // Output stream to write file
                    //   OutputStream output = new FileOutputStream("/sdcard/"+f_url[i]);
                    OutputStream output = new FileOutputStream(
                            "/sdcard/" +i + "buymix.mp3");
                    byte data[] = new byte[1024];
    
                    long total = 0;
    
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        // After this onProgressUpdate will be called
                        publishProgress("" + (int) ((total * 100) / lenghtOfFile));
    
                        // writing data to file
                        output.write(data, 0, count);
                    }
    
    
                    // flushing output
                    output.flush();
    
                    // closing streams
                    output.close();
                    input.close();
                }
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
    
            return null;
        }
    
        /**
         * Updating progress bar
         */
    
        /**
         * After completing background task
         * Dismiss the progress dialog
         **/
        @Override
        protected void onProgressUpdate(String... values) {
            // Update progress
            mBuilder.setProgress(100, Integer.parseInt(values[0]), false);
            mNotifyManager.notify(id, mBuilder.build());
            super.onProgressUpdate(values);
        }
    
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            mBuilder.setContentText("Download complete");
            // Removes the progress bar
            String imagePath = Environment.getExternalStorageDirectory()
                    .toString() + "/downloaded.mp3";
            mBuilder.setProgress(0, 0, false);
            mNotifyManager.notify(id, mBuilder.build());
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      2021 年更新:

      在布局中添加 ProgressBar(TextView 只是为了显示更多信息):

              <ProgressBar
                 android:id="@+id/progressBar"
                 style="?android:attr/progressBarStyleHorizontal"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content" />
      
              <TextView
                 android:id="@+id/textView1"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_below="@id/progressBar"
                 android:text="Hello World!" />
      

      然后在onCreate之前:

                 DownloadManager downloadManager;
                 long downloadReference;
                 TextView text1;
                 ProgressBar progressBar;
                 Timer progressTimer;
      

      之后,在 onCreate:

                  text1 = (TextView) findViewById(R.id.textView1);
                  progressBar = (ProgressBar) findViewById(R.id.progressBar);
      

      然后设置下载管理器后:

                  // <Some codes which setup download manager>
                  downloadReference = downloadManager.enqueue(request); // enqueue a new download
      
                  // update progressbar
                  progressTimer = new Timer();
                  progressTimer.schedule(new TimerTask() {
                      @Override
                      public void run() {
                          DownloadManager.Query downloadQuery = new DownloadManager.Query();
                          downloadQuery.setFilterById(downloadReference);
      
                          Cursor cursor = downloadManager.query(downloadQuery);
                          if (cursor.moveToFirst()) { // this "if" is crucial to prevent a kind of error
                              final int downloadedBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                              final int totalBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); // integer is enough for files under 2GB
                              cursor.close();
      
                              final float downloadProgress = downloadedBytes * 100f / totalBytes;
                              if(downloadProgress > 99.9) // stop repeating timer (it's also useful for error prevention)
                                  progressTimer.cancel();
      
                              runOnUiThread(new Runnable() {
                                  @Override
                                  public void run() {
                                      text1.setText(downloadedBytes + "\n" + totalBytes + "\n" + downloadProgress + "%");
                                      progressBar.setProgress((int) downloadProgress);
                                  }
                              });
                          }
                      }
                  }, 0, 1000);
      

      一些提示:

      • 如果您的文件大于 2GB,则应使用其他类型而不是 int,例如 double 等。
      • 您可以在其他地方停止计时器,例如在 BroadcastReceiver 中(如果有)。
      • 任务执行是每 1000 毫秒(每 1 秒),这显然是可变的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-26
        • 1970-01-01
        • 1970-01-01
        • 2019-05-26
        • 1970-01-01
        • 2017-04-19
        相关资源
        最近更新 更多