在现有的 Android 项目中,我遇到了以下代码(我在其中插入了调试垃圾)
ImageView img = null;
public void onCreate(...) {
img = (ImageView)findViewById(R.id.image);
new Thread() {
public void run() {
final Bitmap bmp = BitmapFactory.decodeFile("/sdcard/someImage.jpg");
System.out.println("bitmap: "+bmp.toString()+" img: "+img.toString());
if ( !img.post(new Runnable() {
public void run() {
System.out.println("setting bitmap...");
img.setImageBitmap(bmp);
System.out.println("bitmap set.");
}
}) ) System.out.println("Runnable won't run!");
System.out.println("runnable posted");
}
}.start();
Android 开发新手,并在 Google 上搜索过,我知道这是在不阻塞主 (UI) 线程的情况下做事的方法,同时在解码后仍将图像设置在 UI 线程上。(至少根据android-developers)(我已经通过Thread.currentThread().getName()
在各个地方登录来验证)
现在有时图像只是不显示,标准输出只说
I/System.out( 8066): bitmap: android.graphics.Bitmap@432f3ee8 img: android.widget.ImageView@4339d698
I/System.out( 8066): runnable posted
没有来自 Runnable 的消息的痕迹。所以看起来 Runnable 没有run()
,虽然img.post()
返回true
。拉入 ImageViewonCreate()
并声明它final
没有帮助。
我一无所知。简单地直接设置位图,同时阻塞 UI 线程,确实可以解决问题,但我想把事情做好。有人明白这里发生了什么吗?
(ps. 这都是在 Android 1.6 手机和 android-3 sdk 上观察到的)