我是Android和Firebase的初学者。我想将文件加载到Firebase存储中,并在上传完成后显示进度栏。
我正在从一个活动中调用方法,该活动将文件加载到Firebase存储中。 方法是:
public void uploadNewAudio(String filename, final String photoid, final String groupid, Context mContext,final ProgressBar progressBar){
progressBar.setVisibility(View.VISIBLE);
FilePaths filePaths = new FilePaths();
if(groupid==null) {
final String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
final StorageReference storageReference = mStorageReference
.child(filePaths.FIREBASE_AUDIO_STORAGE + "/" + user_id + "/" + photoid);
Uri uri = Uri.fromFile(new File(filename));
UploadTask uploadTask = null;
uploadTask = storageReference.putFile(uri);
Task<Uri> urlTask = uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
System.out.println("Upload is " + progress + "% done");
int currentprogress = (int) progress;
progressBar.setProgress(currentprogress);
}
}).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri firebaseUrl = task.getResult();
Toast.makeText(FirebaseMethods.this.mContext, "audio upload success", Toast.LENGTH_SHORT).show();
changeAudioPath(firebaseUrl.toString(), photoid,user_id);
progressBar.setVisibility(View.GONE);
} else {
Log.d(TAG, "onFailure: audio upload failed.");
Toast.makeText(FirebaseMethods.this.mContext, "audio upload failed ", Toast.LENGTH_SHORT).show();
}
}
});
}
}
我想暂停UI线程,直到上传完成并显示进度条,但是由于它是异步活动,因此会调用一个新活动(应在上传完成后发生),并且代码将继续执行。如何阻止这种情况的发生,并仅在上传完成后才调用新活动。