我被困在如何使用asynctask在finally块中实现代码的问题。该图像需要花费一些时间来上传,到那时,用户可能已经单击了sendButton,将他带到下一个活动并将imageURL发送为null。 如果我在按下发送之前给它时间,即等到下载URL在日志中弹出,该应用程序就可以正常工作。因此,我需要有关如何在异步任务中实现此代码的帮助。我试图将大多数代码放在一个新函数中,但是后来我能够在myTask类中调用该函数。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_snaps)
val userInputMessage = findViewById<EditText>(R.id.userinput)
val sendButton = findViewById<ImageButton>(R.id.sendButton)
userInputMessage.visibility = View.INVISIBLE
sendButton.visibility = View.INVISIBLE
checkStoragePermission()
val imageButton = findViewById<ImageButton>(R.id.imagebutton)
imageButton.setOnClickListener {
imageButton.visibility = View.INVISIBLE
createImageGallery()
lock()
val storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val galleryFolder = File(storageDirectory, resources.getString(R.string.app_name))
val argument = createImageFile(galleryFolder)
val outputPhoto: FileOutputStream? = FileOutputStream(argument)
try {
textureview.getBitmap().compress(Bitmap.CompressFormat.PNG, 40, outputPhoto)
} catch (e: Exception) {
e.printStackTrace()
} finally {
// Do this part async
val imageTBP: Uri = Uri.fromFile(argument)
val storageRef = storage.getReference().child("images").child(imagetbpname)
val uploadTask = storageRef.putFile(imageTBP)
uploadTask.addOnFailureListener(OnFailureListener{
Toast.makeText(this, "Upload Failed", Toast.LENGTH_SHORT).show()
}).addOnSuccessListener(OnSuccessListener<UploadTask.TaskSnapshot>{
storageRef.getDownloadUrl().addOnSuccessListener(OnSuccessListener<Uri> {
downloadURL = it.toString()
Log.i("URL", downloadURL)
})
})
try {
if(outputPhoto != null){
outputPhoto.close()
}
} catch (e: IOException){
Log.e(TAG, e.toString())
}
sendButton.visibility = View.VISIBLE
userInputMessage!!.visibility = View.VISIBLE
}
}
sendButton.setOnClickListener {
val intent = Intent(this, ChooseUserActivity::class.java)
intent.putExtra("imageName", imagetbpname)
Toast.makeText(this, "download URL $downloadURL", Toast.LENGTH_LONG).show()
intent.putExtra("imageURL", downloadURL)
intent.putExtra("Message", userInputMessage!!.text.toString())
startActivity(intent)
}
}
class myTask: AsyncTask<Void, String, Void>() {
override fun doInBackground(vararg p0: Void?): Void? {
return null
}
override fun onProgressUpdate(vararg values: String?) {
super.onProgressUpdate(*values)
}
}
答案 0 :(得分:0)
尝试使用此方法代替上层方法。并使您Specification ID Primary Site
1234 Site1
12345 Site2
123456 Site3
是全局变量
SPEC_ID Z_PRIMARY_SITE
Specification ID Primary Site
1234 Site1
12345 Site2
123456 Site3