在Android中,进度条在到达终点之前消失

在Android中,进度条在到达终点之前消失,android,android-asynctask,progress-bar,Android,Android Asynctask,Progress Bar,我正在尝试使用异步任务下载视频文件。视频正在完美下载,但进度条在结束前消失,并再次开始下载。下载图像文件时不会发生这种情况 这是我的密码 FileDownloadTask.Java public class FileDownloadTask extends AsyncTask<String, Integer, String> { private static final String TAG = FileDownloadTask.class.getSimpleName(

我正在尝试使用异步任务下载视频文件。视频正在完美下载,但进度条在结束前消失,并再次开始下载。下载图像文件时不会发生这种情况

这是我的密码

FileDownloadTask.Java

public class FileDownloadTask extends AsyncTask<String, Integer, String> {
    private static final String    TAG = FileDownloadTask.class.getSimpleName();
    final DownloadInfo  mInfo;
    //public static String file_url = "http://www.gettyimages.ca/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg";
   //public static String file_url="http://imaze.net/apps/groups/123.mp4";
   // Context context=getApplicationContext();
    public FileDownloadTask(DownloadInfo info) {
        mInfo = info;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        mInfo.setProgress(values[0]);
        ProgressBar bar = mInfo.getProgressBar();
        if(bar != null) {
            bar.setProgress(mInfo.getProgress());
            bar.invalidate();
        }
    }

     @Override

     protected String doInBackground(String... f_url) {
         int count;
         try {
             String root = Environment.getExternalStorageDirectory().toString();

             System.out.println("Downloading");
             URL url = new URL(mInfo.getFileUrl());

             URLConnection conection = url.openConnection();
             conection.connect();
             // getting file length
             int lenghtOfFile = conection.getContentLength();

             // input stream to read file - with 8k buffer

             // Output stream to write file
             File rootdirectory= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),"Youtube Videos");
              if(!rootdirectory.exists())
              {
                  rootdirectory.mkdirs();
              }
             String nameoffile= URLUtil.guessFileName(mInfo.getFileUrl(),null, MimeTypeMap.getFileExtensionFromUrl(mInfo.getFileUrl()));
             File file= new File(rootdirectory,nameoffile);
             file.createNewFile();



             mInfo.setDownloadState(DownloadState.DOWNLOADING);
             InputStream input = new BufferedInputStream(url.openStream(), 8192);

             OutputStream output = new FileOutputStream(file);
             byte data[] = new byte[1024];

             long total = 0;
             while ((count = input.read(data)) != -1) {
                 total += count;
               publishProgress((int)(total*1001)/lenghtOfFile);
                 // writing data to file
                 output.write(data, 0, count);

             }

             // flushing output
             output.flush();

             // closing streams
             output.close();
             input.close();
//             Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//             intent.setData(Uri.parse(file_url));
//             getActivity().sendBroadcast(intent);

         } catch (Exception e) {
             Log.e("Error: ", e.getMessage());
         }
         mInfo.setDownloadState(DownloadState.COMPLETE);
         return null;
     }








             protected void onPostExecute(String file_url) {
        mInfo.setDownloadState(DownloadState.COMPLETE);

    }

    @Override
    protected void onPreExecute() {
        mInfo.setDownloadState(DownloadState.DOWNLOADING);
    }


}
import android.util.Log;
import android.widget.ProgressBar;


public class DownloadInfo {
    private final static String TAG = DownloadInfo.class.getSimpleName();
    public enum DownloadState {
        NOT_STARTED,
        QUEUED,
        DOWNLOADING,
        COMPLETE
    }
    private volatile DownloadState mDownloadState = DownloadState.NOT_STARTED;
    private  String mFilename;
//    private final String mFileUrl;
private  Integer mFileSize;
    private  String mFileUrl="";
    private volatile Integer mProgress;
  //  private final Integer mFileSize;
    private volatile ProgressBar mProgressBar;

    public DownloadInfo(String filename, String FileUrl) {
        mFilename = filename;
        mProgress = 0;
        mFileUrl = FileUrl;
     //   mFileSize = mFileSize;

      //  mFileSize = size;
        mProgressBar = null;
    }

    public ProgressBar getProgressBar() {
        return mProgressBar;
    }
    public void setProgressBar(ProgressBar progressBar) {
        Log.d(TAG, "setProgressBar " + mFilename + " to " + progressBar);
        mProgressBar = progressBar;
    }

    public void setDownloadState(DownloadState state) {
        mDownloadState = state;
    }
    public DownloadState getDownloadState() {
        return mDownloadState;
    }

    public Integer getProgress() {
        return mProgress;
    }

    public void setProgress(Integer progress) {
        this.mProgress = progress;
    }
//
//    public Integer getFileSize() {
//        return mFileSize;
//   }



    public Integer getFileSize() {
        return mFileSize;
    }

