如何在Android上显示从Firebase Storage的下载进度
作者:互联网
如何显示从Firebase存储的下载进度.我可以下载文件,但无法显示下载进度.我怎样才能做到这一点?
这是我的简单代码,可从Firebase存储区下载.mp3文件->
fun getSound(dSoundIndex : Int) {
Toast.makeText(context.applicationContext,"Starting Downloading",Toast.LENGTH_SHORT).show()
val mStorage = FirebaseStorage.getInstance("gs://depressioncuresounds-9e9a8.appspot.com")
val mStorageRef = mStorage.reference
try {
val downloadRef = mStorageRef.root.child(downloadPath)
val rootPath = File(Environment.getExternalStorageDirectory(),"DepressionCureSounds")
if(!rootPath.exists()){
rootPath.mkdirs()
}
val localFile = File(rootPath,"sound2.mp3")
downloadRef.getFile(localFile).addOnSuccessListener {
Toast.makeText(context.applicationContext, "Sound downloaded successfully", Toast.LENGTH_LONG).show()
when(context.soundAndImagesIndex){
5->{
context.isSoundDownloaded[0] = true
}
6->{
context.isSoundDownloaded[1] = true
}
7->{
context.isSoundDownloaded[2] = true
}
8->{
context.isSoundDownloaded[3] = true
}
9->{
context.isSoundDownloaded[4] = true
}
else->{
Toast.makeText(context.applicationContext,"Bug in coding",Toast.LENGTH_LONG).show()
}
}
}.addOnFailureListener { exception ->
Toast.makeText(context.applicationContext, "Failed to download file ${exception.toString()}", Toast.LENGTH_LONG).show()
}
} catch (e: IOException) {
Toast.makeText(context.applicationContext, "IOException failed to download file", Toast.LENGTH_LONG).show()
}
}
解决方法:
使用此工具,您可以从Firebase存储下载文件,进度监听器将为您提供进度.希望能帮助到你
//Show Progress Dialog\\
File localFile = File.createTempFile("audioFile", "mp3");
yourStorageReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//Dismiss Progress Dialog\\
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//Dismiss Progress Dialog\\
}
}).addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onProgress(FileDownloadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
yourProgressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
标签:android-studio-3-0,firebase-storage,android 来源: https://codeday.me/bug/20191110/2013712.html