如何在下载.mp4视频时更新进度条?

时间:2013-02-19 06:54:11

标签: android listview download android-asynctask

我们如何更新ListView中的进度条。当每个进度条与文件下载相关联时,通过AsyncTask完成。

    In the View Inflation process of ListView. (This is also not working)

基本上每当我在浏览器中获得类似.mp4的文件时,我都会将其称为asynctask,因此可能会有n个asynctask实例。但是如何使用特定的Aysnctask任务更新特定的进度条。我的代码在>>>>>

之下
    package com.example.testhopelist;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;

public class TestHopeList extends Activity {
    ListView lv;
    // ArrayList<String> list = new ArrayList<String>();
    ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
    MyListAdapter adtf;

    public static String prf_date_view = "";

    String str_start;
    Button all_detail;
    Button accepted_all;
    Button not_shown;
    public static SQLiteDatabase db;
    String name;
    File download;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_hope_list);


        list = DBAdapter.getUrl_Detail();
        Log.v("log_tag","list  :: "+list.size());
        lv = (ListView) findViewById(R.id.main_list_meet);
        adtf = new MyListAdapter(this);
        lv.setAdapter(adtf);

        SqliteAdpter dba = SqliteAdpter.getAdapterInstance(getApplicationContext());
        dba.createdatabase();
        db = dba.openDataBase();
    }



    public class MyListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public MyListAdapter(Context context) {
            mInflater = LayoutInflater.from(context);

        }

        public int getCount() {
            return list.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {

                convertView = mInflater
                        .inflate(R.layout.custome_list_view, null);


                Button cl = (Button) convertView.findViewById(R.id.cancle_sedual);
                final ProgressBar pr=(ProgressBar)convertView.findViewById(R.id.listprogressbar);

                //pr.setProgress(getItem(position));
                cl.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        str_start=list.get(position).url_video;
                        Log.v("log_tag","str_start  "+ str_start);

                        //
                        //new DownloadFileFromURL().execute(str_start);
                        new DownloadFileFromURL().execute(pr,str_start);
                    }
                });


            return convertView;
        }
    }


    class DownloadFileFromURL extends AsyncTask<Object, String, String> {


        int count = 0;
        ProgressDialog dialog;
        ProgressBar progressBar;
        int myProgress;
        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
             ProgressBar progressBar;

        }


        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(Object... params) {

            int count;
            progressBar= (ProgressBar) params[0];
            try {
                //URL url = new URL(f_url[0]);
                URL url = new URL((String)params[1]);
                Log.v("log_tag","name  ::: "+url);
                name = ((String) params[1]).substring(((String) params[1]).lastIndexOf("/") + 1);
                Log.v("log_tag","name Substring ::: "+name);
                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);
                  download = new File(Environment
                            .getExternalStorageDirectory()
                            + "/download/");
                          if (!download.exists()) {
                              download.mkdir();
                          }
                String strDownloaDuRL = download+"/" + name;
                Log.v("log_tag"," down url   " + strDownloaDuRL);
                FileOutputStream output = new FileOutputStream(strDownloaDuRL);


                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
         * */
        protected void onProgressUpdate(String... values) {
            progressBar.setProgress(0);
            super.onProgressUpdate(values);
            Log.v("log_tag","progress :: "+values);
            // setting progress percentage
            // pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {

            Log.v("log", "login  ::: 4::: "
                    + download);
            String videoPath =download +"/"+ name;
            String chpName = name;
            Log.v("log_tag","chpName  ::::"+ chpName +  "  videoPath " +videoPath);
            db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\"" + chpName + "\",\"" + videoPath + "\" )");

        }



    }


}

3 个答案:

答案 0 :(得分:3)

  

我们如何更新ListView中的进度条。当每个进度条   与文件相关联,并通过AsyncTask完成。

让AsyncTask接受对象参数数组,将每行的ProgressBar传递给asyncTask并完成。

现在onProgressUpdate更新已发送到asyncTask的引用progressBar的值

简单示例

class DownloadFileFromURL extends AsyncTask<Object, String, String> {

