在Android 7中,ContentResolver的method-openAssetFileDescriptor(vCardUri,"r")返回声明为Length为-1的AssetFileDescriptor [英] In Android 7, ContentResolver's method-openAssetFileDescriptor(vCardUri, "r") returns AssetFileDescriptor having declaredLength as -1
问题描述
在Android 7中,getContentResolver().openAssetFileDescriptor(vCardUri, "r")
返回将AssetFileDescriptor
声明为getDeclaredLength()
返回的-1的AssetFileDescriptor
.
In Android 7, getContentResolver().openAssetFileDescriptor(vCardUri, "r")
returns AssetFileDescriptor
having declaredLength as -1 returned by getDeclaredLength()
.
尝试将联系人作为vcard导出到vcf文件.我尝试过的代码如下
Trying to export the contacts as vcards into vcf file. The code I have tried is as follows
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd = resolver.openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] b = new byte[(int)fd.getDeclaredLength()];
fis.read(b);
上面的代码在Android 6或更低版本的Android 6上可以完美运行.但是,当使用Android 7运行时,创建byte []的行将导致NegativeByteArraySizeException
,因为clarifiedLength为-1.
当我调试下载Android 7的源代码时,发现了这个问题.
任何一种健康都是非常可观的.
The above code works perfectly in Android 6 or below.But when ran using Android 7, The line creating byte[] results in NegativeByteArraySizeException
as the declaredLength is -1.
When I debugged downloading the sources of Android 7, I observed the problem.
Any kind of health would be really appreciable.
推荐答案
在@pskink的帮助下,我发现以下解决了我的问题的方法.
With the help of @pskink, I found the following solve my problem.
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri vCardUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor assetFileDescriptor;
FileInputStream inputStream;
try {
assetFileDescriptor = getActivity().getContentResolver().openAssetFileDescriptor(vCardUri, "r");
if (assetFileDescriptor != null) {
inputStream = assetFileDescriptor.createInputStream();
return readAsByteArray(inputStream);
}
} catch (FileNotFoundException e) {
Log.e(TAG, "Vcard for the contact " + lookupKey + " not found", e);
} catch (IOException e) {
Log.e(TAG, "Problem creating stream from the assetFileDescriptor.", e);
}
其中的readAsByteArray()是使用 Mihai代码段中的代码编写的.
where the readAsByteArray() is written using the code from Mihai Snippet.
谢谢@pskink
这篇关于在Android 7中,ContentResolver的method-openAssetFileDescriptor(vCardUri,"r")返回声明为Length为-1的AssetFileDescriptor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!