使用Android中的Volley下载文件时显示百分比的进度条

时间:2016-06-15 11:27:34

标签: android download android-volley

我正在使用volley使用异步任务下载文件。我想在下载文件时显示百分比的进度。但问题是异步任务是在响应到来时启动的。在最终响应完全到来之前,我找不到任何方法来跟踪进度。 我没有在JsonRequest中找到可用于此的任何方法。

下面是请求类的onResponse方法,它扩展了我正在使用的JsonRequest。

 protected Response<T> parseNetworkResponse(NetworkResponse response) {
if (response.statusCode >= 200 && response.statusCode <= 299) {
                // If the status is correct, we return a success but with a null object, because the server didn't return anything
                return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
            }
         else {
            try {
                if (downloadFlag) {
                    DownloadFileAsyncTask downloadFileAsyncTask = new DownloadFileAsyncTask(mContext, fileNameAndExtn,mNotifyManager,mBuilder,mDownloadNotificationUniqueId);
                    downloadFileAsyncTask.execute(response.data);
                } else if (isResponseByteArr) {
                    return (Response<T>) Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
                } else {
                  String json = null;
                    if (isGzipped(response)) {
                        json = gzipDecompress(response.data);
                    } else {
                        json = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
                    }

                    T parsedObject = gson.fromJson(json, clazz);
                    return Response.success(parsedObject, HttpHeaderParser.parseCacheHeaders(response));
                }
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JsonSyntaxException e) {
                return Response.error(new ParseError(e));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

DownFileAsyncTask如下:     包com.android.webframework.webservice;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.android.applogger.AppLogger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class DownloadFileAsyncTask extends AsyncTask<byte[], Integer, String> {
    private String fileNameAndExtn;
    private Context mContext;
    private NotificationManager mNotifyManager;
    private NotificationCompat.Builder mBuilder;
    private int mUniqueId;

    public DownloadFileAsyncTask(Context context, String fileNameAndExtn, NotificationManager notifyManager, NotificationCompat.Builder builder, int uniqueId) {
        this.fileNameAndExtn = fileNameAndExtn;
        this.mContext = context;
        this.mNotifyManager = notifyManager;
        this.mBuilder = builder;
        this.mUniqueId = uniqueId;
    }

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

    String MEDIA_MOUNTED = "mounted";

    @Override
    protected String doInBackground(byte[]... bytes) {
        File file = null;
        int copyCount = 0;
        String filePath = "";
        String diskState = Environment.getExternalStorageState();
        if (diskState.equalsIgnoreCase(MEDIA_MOUNTED)) {
            File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            file = new File(sd, fileNameAndExtn);

            String fileName = "";
            String fileExtn;

            String fileNameToSave = fileNameAndExtn;

            while (file.exists()) {

                copyCount++;

                String[] parts = fileNameAndExtn.split("[.]");

                if (parts[0] != null)
                    fileName = parts[0];

                fileName += "-" + copyCount;

                fileNameToSave = fileName + "." + parts[1];

                file = new File(sd, fileNameToSave);

            }

            fileNameAndExtn = fileNameToSave;

            /*if (file.exists()) {

                file.delete();
            }*/

            try {
                FileOutputStream fos = new FileOutputStream(file.getPath());
                fos.write(bytes[0]);
                fos.close();
            } catch (IOException e) {
                AppLogger.e("file", "Exception in photoCallback", e);
            }
            AppLogger.e("file Download completed", "***************");

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(Uri.fromFile(file));
            mContext.sendBroadcast(intent);

            filePath = file.getAbsolutePath();
        } else {
            Toast.makeText(mContext, "The external disk is not mounted.", Toast.LENGTH_SHORT).show();
        }
        return (filePath);
    }

    @Override
    protected void onPostExecute(String filePath) {
        super.onPostExecute(filePath);
        if (fileNameAndExtn != null && !fileNameAndExtn.equalsIgnoreCase("")) {
//            Toast.makeText(mContext, "File downloaded in Downloads/" + fileNameAndExtn, Toast.LENGTH_LONG).show();
            Toast.makeText(mContext, fileNameAndExtn + " downloaded successfully", Toast.LENGTH_LONG).show();
            mBuilder.setProgress(100, 100, false);
            Intent intent = getPendingIntent(mContext, filePath);
            mBuilder.setContentTitle(fileNameAndExtn)
                    .setAutoCancel(true)
                    .setContentText("Download complete");
            PendingIntent pendingIntent = null;
            if (intent != null) {
                pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            }

            if (pendingIntent != null) {
                mBuilder.setContentIntent(pendingIntent).setProgress(0, 0, false);
            }

            mNotifyManager.notify(mUniqueId, mBuilder.build());

        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        mBuilder.setProgress(100, values[0], false);
        mNotifyManager.notify(mUniqueId, mBuilder.build());
        super.onProgressUpdate(values);
    }

    public Intent getPendingIntent(Context context, String filePath) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
//                File file = new File("YOUR_SONG_URI"); // set your audio path
        File file = new File(filePath);
        intent.setDataAndType(Uri.fromFile(file), getMimeType(filePath));

        if (intent.resolveActivityInfo(context.getApplicationContext().
                getPackageManager(), 0) != null) {
//            context.getApplicationContext().startActivity(intent);
            return intent;
        } else {
            Toast.makeText(context, "File not present or Explorer app not present.",
                    Toast.LENGTH_LONG).show();
            return null;
            // if you reach this place, it means there is no any file
            // explorer app installed on your device
        }
    }

    public static String getMimeType(String url) {
        String filePathWithoutWhiteSpace = url.replaceAll("\\s", "%20");
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(filePathWithoutWhiteSpace);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
        }
        return type;
    }
}

2 个答案:

答案 0 :(得分:0)

不确定您是否可以通过排球来执行此操作,但是您可以使用AsyncTask轻松解决此问题。这是一个链接http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/他做了同样的事情你正在寻找。

答案 1 :(得分:0)

我通过用户点击下载后立即创建通知解决了这个问题,然后在下载完成后异步任务通知但我无法在下载时显示确切的进度。