Why email attachment is empty attached from external storage? - android

Developing Android email plugin for Unity. I have a screenshot in the files/ folder of the app, I want to attach to mail. As it turned out, I cannot attach from there directly. I implemented a FileProvider, but it turned out that it exist only above 4.0.
So I implemented the suggested workaround, to save it to external storage, then attach from there. Saving seems work, even reading seems work, but still, Gmail says "Can't attach empty file". Also When launching email intent, I have an error message, like:
E/HwEmailTag( 7327): AttachmentUtilities->inferMimeTypeForUri->Unable to determine MIME type for uri=/storage/emulated/0/com.eppz.plugins_screenshot.jpg
I tried application/image, image/jpg as intent.setType(), still the same, while Gmail says the file is empty.
Is this something with emulated external storage /storage/emulated/0/? The device has no SD card, but I've read that getExternalStorage() returns a shared / public place for files in such cases either.
It should work. Should I remove dots from filename? Hope not. Here's the corresponding code:
String saveImageAtPathToExternalStorage(String imagePath)
{
Log.i(TAG, "saveImageAtPathToExternalStorage(...)");
// Create bitmap.
File imageFile = new File(imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), new BitmapFactory.Options());
// Output.
String outputFileName = _unityPlayerActivity.getPackageName()+"_screenshot.jpg";
String externalStorageDirectory = Environment.getExternalStorageDirectory().toString();
File outputImageFile = new File(externalStorageDirectory, outputFileName);
String outputImagePath = outputImageFile.getAbsolutePath();
if (outputImageFile.exists()) outputImageFile.delete(); // Delete if existed
try
{
// Write JPG.
FileOutputStream outputStream = new FileOutputStream(outputImageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
Log.i(TAG, "Image written to `"+outputImagePath+"`");
}
catch (Exception e)
{ e.printStackTrace(); }
// Return with output path.
return outputImagePath;
}
public void openMailComposer(String to, String subject, String body, int isHTML, String attachmentImagePath)
{
Log.i(TAG, "openMailComposer(...)");
// Attachment image.
File attachmentImageFile = new File(attachmentImagePath);
if (attachmentImageFile.exists() == false)
{
Log.i(TAG, IMAGE_NOT_FOUND);
SendUnityMessage(OPEN_MAIL_COMPOSER_CALLBACK_METHOD_NAME, IMAGE_NOT_FOUND);
return;
}
// Save to external first.
String externalImagePath = saveImageAtPathToExternalStorage(attachmentImagePath);
final Uri externalImageUri = Uri.parse(externalImagePath);
Log.i(TAG, "externalImageUri `"+externalImageUri+"`");
// Intent.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_EMAIL, to);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, body);
if (isHTML == 1) intent.putExtra(Intent.EXTRA_HTML_TEXT, body);
// Attach.
intent.putExtra(Intent.EXTRA_STREAM, externalImageUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent, "Send email"), OPEN_MAIL_COMPOSER_REQUEST_CODE);
}
I'm relatively new to Android development, and really want to believe, but having all this hassle compared to having a single line for this in iOS is quiet distressing.
I'm running this on a Huawei MediaPad (TT1 7.0), Android 4.4.2, and I want it to run about Android 2.3+ basically (why I refused using FileProvider earlier).

Related

Android - Access External Storage Files Android 10/11

