在Android 7.0上分享联系人

时间:2016-10-03 09:45:38

标签: android share contacts android-7.0-nougat

问题是当我尝试在Android 7.0上分享联系人时,我的应用程序崩溃了。

   final ContentResolver resolver = context.getContentResolver();

            cursor = resolver.query(contactsUri, null, null, null, null);
            String name = "";
            String contactLookupKey = "";
            if (cursor != null && cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndexOrThrow(
                        ContactsContract.Contacts.DISPLAY_NAME));
                contactLookupKey = cursor.getString(cursor.getColumnIndexOrThrow(
                        ContactsContract.Contacts.LOOKUP_KEY));
            }

            name = name.replaceAll("[^0-9a-zA-Z]", "_");
            name = name + "_" + CONTACT_PREFIX;
            Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI,
                    contactLookupKey);

            File storageDir = new File(Environment.getExternalStorageDirectory(), "contacts");
            if (!storageDir.exists()) {
                storageDir.mkdir();
            }
            File vCardFile = File.createTempFile(name, ".vcf", storageDir);

            if (!vCardFile.exists()) {
                vCardFile.createNewFile();
            }
            fileOutputStream = new FileOutputStream(vCardFile);

            AssetFileDescriptor
                    fd = resolver.openAssetFileDescriptor(uri, "r");

            fis = fd.createInputStream();

            final byte[] buf = new byte[(int) fd.getDeclaredLength()];

fd.getDeclaredLength() - return "-1" and app crash? 

可能有什么问题?

1 个答案:

答案 0 :(得分:1)

解决方案/ 相反:

final byte[] buf = new byte[(int) fd.getDeclaredLength()];

使用:

byte[] buf;

if (fd.getDeclaredLength() != AssetFileDescriptor.UNKNOWN_LENGTH) {
    buf = new byte[(int) fd.getDeclaredLength()];
} else {
    buf = new byte[fis.available()];
}
fis.read(buf);