Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

android - Camera Intent not saving photo

I successfully have used this code snippet before, but with the file pointing to somewhere on the SD card.

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);

However when I use getCacheDir instead of a loc on the SD card it seems the photo is never saved. Is this a limitation of cache dir and image capture?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Technically, this is because writing to internal storage is not supported when using the Camera application to capture an image. In fact, you may notice an exception printed in logcat stating Writing to internal storage is not supported. However, the real reason this doesn't work is because by default you are creating a file that is private to your application package and another application (i.e. the Camera app) can't access that file location because it doesn't have permission to do so. External storage is the only globally accessibly portion of the filesystem.

The workaround is for you to create the file with global (WORLD_WRITEABLE) permissions. Typically, this allows the Camera app to access the file via the passed Uri. There aren't really methods to do this directly on File, so you have to create the file using the methods available in Context and then grab a handle to it afterward:

//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");

This also sort of limits where you can place the file since the Context methods inherently create files in the root "files" directory, and you can't redirect that to the cache directory.

HTH


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...