Android 获取发送到远程服务器的数据量
Android get the amount of data send to remote server
我使用 "Volley plus" 将文件发送到远程服务器,我想添加一个进度条来通知用户发送进度。
我找不到如何获取发送的字节数。
如果可能的话,我宁愿避免使用 TrafficStats。
我该怎么办?
您需要在文件上传代码中执行此操作..
获取特定大小的缓冲区,
byte[] buffer = new byte[BUFFER_SIZE];
在 FileInputStream 中读取您的文件..
final FileInputStream inputStream = new FileInputStream(uploadFile);
开始读取大小缓冲区的输入流,
while ((read = inputStream.read(buffer)) > 0) {
将这个已读取的缓冲区添加到 totalRead
totalRead += read;
将读取缓冲区写入输出流..
outputStream.write(buffer, 0, read);
现在使用总文件大小 (totalSize) 来确定完成的文件传输大小..
long totalSize = uploadFile.length();
写入outputStream后,通过以下公式计算百分比
int percentage = (int) ((totalRead / (float) totalSize) * 100);
完整代码下面的代码看起来像这样
byte[] buffer = new byte[BUFFER_SIZE];
try {
final FileInputStream inputStream = new FileInputStream(uploadFile);
long totalRead = 0;
long totalSize = uploadFile.length();
int read;
while ((read = inputStream.read(buffer)) > 0) {
totalRead += read;
int percentage = (int) ((totalRead / (float) totalSize) * 100);
outputStream.write(buffer, 0, read);
long now = System.currentTimeMillis();
if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < now - 100) {
lastProgressUpdateTime = now;
Log.e("", totalRead + " " + " " + percentage);
if (listener != null)
this.listener.onUpdateProgress(percentage, totalRead);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.flush();
}
我使用 "Volley plus" 将文件发送到远程服务器,我想添加一个进度条来通知用户发送进度。
我找不到如何获取发送的字节数。
如果可能的话,我宁愿避免使用 TrafficStats。
我该怎么办?
您需要在文件上传代码中执行此操作..
获取特定大小的缓冲区,
byte[] buffer = new byte[BUFFER_SIZE];
在 FileInputStream 中读取您的文件..
final FileInputStream inputStream = new FileInputStream(uploadFile);
开始读取大小缓冲区的输入流,
while ((read = inputStream.read(buffer)) > 0) {
将这个已读取的缓冲区添加到 totalRead
totalRead += read;
将读取缓冲区写入输出流..
outputStream.write(buffer, 0, read);
现在使用总文件大小 (totalSize) 来确定完成的文件传输大小..
long totalSize = uploadFile.length();
写入outputStream后,通过以下公式计算百分比
int percentage = (int) ((totalRead / (float) totalSize) * 100);
完整代码下面的代码看起来像这样
byte[] buffer = new byte[BUFFER_SIZE];
try {
final FileInputStream inputStream = new FileInputStream(uploadFile);
long totalRead = 0;
long totalSize = uploadFile.length();
int read;
while ((read = inputStream.read(buffer)) > 0) {
totalRead += read;
int percentage = (int) ((totalRead / (float) totalSize) * 100);
outputStream.write(buffer, 0, read);
long now = System.currentTimeMillis();
if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < now - 100) {
lastProgressUpdateTime = now;
Log.e("", totalRead + " " + " " + percentage);
if (listener != null)
this.listener.onUpdateProgress(percentage, totalRead);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.flush();
}