I really need your help because I'm stuck <.<
I have already tryed all solutions I've found here in "stackoverflow" for this problem, but any of them worked for me..
I have updated my application to follow the new Google Play Store policies, so actually my app is using only "Scoped Storage" without "Shared Storage" behaviour, so I've removed from the manifest the "requestLegacyExternalStorage".
In my app I need to send to the server some file selected by the user, these file can be stored in the "internal storage" or in the "external storage". They are always stored outside of the app-specific directory, so the directory in:
"/storage/emulated/0/Android/data/[APP_PACKAGE]/files"
My biggest problem is that I can't open any file stored outside of the app-specific directory!
I really need to open the files that the user has selected and convert its content to "base64" to send it to the server.
But when I use this method to get the file content encoded in base64:
public static String fileToBase64(#NonNull String filePath) {
String ret = null;
byte[] buffer = new byte[8192];
int bytesRead;
try(ByteArrayOutputStream bAOS = new ByteArrayOutputStream();
Base64OutputStream b64OS = new Base64OutputStream(bAOS, Base64.DEFAULT);
InputStream iS = new FileInputStream(filePath)){
while ((bytesRead = iS.read(buffer)) != -0x1) {
b64OS.write(buffer, 0x0, bytesRead);
}
b64OS.flush();
ret = bAOS.toString();
} catch (IOException ioE) {
Logger.onException(TAG, ioE);
}
return ret;
}
I always get an ACCESS PERMISSION DENIED.
Is there any way to solve this problem without using "requestLegacyStorage" in the manifest?
I know that Google will remove all applications that don't use only "SCOPED STORAGE" from the store starting from 5 of july, so I can't use the "reqestLegacyStorage" to solve this problem...
I'm already requesting and giving the "READ_EXTERNAL_STORAGE" and "WRITE_EXTERNAL_STORAGE" permissions, but I still can't open the file content if it is stored outside of the dedicated application directory...
I can only open and encode file content if it is in the app directory (so: "/storage/emulated/0/Android/data/[APP_PACKAGE]/files"), but I need to upload to my server files choosed by the user so these files were never stored inside the app directory, they are always stored inside the internal storage or the external storage in directories like the "Download" dir or the "Pictures" dir (I need to upload every type of files, so pictures, documents, pdfs ecc.. ecc.)
Is there any solution to this problem?
I have already tryed all the solutions I found online, but I always get an ACCESS EXCEPTION if I don't add "requestLegacyStorage" to the manifest (and I can't add it to notg go against Google's policies...)
Please I really need to solve this problem because this is one of the most important feature of my app..
Thank you so much!
I hope anybody can help me solve this problem T_T
Have a nice day and nice coding!
(Ask if you need more informations and I will add them!)
##########################################################################
If anyone needs it I found a "solution" but works only by using "ACTION_GET_CONTENT" (and probably by using "ACTION_OPEN_DOCUMENT", but I didn't try it yet).
When you select a file (stored outside the app-specific directory) using "ACTION_GET_CONTENT" this file is copied inside the app-specific directory ("/storage/emulated/0/Android/data/[APP_PACKAGE]/files") so you can open it because it agrees with the "SCOPED STORAGE" policy.
# "ACTION_GET_CONTENT" code:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
String[] mimes = {
"application/*",
"audio/*",
"font/*",
"image/*",
"message/*",
"model/*",
"multipart/*",
"text/*",
"video/*"
};
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimes);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, getString(R.string.msg_select_file_to_upload)), REQ_CODE_OPEN_DOCUMENT);
Theoretically it also works without passing the "mimes" array to the intent extra "EXTRA_MIME_TYPES".
To get the path inside the "onActivityResult":
String path = FilesUtils.onActivityResultOpenDocument(this, data);
public static String onActivityResultOpenDocument(Context context, Intent data){
String selectedPath, fileName;
Uri uri = data.getData();
String mimeType = context.getContentResolver().getType(uri);
if (mimeType == null) {
String path = getPathFromOpenDocumentUri(context, uri);
if (path == null) {
fileName = FilenameUtils.getName(uri.toString());
} else {
File file = new File(path);
fileName = file.getName();
}
} else {
Uri returnUri = data.getData();
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
fileName = returnCursor.getString(nameIndex);
}
String sourcePath = context.getExternalFilesDir(null).toString();
selectedPath = formatFilepath(sourcePath, fileName);
File fileSave = new File(selectedPath);
try {
copyUriStreamToFile(context, uri, fileSave);
} catch (Exception e) {
Logger.onException(TAG, e);
Toast.makeText(context, R.string.error_impossibile_recuperare_file, Toast.LENGTH_SHORT).show();
selectedPath = null;
}
return selectedPath;
}
So summarizing by using "ACTION_GET_CONTENT" (and maybe "ACTION_OPEN_DOCUMENT" too, but I didn't tryed this) the selected file is copied inside the app-specific directory (so: "/storage/emulated/0/Android/data/[APP_PACKAGE]/files") in this way the file can be opened because it agrees with the "Scoped Storage" policy.
Thank you all for your answers and your time! (: <3
I still don't know how to read a file if it is stored outside the app-specific directory, so if anybody know it please share your solution (:

Send screenshot by email Android 8.0

I've asked a similar question before but I figured it out myself. But I now have a new problem, my device updated to android 8.0 and now email intent is not working. I don't want to downgrade my device if possible.
private void sendScreen() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".png";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream);
outputStream.flush();
outputStream.close();
File filelocation = new File(MediaStore.Images.Media.DATA + mPath);
Uri myUri = Uri.parse("file://" + filelocation);
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"Enter your email address"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Journey : " + now );
startActivity(Intent.createChooser(emailIntent , "Select your preferred email app.."));
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
This is my code which worked perfectly on android 7.0. The code takes a screenshot, time stamps it, saves it to the local storage and then attached it to an email app of the users choice. Anyone have a solution? Thanks
This is my code which worked perfectly on android 7.0
It should have crashed with a FileUriExposedException.
now email intent is not working
You did not explain what "is not working" means. I am going to guess that you are crashing with a FileUriExposedException. A file Uri — whether via Uri.fromFile() or your Uri.parse("file://"+...) approach — is not usable on Android 7.0+ by default. Switch to using FileProvider and getUriForFile().

"Permission denied for the attachment" (on Gmail 5.0) trying to attach file to email intent

This question has been posted before, but there was no clear or accepted answer and all of the solutions provided that were supposed to "work" didn't for me. See here: Gmail 5.0 app fails with "Permission denied for the attachment" when it receives ACTION_SEND intent
I have an app which builds up data in a text file and needs to send the text file along in an email, automatically attaching it. I have tried many ways to get this to attach, and it apparently works for Gmail 4.9 and below but 5.0 has some new permission features disabling it from doing what I wish.
Intent i = new Intent(Intent.ACTION_SEND);
String to = emailRecipient.getText().toString();
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
i.putExtra(Intent.EXTRA_SUBJECT, "Pebble Accelerometer Data");
i.putExtra(Intent.EXTRA_TEXT, "Attached are files containing accelerometer data captured by SmokeBeat Pebble app.");
String[] dataPieces = fileManager.getListOfData(getApplicationContext());
for(int i2 = 0; i2 < dataPieces.length; i2++){
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(getApplicationContext().getFilesDir() + File.separator + dataPieces[i2])));
}
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(getApplicationContext().getFilesDir() + File.separator + fileManager.getCurrentFileName(getApplicationContext()))));
Log.e("file loc", getApplicationContext().getFilesDir() + File.separator + fileManager.getCurrentFileName(getApplicationContext()));
try {
startActivity(Intent.createChooser(i, "Send Email"));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Main.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
The datapieces might be empty yes but the current file line below the for loop is always reliable and always attaches something.
I have tried changing
Uri.fromFile()
to
Uri.parse()
When I do that, it attaches, but Gmail then crashes and when I check the logcat it's because of a null pointer. This is most likely because Gmail has no access to the file and therefore results as null.
I've also tried using
getCacheDir()
instead of
getFilesDir()
and it has the same outcome.
What am I doing wrong here, and how should I go about fixing it? Some example code would be really, really handy because I am new to Android development and explaining what I need to do without some sort of push off probably won't end up helping.
Thanks a lot.
Alright guys. Took a break and came back, figured it out.
Here's how it works, you need to have write/read permissions to external storage, so add these permissions to your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Then, your file has to be copied from your app's internal storage directory into the app's external directory. I recommend you use internal storage, and that's what I'm doing here so you can figure out SD cards yourself.
Here is the block of code that does the magic. Logs are included but you can remove them by all means.
public void writeToExternal(Context context, String filename){
try {
File file = new File(context.getExternalFilesDir(null), filename); //Get file location from external source
InputStream is = new FileInputStream(context.getFilesDir() + File.separator + filename); //get file location from internal
OutputStream os = new FileOutputStream(file); //Open your OutputStream and pass in the file you want to write to
byte[] toWrite = new byte[is.available()]; //Init a byte array for handing data transfer
Log.i("Available ", is.available() + "");
int result = is.read(toWrite); //Read the data from the byte array
Log.i("Result", result + "");
os.write(toWrite); //Write it to the output stream
is.close(); //Close it
os.close(); //Close it
Log.i("Copying to", "" + context.getExternalFilesDir(null) + File.separator + filename);
Log.i("Copying from", context.getFilesDir() + File.separator + filename + "");
} catch (Exception e) {
Toast.makeText(context, "File write failed: " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show(); //if there's an error, make a piece of toast and serve it up
}
}
Encountered the same attachment denied. Permissions in manifest did not have any effect, rather do not have an effect any more since API 23. Finally solved it as follows.
1st need to check and grant permissions on run-time, I did it in my main activity:
public static final int MY_PERMISSIONS_REQUEST_READ_STORAGE=10001;
private void checkPermission(){
if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (this.shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user asynchronously
} else {
// No explanation needed, we can request the permission.
this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_STORAGE);
}
}
}
Now when sending, create a file in PUBLIC directory (tried saving to my app folder - same denial problem)
public File createFile(){
String htmlStr="<!DOCTYPE html>\n<html>\n<body>\n<p>my html file</p></body></html>";
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "aimexplorersummary.html");
try {
FileWriter writer = new FileWriter(file ,false);
writer.write(htmlStr);
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return file;
}
Now compose sending intent and putExtra with uri to your file which is in public storage that user must grant permissions to and that causes no problem now
public void send(){
Intent intentSend = new Intent(android.content.Intent.ACTION_SEND);
intentSend.setType("text/html");
File file = createFile();
if(file!=null){
intentSend.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
}
startActivity(Intent.createChooser(intentSend, "Send using:"));
}

