我在使用最近发布的GDK中的卡时遇到问题。基本上,Card.addImage()只能接受两个参数,即资源ID或URI。
对于我的用例,我需要打开一个作为文件存在的图像,而不是直接作为资源。因此,出于测试目的,我将图像包含在assets文件夹中。试图直接从资产文件夹访问它们失败,所以我将它们从那里复制到内部存储。复制完成后,我会从文件中生成一个URI并将其分配给卡片。生成的卡片显示图像所在的灰色块。
String fileName = step.attachment; //of the form, "folder1/images/image1.jpg"
File outFile = new File(getFilesDir()+File.separator+fileName);
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
//check to see if the file has already been cached in internal storage before copying
if(!outFile.exists()) {
FileInputStream inputStream = new FileInputStream(getAssets().openFd(fileName).getFileDescriptor());
FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
inputChannel = inputStream.getChannel();
outputChannel = outputStream.getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(inputChannel!=null)
inputChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(outputChannel!=null)
outputChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
card.addImage(Uri.fromFile(outFile));
很难诊断,因为我不知道卡在内部做了什么。
答案 0 :(得分:0)
而不是写
new FileInputStream(getAssets().openFd(fileName).getFileDescriptor());
你可以尝试吗?
getAssets().openFd(fileName).createInputStream();
看看它是否有效?
要回答原始问题,addImage
方法支持resource:
和file:
URI。
答案 1 :(得分:0)
这很奇怪,但我设法解决了我的问题。我用以下内容替换了文件复制代码,它似乎解决了我的问题
InputStream in = null;
OutputStream out = null;
try {
in = getAssets().open(step.attachment);
out = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + step.attachment, e);
}
我不清楚为什么/如何复制我的整个apk,但我猜这是对
的调用getAssets().openFd(fileName).getFileDescriptor()
也许它正在返回apk的文件描述符。这很奇怪,因为我看到一些声称前一种方法有效。