1

我在使用最近发布的 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));

很难诊断,因为我不知道卡在内部做什么。

4

2 回答 2

0

而不是写

new FileInputStream(getAssets().openFd(fileName).getFileDescriptor());

你能试一下吗

getAssets().openFd(fileName).createInputStream();

看看它是否有效?

要回答您的原始问题,该addImage方法支持resource:file:URI。

于 2013-11-28T00:14:51.040 回答
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 的文件描述符。这很奇怪,因为我看到有人声称以前的方法有效。

于 2013-11-28T15:54:31.220 回答