我正在尝试使用倒数锁存器来阻止主线程,直到上传完成。我知道那里有更好的方法,可以随意推荐一些方法,但是我认为我可以通过一个简短的加载屏幕。问题在于,永远不会调用getDownloadurl任务的回调。我已经搜寻了,无法找到答案。现在,我的代码直接来自文档。
fun uploadListing(listing: Listing, images: ArrayList<ByteArray>, onCompleteListener: () -> Unit = {}) {
val listingRef = FirebaseFirestore.getInstance().collection(LISTINGS_COLLECTION).document()
val storageRef = FirebaseStorage.getInstance().reference
listing.id = listingRef.id
val countDownLatch = CountDownLatch(images.size)
var i = 0
images.forEach {
val imageRef = storageRef.child("images/${listing.id}/$i")
val uploadTask = imageRef.putBytes(it)
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let { exception ->
throw exception
}
}
return@Continuation imageRef.downloadUrl
}).addOnCompleteListener { task ->
if (task.isSuccessful) {
listing.images.add(task.result.toString())
countDownLatch.countDown()
} else {
// Handle failures
// ...
}
}
}
countDownLatch.await()
listingRef.set(listing).addOnSuccessListener {
onCompleteListener()
}
}
我的gradle依赖...
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.google.firebase:firebase-firestore:17.1.5'
implementation 'com.google.firebase:firebase-storage:16.0.5'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.squareup.picasso:picasso:2.5.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
// implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:6.5.3'
implementation 'com.google.code.gson:gson:2.8.5'
}
答案 0 :(得分:0)
永远不要阻塞主线程。这通常是一个糟糕的主意(正如您刚刚发现的那样),并且可能导致您的应用因ANR崩溃。
如果要在完成一堆任务后注册另一个回调,请使用Tasks.whenAll()的一种变体,并将要完成的所有任务传递给它,然后再进行下一项工作。