我正在为我的 Android 应用程序代码苦苦挣扎......
我正在尝试下载图片(通过 intentService),然后通过将 ImageView 添加到 LinearLayout 来显示它。
到目前为止一切顺利,管理下载的 intentservice 已将绝对路径发送给我。我用路径名 toast 。
但是我加了imageview就不能显示图片了。。。我也不知道为什么。。。
起初,我以为我的处理程序无法到达布局,但我设法使用 setImageResource 显示我的资源的随机图像。所以我猜问题来自 setimagebitmap 或 bitmapfactory decode...
在我的 Intentservice 中(输出是我的文件名):
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
messenger.send(msg);
} etc...
回到我的主要 Activity ,我有:
Private Handler handler = new Handler() {
public void handleMessage(Message message) {
// I Get the message
Object path = message.obj;
//Check if download went ok
if (message.arg1 == RESULT_OK && path != null) {
Toast.makeText(Update3sur3.this,
"Downloaded" + path.toString(), Toast.LENGTH_LONG)
.show();
//Try to display the pic
LinearLayout res2=(LinearLayout)findViewById(R.id.reslayout2);
ImageView imgView2 = new ImageView(Update3sur3.this);
Bitmap bitmap= BitmapFactory.decodeFile(path.toString());
imgView2.setImageBitmap(bitmap);
res2.addView(imgView2);
} else {
Toast.makeText(Update3sur3.this, "Download failed.",
Toast.LENGTH_LONG).show();
}
};
};
非常感谢!
劳伦特
最佳答案
首先我会尝试确保我是否可以正确访问该文件,即按照以下步骤操作:
使用 decodeByteArray(byte[] data, int offset, int length) 方法代替 BitmapFactory.decodeFile(path.toString())
要使用这种新方法,您必须自己读取文件的字节数组,这会增加额外的步骤,但您将确保您正在正确读取文件。
使用FileInputStream读取字节
文件 imageFile = new 文件(路径); byte imageData[] = new byte[(int)imageFile.length()];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFile);
in.read(imageData, 0, (int)imageFile.length());
Log.d("", "图像文件大小:"+ imageFile.length());//检查这里你得到的文件大小正确吗?
//现在 imageData 是您将用于生成图像的字节数组,因此: decodeByteArray(imageData, 0, (int) imageFile.length());
如果图像仍然没有出现,那么输入日志语句并打印图像的大小,看看它是否正确。
关于Android通过intentservice下载图片OK但无法在ImageVIew中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990745/