我有一些令我困惑的问题。我似乎无法获得基于文件的 Uri 的正确真实路径。这是带有最终结果变量值的代码,如下所示:
String shareFile_Path = "";
String contentURI_Path_Real = "";
String contentURI_Path_Simple = "";
Uri myContentUri_Camera = null;
Bitmap myBitmap = SharedCode.sharedGetImageAsBitmapFromResource(thisActivityContext, R.drawable.replace__logo__app_256_256);
File mySharedFile_Camera = SharedCode.sharedSaveBitmapToInternalStoragePath(thisActivityContext, "shared", "camera.jpg", myBitmap);
if ( (mySharedFile_Camera != null) && (mySharedFile_Camera.exists()) ) {
shareFile_Path = mySharedFile_Camera.getAbsolutePath();
try {
myContentUri_Camera = FileProvider.getUriForFile(thisActivityContext, "com.example.app.fileprovider", mySharedFile_Camera);
}
catch (Exception e) {
String debug_s = e.toString();
}
if (myContentUri_Camera != null) {
contentURI_Path_Simple = myContentUri_Camera.getPath();
contentURI_Path_Real = SharedCode.sharedGetRealPathFromURI(thisActivityContext, myContentUri_Camera);
}
}
不同变量的最终结果:
- sharedFile_Path = "/data/data/com.example.app/files/shared/camera.jpg"
- contentURI_Path_Simple = "/providershared/camera.jpg"
- contentURI_Path_Real = ""
可以看出,问题在于contentURI_Path_Real的值,这就是SharedCode.sharedGetRealPathFromURI的完整代码在这里的原因——我最初通过 SO 找到的东西:
public static String sharedGetRealPathFromURI(Context context, Uri contentUri) {
String res = "";
if (contentUri != null) {
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(contentUri, null, null, null, null);
if (cursor !== null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
if (idx > -1) {
res = cursor.getString(idx);
}
}
}
catch(Exception e){
}
if (cursor != null) {
cursor.close();
}
}
return res;
}
单步执行代码时,似乎if (idx > -1)产生false。
...
这是AndroidManifest.xml的相关代码
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.app.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_filepaths" />
</provider>
这是provider_filepaths.xml的完整代码
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path path="shared/" name="providershared" />
</paths>
...
最后,在调用相机意图时,我需要一个有效的myContentUri_Camera :
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if ( (myContentUri_Camera != null) && (contentURI_Path_Real != "") ) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, myContentUri_Camera);
}
startActivityForResult(cameraIntent, CAMERA_REQUEST);
就像现在一样,如果传递了myContentUri_Camera ,相机会在完成后使应用程序崩溃 - 在onActivityResult返回之前。我怀疑这是因为它没有“真实路径”,这就是我在这里询问路径问题的原因。