Android获取发送到远程服务器的数据量
我使用“Volley plus”向远程服务器发送一个文件,并希望添加一个ProgressBar来通知用户发送进度 我找不到如何获取发送的字节数 如果可能的话,我宁愿避免使用TrafficStatsAndroid获取发送到远程服务器的数据量,android,android-volley,Android,Android Volley,我使用“Volley plus”向远程服务器发送一个文件,并希望添加一个ProgressBar来通知用户发送进度 我找不到如何获取发送的字节数 如果可能的话,我宁愿避免使用TrafficStats 我该怎么办 您需要在文件上载代码中执行此操作 取适当大小的缓冲区 byte[] buffer = new byte[BUFFER_SIZE]; 在FileInputStream中读取文件 final FileInputStream inputStream = new FileInputStream
我该怎么办 您需要在文件上载代码中执行此操作 取适当大小的缓冲区
byte[] buffer = new byte[BUFFER_SIZE];
在FileInputStream中读取文件
final FileInputStream inputStream = new FileInputStream(uploadFile);
开始读取缓冲区大小的inputstream
while ((read = inputStream.read(buffer)) > 0) {
将此已读缓冲区添加到totalRead
totalRead += read;
将读缓冲区写入输出流
outputStream.write(buffer, 0, read);
现在使用total filesize(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();
}
byte[]buffer=新字节[buffer_SIZE];
试一试{
final FileInputStream inputStream=新FileInputStream(上传文件);
长totalRead=0;
long totalSize=uploadFile.length();
int-read;
而((read=inputStream.read(buffer))>0){
totalRead+=读取;
整数百分比=(整数)((totalRead/(float)totalSize)*100);
写入(缓冲区,0,读取);
long now=System.currentTimeMillis();
如果(lastProgressUpdateTime==0 | | lastProgressUpdateTime