In an existing Android project I've encountered the following piece of code (where I inserted the debugging litter)
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();
New to Android development, and having googled around, I understand that this is the way to do stuff without blocking the main (UI) thread, while still setting the image on the UI thread after decoding. (at least according to android-developers) (which I have verified by logging Thread.currentThread().getName()
at various places)
Now sometimes the image just doesn't show up, and stdout only says
I/System.out( 8066): bitmap: android.graphics.Bitmap@432f3ee8 img: android.widget.ImageView@4339d698
I/System.out( 8066): runnable posted
with not a trace of the messages from the Runnable. So appearantly the Runnable doesn't run()
, although img.post()
returns true
. Pulling the ImageView in onCreate()
and declaring it final
doesn't help.
I'm clueless. Simply setting the bitmap directly, while blocking the UI thread, does fix things, but I want to get things right. Does anybody understand what's going on here?
(ps. this was all observed on an Android 1.6 phone and android-3 sdk)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…