    public void setFileSize(Integer FileSize) {
        mFileSize = FileSize;
    }
//    public void setFileUrl(String FileUrl)
//    {
//        this.FileUrl = FileUrl;
//    }


public String getFilename() {
    return mFilename;
}
    public String getFileUrl()
    {
        return mFileUrl;
    }
}
public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
    // Simple class to make it so that we don't have to call findViewById frequently
    private static class ViewHolder {
        TextView textView;
        ProgressBar progressBar;
        Button button;
        DownloadInfo info;
    }


    private static final String TAG = DownloadInfoArrayAdapter.class.getSimpleName();

    public DownloadInfoArrayAdapter(Context context, int textViewResourceId,
                                    List<DownloadInfo> objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        final DownloadInfo info = getItem(position);
        // We need to set the convertView's progressBar to null.

        ViewHolder holder = null;

        if(null == row) {
            LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.file_download_row, parent, false);

            holder = new ViewHolder();
            holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
            holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
            holder.button = (Button)row.findViewById(R.id.downloadButton);
            holder.info = info;

            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();

            holder.info.setProgressBar(null);
            holder.info = info;
            holder.info.setProgressBar(holder.progressBar);
        }

        holder.textView.setText(info.getFilename());
        holder.progressBar.setProgress(info.getProgress());
        holder.progressBar.setMax(100);
        info.setProgressBar(holder.progressBar);

        holder.button.setEnabled(info.getDownloadState() == DownloadState.NOT_STARTED);
        final Button button = holder.button;
        holder.button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                info.setDownloadState(DownloadState.QUEUED);
                button.setEnabled(false);
                button.invalidate();
                FileDownloadTask task = new FileDownloadTask(info);
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        });


        //TODO: When reusing a view, invalidate the current progressBar.

        return row;
    }

}
下载InfoArrayAdapter.Java

public class FileDownloadTask extends AsyncTask<String, Integer, String> {
    private static final String    TAG = FileDownloadTask.class.getSimpleName();
    final DownloadInfo  mInfo;
    //public static String file_url = "http://www.gettyimages.ca/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg";
   //public static String file_url="http://imaze.net/apps/groups/123.mp4";
   // Context context=getApplicationContext();
    public FileDownloadTask(DownloadInfo info) {
        mInfo = info;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        mInfo.setProgress(values[0]);
        ProgressBar bar = mInfo.getProgressBar();
        if(bar != null) {
            bar.setProgress(mInfo.getProgress());
            bar.invalidate();
        }
    }

     @Override

     protected String doInBackground(String... f_url) {
         int count;
         try {
             String root = Environment.getExternalStorageDirectory().toString();

             System.out.println("Downloading");
             URL url = new URL(mInfo.getFileUrl());

             URLConnection conection = url.openConnection();
             conection.connect();
             // getting file length
             int lenghtOfFile = conection.getContentLength();

             // input stream to read file - with 8k buffer

             // Output stream to write file
             File rootdirectory= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),"Youtube Videos");
              if(!rootdirectory.exists())
              {
                  rootdirectory.mkdirs();
              }
             String nameoffile= URLUtil.guessFileName(mInfo.getFileUrl(),null, MimeTypeMap.getFileExtensionFromUrl(mInfo.getFileUrl()));
             File file= new File(rootdirectory,nameoffile);
             file.createNewFile();



             mInfo.setDownloadState(DownloadState.DOWNLOADING);
             InputStream input = new BufferedInputStream(url.openStream(), 8192);

             OutputStream output = new FileOutputStream(file);
             byte data[] = new byte[1024];

             long total = 0;
             while ((count = input.read(data)) != -1) {
                 total += count;
               publishProgress((int)(total*1001)/lenghtOfFile);
                 // writing data to file
                 output.write(data, 0, count);

             }

             // flushing output
             output.flush();

             // closing streams
             output.close();
             input.close();
//             Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//             intent.setData(Uri.parse(file_url));
//             getActivity().sendBroadcast(intent);

         } catch (Exception e) {
             Log.e("Error: ", e.getMessage());
         }
         mInfo.setDownloadState(DownloadState.COMPLETE);
         return null;
     }








             protected void onPostExecute(String file_url) {
        mInfo.setDownloadState(DownloadState.COMPLETE);

    }

    @Override
    protected void onPreExecute() {
        mInfo.setDownloadState(DownloadState.DOWNLOADING);
    }


}
import android.util.Log;
import android.widget.ProgressBar;


public class DownloadInfo {
    private final static String TAG = DownloadInfo.class.getSimpleName();
    public enum DownloadState {
        NOT_STARTED,
        QUEUED,
        DOWNLOADING,
        COMPLETE
    }
    private volatile DownloadState mDownloadState = DownloadState.NOT_STARTED;
    private  String mFilename;
//    private final String mFileUrl;
private  Integer mFileSize;
    private  String mFileUrl="";
    private volatile Integer mProgress;
  //  private final Integer mFileSize;
    private volatile ProgressBar mProgressBar;

