[英]How to show progress on a progress bar (Retrofit Download)
我正在使用Retrofit从互联网上下载文件,我想做一个显示下载进度的进度条,但是我遇到了问题,我能够做一个通知(不完美)但是在某个时候工作.....但是就像一个无限进度条,没有显示下载的进度。 如何在进度条上显示进度?
private boolean writeResponseBodyToDisk(ResponseBody body, String fileName) {
try {
final int progressMax = 463451606;
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, activityIntent, 0);
final NotificationCompat.Builder notification = new NotificationCompat.Builder(this, CHANNEL_2_ID)
.setSmallIcon(R.drawable.ic_cloud_download_black_24dp)
.setContentTitle("Descargando")
.setContentText("Archivo descargando")
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setContentIntent(contentIntent)
.setProgress(progressMax, 0, true);
notificationManager.notify(2, notification.build());
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
final long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.e(TAG, "Archivo " + fileSizeDownloaded + " de " + fileSize);
new Thread(new Runnable() {
@Override
public void run() {
for (int fileSizeDownloaded = 0; fileSize <= progressMax; fileSizeDownloaded++) {
}
notification.setContentText("Completado")
.setProgress(0, 0, false)
.setOngoing(false);
notificationManager.notify(2, notification.build());
}
}).start();
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
Github上的OkHttp配方有一个如何做到这一点的例子。 https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.