How to open Context.MODE_PRIVATE files with external apps

I have a string (called comments) that contains some text that I want to display using an external app. I initially create the file like so:
String end = "rtf";
FileOutputStream outputStream;
try {
outputStream = openFileOutput("document." + end, Context.MODE_PRIVATE);
outputStream.write(comments.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
However I am unable to open the file with an external application when I try the following:
String type = "text/rtf";
Intent intent = new Intent (Intent.ACTION_VIEW);
File file = new File(getFilesDir() + "/document." + end);
Uri fileUri = Uri.fromFile(file);
intent.setDataAndType(fileUri,type);
startActivityForResult(intent, Intent.FLAG_GRANT_READ_URI_PERMISSION);
The message that I receive when I open try to the document with the external app is:
"open failed: EACCESS (Permission denied)."
Please advise. Thanks.
However I am unable to open the file with an external application when I try the following:
Correct. Intent.FLAG_GRANT_READ_URI_PERMISSION is for use with a ContentProvider, not for bare file:// Uri values, such as you are using. Use FileProvider to add such a ContentProvider to your app. See also the "Sharing Files" training module and this sample app.
Bear in mind that there's a good chance that your next problem will be an ActivityNotFoundException, as relatively few Android devices will have an app that will support the text/rtf MIME type.

Trouble writing internal memory android

void launchImageCapture(Activity context) {
Uri imageFileUri = context.getContentResolver()
.insert(Media.INTERNAL_CONTENT_URI, new ContentValues());
m_queue.add(imageFileUri);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
context.startActivityForResult(i, ImportActivity.CAMERA_REQUEST);
}
The above code, which has always worked, is now generating this exception for me at insert().
java.lang.UnsupportedOperationException: Writing to internal storage is not supported.
at com.android.providers.media.MediaProvider.generateFileName(MediaProvider.java:2336)
at com.android.providers.media.MediaProvider.ensureFile(MediaProvider.java:1851)
at com.android.providers.media.MediaProvider.insertInternal(MediaProvider.java:2006)
at com.android.providers.media.MediaProvider.insert(MediaProvider.java:1974)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:150)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:140)
at android.os.Binder.execTransact(Binder.java:287)
at dalvik.system.NativeStart.run(Native Method)
It is not a space issue, and the only thing I changed was the package of an unrelated class all together. Also, I restarted my phone.
Facing same problem here, I was happy to find this thread. Even though two things were bugging me in this workaround, this post had me looking in the right direction. I'd like to share my own workaround/solution.
Let me begin by stating what I did not see myself living with.
First, I did not want to leave the application private file as MODE_WORLD_WRITEABLE. This looks like non-sense to me, although I cannot figure exactly how another application could access this file unless knowing where to look for it with complete name and path. I'm not saying it is necessarily bad for your scenario, but it is still bugging me somehow. I would prefer to cover all my bases by having picture files really private to my app. In my business case, pictures are of no use outside of the application and by no means should they be deleteable via, say, the Android Gallery. My app will trigger cleanup at an appropriate time so as to not vampirize Droid device storage space.
Second, openFileOutput() do not leave any option but to save the resulting file in the root of getFilesDir(). What if I need some directory structure to keep things in order? In addition, my application must handle more than one picture, so I would like to have the filename generated so I can refer to it later on.
See, it is easy to capture a photo with the camera and save it to public image area (via MediaStore) on the Droid device. It is also easy to manipulate (query, update, delete) media from MediaStore. Interestingly, inserting camera picture to MediaStore genreates a filename which appears to be unique. It is also easy to create private File for an application with a directory structure. The crux of the "Capturea camera picture and save it to internal memory" problem is that you can't do so directly because Android prevents ContentResolver to use Media.INTERNAL_CONTENT_URI, and because private app files are by definition not accessible via the (outside) Camera activity.
Finally I adopted the following strategy:
Start the Camera activity for result from my app with the Intent to capture image.
When returning to my app, insert capture to the MediaStore.
Query the MediaStore to obtain generated image file name.
Create a truly internal file onto whatever path relative to private application data folder using Context.getDir().
Use an OutputStream to write Bitmap data to this private file.
Delete capture from MediaStore.
(Optional) show an ImageView of the capture in my app.
Here is the code starting the cam:
public void onClick (View v)
{
ContentValues values = new ContentValues ();
values.put (Media.IS_PRIVATE, 1);
values.put (Media.TITLE, "Xenios Mobile Private Image");
values.put (Media.DESCRIPTION, "Classification Picture taken via Xenios Mobile.");
Uri picUri = getActivity ().getContentResolver ().insert (Media.EXTERNAL_CONTENT_URI, values);
//Keep a reference in app for now, we might need it later.
((XeniosMob) getActivity ().getApplication ()).setCamPicUri (picUri);
Intent takePicture = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
//May or may not be populated depending on devices.
takePicture.putExtra (MediaStore.EXTRA_OUTPUT, picUri);
getActivity ().startActivityForResult (takePicture, R.id.action_camera_start);
}
And here is my activity getting cam result:
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
super.onActivityResult (requestCode, resultCode, data);
if (requestCode == R.id.action_camera_start)
{
if (resultCode == RESULT_OK)
{
Bitmap pic = null;
Uri picUri = null;
//Some Droid devices (as mine: Acer 500 tablet) leave data Intent null.
if (data == null) {
picUri = ((XeniosMob) getApplication ()).getCamPicUri ();
} else
{
Bundle extras = data.getExtras ();
picUri = (Uri) extras.get (MediaStore.EXTRA_OUTPUT);
}
try
{
pic = Media.getBitmap (getContentResolver (), picUri);
} catch (FileNotFoundException ex)
{
Logger.getLogger (getClass ().getName ()).log (Level.SEVERE, null, ex);
} catch (IOException ex)
{
Logger.getLogger (getClass ().getName ()).log (Level.SEVERE, null, ex);
}
//Getting (creating it if necessary) a private directory named app_Pictures
//Using MODE_PRIVATE seems to prefix the directory name provided with "app_".
File dir = getDir (Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);
//Query the MediaStore to retrieve generated filename for the capture.
Cursor query = getContentResolver ().query (
picUri,
new String [] {
Media.DISPLAY_NAME,
Media.TITLE
},
null, null, null
);
boolean gotOne = query.moveToFirst ();
File internalFile = null;
if (gotOne)
{
String dn = query.getString (query.getColumnIndexOrThrow (Media.DISPLAY_NAME));
String title = query.getString (query.getColumnIndexOrThrow (Media.TITLE));
query.close ();
//Generated name is a ".jpg" on my device (tablet Acer 500).
//I prefer to work with ".png".
internalFile = new File (dir, dn.subSequence (0, dn.lastIndexOf (".")).toString () + ".png");
internalFile.setReadable (true);
internalFile.setWritable (true);
internalFile.setExecutable (true);
try
{
internalFile.createNewFile ();
//Use an output stream to write picture data to internal file.
FileOutputStream fos = new FileOutputStream (internalFile);
BufferedOutputStream bos = new BufferedOutputStream (fos);
//Use lossless compression.
pic.compress (Bitmap.CompressFormat.PNG, 100, bos);
bos.flush ();
bos.close ();
} catch (FileNotFoundException ex)
{
Logger.getLogger (EvaluationActivity.class.getName()).log (Level.SEVERE, null, ex);
} catch (IOException ex)
{
Logger.getLogger (EvaluationActivity.class.getName()).log (Level.SEVERE, null, ex);
}
}
//Update picture Uri to that of internal file.
((XeniosMob) getApplication ()).setCamPicUri (Uri.fromFile (internalFile));
//Don't keep capture in public storage space (no Android Gallery use)
int delete = getContentResolver ().delete (picUri, null, null);
//rather just keep Uri references here
//visit.add (pic);
//Show the picture in app!
ViewGroup photoLayout = (ViewGroup) findViewById (R.id.layout_photo_area);
ImageView iv = new ImageView (photoLayout.getContext ());
iv.setImageBitmap (pic);
photoLayout.addView (iv, 120, 120);
}
else if (resultCode == RESULT_CANCELED)
{
Toast toast = Toast.makeText (this, "Picture capture has been cancelled.", Toast.LENGTH_LONG);
toast.show ();
}
}
}
Voila! Now we have a truly application private picture file, which name has been generated by the Droid device. And nothing is kept in the public storage area, thus preventing accidental picture manipulation.
here is my working code to save a captured image from the camera to app internal storage:
first, create the file with the desired filename. in this case it is "MyFile.jpg", then start the activity with the intent below. you're callback method(onActivityResult), will be called once complete. After onActivityResult has been called your image should be saved to internal storage. key note: the mode used in openFileOutput needs to be global.. Context.MODE_WORLD_WRITEABLE works fine, i have not tested other modes.
try {
FileOutputStream fos = openFileOutput("MyFile.jpg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpg");
startActivityForResult(
new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f))
, IMAGE_CAPTURE_REQUEST_CODE);
}
catch(IOException e) {
}
and in the activity result method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == IMAGE_CAPTURE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Log.i(TAG, "Image is saved.");
}
}
to retrieve your image:
try {
InputStream is = openFileInput("MyFile.jpg");
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 4;
Bitmap retrievedBitmap = BitmapFactory.decodeStream(is, null, options);
}
catch(IOException e) {
}
The camera apparently doesn't support writing to internal storage.
Unfortunately this is not mentioned in the documentation.
MediaProvider.java has the following code:
private String generateFileName(boolean internal,
String preferredExtension, String directoryName)
{
// create a random file
String name = String.valueOf(System.currentTimeMillis());
if (internal) {
throw new UnsupportedOperationException(
"Writing to internal storage is not supported.");
// return Environment.getDataDirectory()
// + "/" + directoryName + "/" + name + preferredExtension;
} else {
return Environment.getExternalStorageDirectory()
+ "/" + directoryName + "/" + name + preferredExtension;
}
}
So writing to internal storage has been intentionally disabled for the time being.
Edit - I think you can use binnyb's method as a work-around, but I wouldn't recommend it; I'm not sure if this will continue to work on future versions. I think the intention is to disallow writing to internal storage for media files.
I filed a bug in the Android issue tracker.
Edit - I now understand why binnyb's method works. The camera app is considered to be just another application. It can't write to internal storage if it doesn't have permissions. Setting your file to be world-writable gives other applications permission to write to that file.
I still don't think that this is a very good idea, however, for a few reasons:
You don't generally want other apps writing to your private storage.
Internal storage is quite limited on some phones, and raw camera images are quite large.
If you were planning on resizing the image anyway, then you can read it from external storage and write it yourself to your internal storage.

Categories

Resources