我以前成功地使用过这个代码片段,但是文件指向SD卡上的某个地方。
final File temp = new File(getCacheDir(), "temp.jpg");
temp.delete();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp));
startActivityForResult(intent, CONFIG.Intents.Actions.SELECT_CAMERA_PHOTO);
然而,当我使用getCacheDir而不是SD卡上的loc时,照片似乎从未保存过。这是缓存目录和图像捕获的限制吗?
发布于 2011-10-11 09:27:56
从技术上讲,这是因为使用相机应用程序捕获图像时不支持写入内部存储。实际上,您可能会注意到在logcat中打印了一个异常,声明为Writing to internal storage is not supported
。然而,这不起作用的真正原因是,默认情况下,您正在创建一个应用程序包的私有文件,而另一个应用程序(即相机应用程序)无法访问该文件位置,因为它没有权限这样做。外部存储是文件系统唯一可全局访问的部分。
解决方法是创建具有全局(WORLD_WRITEABLE)权限的文件。通常,这允许相机应用程序通过传递的Uri访问文件。在File
上没有真正能做到这一点的方法,所以您必须使用Context
中提供的方法创建文件,然后获取该文件的句柄:
//Remove if exists, the file MUST be created using the lines below
File f = new File(getFilesDir(), "Captured.jpg");
f.delete();
//Create new file
FileOutputStream fos = openFileOutput("Captured.jpg", Context.MODE_WORLD_WRITEABLE);
fos.close();
//Get reference to the file
File f = new File(getFilesDir(), "Captured.jpg");
这也在某种程度上限制了您可以放置文件的位置,因为Context
方法固有地在根" files“目录中创建文件,而您不能将其重定向到缓存目录。
HTH
https://stackoverflow.com/questions/7720383
复制相似问题