我正在使用Kotlin和Picasso来显示来自URL的图片。现在我正在用一个Intent共享一些内容,我正在共享图片和一些文本。这是我的代码。
Picasso.get().load(URL).into(object : Target {
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
val shareIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND_MULTIPLE
putExtra(Intent.EXTRA_STREAM, getBitmapFromView(bitmap, this@DealActivity))
putExtra(Intent.EXTRA_TEXT, textForShare)
type = "image/jpeg"
}
startActivity(Intent.createChooser(shareIntent, "SEND"))
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) { }
override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) { }
})
这工作,一些时间。大多数时候,什么都没有发生。这是我的日志。
2020-05-14 22:12:52.378 11310-11402/il.co.nazooza D/Picasso: Dispatcher enqueued [R19]+2ms
2020-05-14 22:12:52.380 11310-11430/il.co.nazooza D/Picasso: Hunter executing [R19]+3ms
2020-05-14 22:12:53.150 11310-11430/il.co.nazooza D/Picasso: Hunter decoded [R19]+773ms
2020-05-14 22:12:53.151 11310-11402/il.co.nazooza D/Picasso: Dispatcher batched [R19]+775ms for completion
2020-05-14 22:12:53.195 11310-11310/il.co.nazooza D/Picasso: Main canceled [R19]+813ms target got garbage collected
我读到目标必须被做成一个字段 但我在Kotlin中很难做到这一点。
看起来这段代码是在一个 Activity
所以你只需要在你的 Activity
并将其存储在那里。
class MyActivity: Activity() {
private var shareTarget: Target? = null
//...
fun someMethod() {
shareTarget = object : Target {
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
val shareIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND_MULTIPLE
putExtra(Intent.EXTRA_STREAM, getBitmapFromView(bitmap, this@DealActivity))
putExtra(Intent.EXTRA_TEXT, textForShare)
type = "image/jpeg"
}
startActivity(Intent.createChooser(shareIntent, "SEND"))
// don't need to store it any longer
shareTarget = null
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) { }
override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {
// don't need to store it any longer
shareTarget = null
}
}
Picasso.get().load(URL).into(shareTarget)
}
// ...
}
请注意,这是假设你每次只有一个这样的请求在飞行中。 如果你有多个请求,你将不得不把它们存储在一个集合中,或者多个变量中,或者类似的东西。