gpt4 book ai didi

java - 如何在进度条上显示进度(Retrofit 下载)

转载 作者:行者123 更新时间:2023-12-02 05:38:02 27 4
gpt4 key购买 nike

我正在使用 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

关于java - 如何在进度条上显示进度(Retrofit 下载),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56154926/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com