    public DownloadInfo(String filename, String FileUrl) {
        mFilename = filename;
        mProgress = 0;
        mFileUrl = FileUrl;
     //   mFileSize = mFileSize;

      //  mFileSize = size;
        mProgressBar = null;
    }

    public ProgressBar getProgressBar() {
        return mProgressBar;
    }
    public void setProgressBar(ProgressBar progressBar) {
        Log.d(TAG, "setProgressBar " + mFilename + " to " + progressBar);
        mProgressBar = progressBar;
    }

    public void setDownloadState(DownloadState state) {
        mDownloadState = state;
    }
    public DownloadState getDownloadState() {
        return mDownloadState;
    }

    public Integer getProgress() {
        return mProgress;
    }

    public void setProgress(Integer progress) {
        this.mProgress = progress;
    }
//
//    public Integer getFileSize() {
//        return mFileSize;
//   }



    public Integer getFileSize() {
        return mFileSize;
    }

    public void setFileSize(Integer FileSize) {
        mFileSize = FileSize;
    }
//    public void setFileUrl(String FileUrl)
//    {
//        this.FileUrl = FileUrl;
//    }


public String getFilename() {
    return mFilename;
}
    public String getFileUrl()
    {
        return mFileUrl;
    }
}
public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
    // Simple class to make it so that we don't have to call findViewById frequently
    private static class ViewHolder {
        TextView textView;
        ProgressBar progressBar;
        Button button;
        DownloadInfo info;
    }


    private static final String TAG = DownloadInfoArrayAdapter.class.getSimpleName();

    public DownloadInfoArrayAdapter(Context context, int textViewResourceId,
                                    List<DownloadInfo> objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        final DownloadInfo info = getItem(position);
        // We need to set the convertView's progressBar to null.

        ViewHolder holder = null;

        if(null == row) {
            LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.file_download_row, parent, false);

            holder = new ViewHolder();
            holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
            holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
            holder.button = (Button)row.findViewById(R.id.downloadButton);
            holder.info = info;

            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();

            holder.info.setProgressBar(null);
            holder.info = info;
            holder.info.setProgressBar(holder.progressBar);
        }

        holder.textView.setText(info.getFilename());
        holder.progressBar.setProgress(info.getProgress());
        holder.progressBar.setMax(100);
        info.setProgressBar(holder.progressBar);

        holder.button.setEnabled(info.getDownloadState() == DownloadState.NOT_STARTED);
        final Button button = holder.button;
        holder.button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                info.setDownloadState(DownloadState.QUEUED);
                button.setEnabled(false);
                button.invalidate();
                FileDownloadTask task = new FileDownloadTask(info);
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        });


        //TODO: When reusing a view, invalidate the current progressBar.

        return row;
    }

}
公共类下载InfoArrayAdapter扩展了ArrayAdapter{
//简单的类,这样我们就不必频繁调用findViewById
私有静态类视图持有者{
文本视图文本视图;
ProgressBar ProgressBar;
按钮;
下载资讯;
}
private static final String TAG=DownloadInfoArrayAdapter.class.getSimpleName();
公开下载InfoArrayAdapter(上下文,int textViewResourceId,
列出对象){
超级(上下文、textViewResourceId、对象);
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
视图行=转换视图;
最终下载信息=getItem(位置);
//我们需要将convertView的progressBar设置为null。
ViewHolder=null;
如果(空==行){
LayoutInflater充气器=(LayoutInflater)getContext().getSystemService(Context.LAYOUT\u充气器\u SERVICE);
行=充气机。充气(R.layout.file\u download\u行,父级,false);
holder=新的ViewHolder();
holder.textView=(textView)row.findViewById(R.id.downloadFileName);
holder.progressBar=(progressBar)row.findViewById(R.id.downloadProgressBar);
holder.button=(button)row.findViewById(R.id.downloadButton);
holder.info=info;
row.setTag(支架);
}否则{
holder=(ViewHolder)row.getTag();
holder.info.setProgressBar(空);
holder.info=info;
holder.info.setProgressBar(holder.progressBar);
}
holder.textView.setText(info.getFilename());
holder.progressBar.setProgress(info.getProgress());
保持架.进度条.设定最大值(100);
信息设置进度条(持有者进度条);
holder.button.setEnabled(info.getDownloadState()==DownloadState.NOT_start);
最终按钮=保持架按钮;
holder.button.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
info.setDownloadState(DownloadState.QUEUED);
按钮。设置启用(错误);
按钮。无效();
FileDownloadTask任务=新建FileDownloadTask(信息);
task.executeOnExecutor(异步task.THREAD\u POOL\u EXECUTOR);
}
});
//TODO:重用视图时,使当前进度栏无效。
返回行;
}
}

条无效()
在方法
onProgressUpdate
中从
FileDownloadTask.Java
文件中删除这一行,它仍然会消失,而不是
bar.invalidate()
使用
bar.postInvalidate()否。。在适配器类中放置“holder.progressBar.setMax(100);”时也会发生同样的情况。这是问题吗?如果是,那么我应该写什么?