我尝试使用此代码中的服务导出联系人,它在android 6.0中成功,但是在7.0及更高版本上,该应用已停止工作。
这是我的代码:
@Override
public IBinder onBind(Intent p1) {
// TODO: Implement this method
return null;
}
Cursor cursor;
ArrayList<String> vCard ;
String vfile;
@Override public void onStart(Intent intent, int startId) {
try {
getVcardString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void getVcardString() throws IOException {
final String vfile = "/android"+"/data"+"/com.export"+"/saved/"+"POContactsRestore.vcf";
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0) {
int i;
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
cursor.moveToFirst();
for(i = 0;i<cursor.getCount();i++) {
get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
mFileOutputStream.write(vCard.get(i).toString().getBytes());
}
mFileOutputStream.close();
cursor.close();
} else {
Log.d("TAG", "No Contacts in Your Phone");
}
}
private void get(Cursor cursor2) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
如何导出Android Nougat及更高版本的联系人?
最好将其导出到文本文件而不是VCF中,但这不是主要问题。我首先需要成功导出联系人。