        ProgressBar progressBar;
        @Override
        protected String doInBackground(Object... params) {
            .....
            progressBar= (ProgressBar) params[0];

            try {
                 URL url = new URL((String)params[1]);
                }
           catch (MalformedURLException e) {}
           return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            ....
            progressBar.setProgress(0);
            super.onProgressUpdate(values);
        }

    }

现在您可以调用AsyncTask,如下所示:

  new DownloadFileFromURL().execute(pr,str_start);

答案 1 :(得分:3)

我在GridView中实现了这种类型的功能。 在该应用程序中,我使用VO(Value对象)管理进度条的状态。

我使用以下来执行AsnchTask。

new uploadTask(holder.progressBar,vo,this).execute();

在GridView的getView()方法中,

switch(data.getStateOfProgress())
     {
         case Constants.START_DOWNLOADING:
            holder.transBlackImage.setVisibility(View.VISIBLE);
             System.out.println("Downloading Starts........");
             holder.progressBar.setVisibility(View.VISIBLE);
             new DownloadToDeviceTask(holder.progressBar, data, this).execute();
             break;
         case Constants.STOP_DOWNLOADING:
            holder.transBlackImage.setVisibility(View.GONE);
             System.out.println("Downloading Stops..........");
             holder.progressBar.setVisibility(View.INVISIBLE);
             break;
         case Constants.DOWNLOADING:
             holder.transBlackImage.setVisibility(View.VISIBLE);
             holder.progressBar.setVisibility(View.VISIBLE);
             System.out.println("Downloading................");
             break;
         case Constants.START_UPLOADING:
            holder.transBlackImage.setVisibility(View.VISIBLE);
            holder.progressBar.setVisibility(View.VISIBLE);
             new UploadToStorageTask(holder.progressBar, data, this, isStoredOnBoth).execute();
             break;
         case Constants.STOP_UPLOADING:
            holder.transBlackImage.setVisibility(View.GONE);
             holder.progressBar.setVisibility(View.INVISIBLE);
             break;
         case Constants.UPLOADING:
            holder.transBlackImage.setVisibility(View.VISIBLE);
             holder.progressBar.setVisibility(View.VISIBLE);
             break;
     }

VO如下,

public class BookInfoVO {
private ArrayList<BookInfoVO> bookInfoVO;
private String bookTitle;
private String bookPublicInfo;
private float bookSize;
private int bookImage;
private int bookState;
private int typeOfData;
private String folderName;
private boolean checked;
private int stateOfProgress;

public void setBookTitle(String bookTitle) {
    this.bookTitle = bookTitle;
}
public String getBookTitle() {
    return bookTitle;
}
public void setBookPublicInfo(String bookPublicInfo) {
    this.bookPublicInfo = bookPublicInfo;
}
public String getBookPublicInfo() {
    return bookPublicInfo;
}
public void setBookSize(float bookSize) {
    this.bookSize = bookSize;
}
public float getBookSize() {
    return bookSize;
}
public void setBookImage(int bookImage) {
    this.bookImage = bookImage;
}
public int getBookImage() {
    return bookImage;
}
public void setBookState(int bookState) {
    this.bookState = bookState;
}
public int getBookState() {
    return bookState;
}
public void setTypeOfData(int typeOfData) {
    this.typeOfData = typeOfData;
}
public int getTypeOfData() {
    return typeOfData;
}
public void setBookInfoVO(ArrayList<BookInfoVO> bookInfoVO) {
    this.bookInfoVO = bookInfoVO;
}
public ArrayList<BookInfoVO> getBookInfoVO() {
    return bookInfoVO;
}
public void setFolderName(String folderName) {
    this.folderName = folderName;
}
public String getFolderName() {
    return folderName;
}
public void setChecked(boolean checked) {
    this.checked = checked;
}
public boolean isChecked() {
    return checked;
}
public void setStateOfProgress(int stateOfProgress) {
    this.stateOfProgress = stateOfProgress;
}
public int getStateOfProgress() {
    return stateOfProgress;
}

}

试试这个。

答案 2 :(得分:2)

尝试使用此循环更改可能有效

    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
                progressBar.setProgress((int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }

享受..&GT; !!