【发布时间】:2017-07-17 14:15:28
【问题描述】:
因为我是 Java 新手,所以我自己编写了这段代码,其中一些部分是从其他来源学习的。我想将所有联系人信息备份到主存储或 sdcard 中的 .vcf 文件中(没关系),最后将它们取回。但在这段代码中你只能看到备份部分:
public class MainActivity extends Activity
{
Cursor cursor;
ArrayList<String> vCard ;
String vfile;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vfile = "Contacts" + "_" + System.currentTimeMillis()+".vcf";
getVcardString();
}
private void getVcardString() {
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{
get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
}
}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}
}
public void get(Cursor cursor)
{
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);
String storage_path = Environment.getRootDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
mFileOutputStream.write(vcardstring.toString().getBytes());
} catch (Exception e1)
{
e1.printStackTrace();
}
}
}
问题是代码不起作用并且没有出现异常或任何错误。我搜索了根目录和所有文件夹,但没有 .vcf 文件。我的权限是:<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
我在 API 17 和 24 上运行了它。知道为什么它不起作用吗?
【问题讨论】:
-
要获取 SD 卡路径,您必须使用 Environment.getExternalStorageDirectory() Environment.getRootDirectory() 返回设备根目录“/” - 您无法在此目录中写入(或读取)在非根设备上。
-
您也获得了写入外部存储权限吗?
-
@kapsym 啊,我不知道我也应该使用该权限,但我的首要任务是将该文件保存在设备的存储中。如果 Environment.getRootDirectory() 不起作用,那么我应该如何将它保存在设备内存中? (不是外部存储器)
-
如果你不想要外部存储,那么你可以使用内部存储。在这种情况下,您不需要写权限,并且您的文件将仅对您的应用程序可见。参考这里-developer.android.com/guide/topics/data/…
-
@kapsym Tnx,有几个问题:1:我的代码现在是否正确,应该可以正常用于内部存储?