Sending file via email from Cache directory - android

I am trying to send file attached email from my App.
The file saved into external storage(SDCard) can successfully attached, but the same file that is saved into temporary directory where I can get getCacheDir() method cannot be attached.
The only difference is to where the file I want to attatch is saved,
Is this because of an Android spec or limitation, or am I missing something?
I'm using ACTION_SEND intent to send attachment file via email
//// getting file path to save
//[fail] -- no attatchment in email
//path = new StorageUtil().getCacheFilePath(this, "attatchment.html");
//[success] -- attatchment.html is on email
path = new StorageUtil().getExternalAppStoragePath(this, "attatchment.html");
/// start intent if file saving is successful
if (this.export(path)==true) {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.setType("text/html");
i.putExtra(Intent.EXTRA_SUBJECT, "a subject");
i.putExtra(Intent.EXTRA_TEXT, "");
File f = new File(path);
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(Intent.createChooser(i, "Send Email"));
}
getCacheFilePath() creates path from following code where fileName is the second argument of the method:
File cacheDir = ctx.getCacheDir();
File cacheFile = new File(cacheDir, fileName);
return cacheFile.getPath(); //path
each path is as follows
//cache dir (attachcment failed):
/data/data/{PACKAGE_NAME}/cache/attachment.html
//external dir (attachment successed):
/mnt/sdcard/Android/data/{PACKAGE_NAME}/files/attachment.html
File object from the cache dir canRead() and could obtain file length.
thanks!
== SOLVED ==
I found that the following error is on Logcat when sending Gmail:
file:// attachment paths must point to file:///mnt/sdcard. Ignoring attachment file:///data/data/{PACKAGE_NAME}/cache/attachment.html"
So this should be a Android limitation. Adding Intent.FLAG_GRANT_READ_URI_PERMISSION has no effect and other Activity like Dropbox results similar.

I suggest you to use getExternalCacheDir() instead of getCacheDir(), which point to "/storage/emulated/0/Android/data/". File under this folder seems can be attached to gmail.

Related

Uri and storage paths differ - Xamarin

Where a downloaded file is stored and where Uri goes to pick it up are not the same.
Java.IO.File file = new Java.IO.File(Query.filePathh);
Console.WriteLine("Downloaded file PATH: " + Query.filePathh);
Intent open = new Intent(Intent.ActionView);
open.AddFlags(ActivityFlags.GrantReadUriPermission);
open.SetFlags(ActivityFlags.NewTask);
Context context = Android.App.Application.Context;
Android.Net.Uri fileUri = FileProvider.GetUriForFile(context, "com.companyname.Login.provider", file).NormalizeScheme();
Console.WriteLine("File uri: " + fileUri.Path);
open.SetDataAndType(fileUri, "*/*");
Intent intentC = Intent.CreateChooser(open, "Open With");
intentC.AddFlags(ActivityFlags.GrantReadUriPermission);
intentC.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intentC);
We get pop-up that asked how to open a file, but when the application tries to open it, it crashes with an error that the file path does not exist.
While debugging we tried to see file locations on where the file is downloaded and what Uri is calling and we get:
For storage_path:
storage/emulated/0/Download/How_to_initialize_your_Xamarin_app_to_use_AppConnect_C#_APIs.pdf
For Uri path:
/external/Download/How_to_initialize_your_Xamarin_app_to_use_AppConnect_C#_APIs.pdf
We can open the file normally if we go to Download folder in our Emulator.
Any suggestions on what to do?

Open a Downloaded file (pdf) from the Downloads folder in the INTERNAL STORAGE

I have downloaded a file (133465.pdf) using the Download manager and now it is stored in the Downloads folder of the mobile phone (Internal storage).
How should i try and retrieve the downloaded pdf from the Downloads folder?
I am using the below code to try and retrieve the pdf from the downloads folder but i am getting an error on the Toast, saying "Cannot display PDF (133465.pdf cannot be opened)" .
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + "133465.pdf";
Log.i("Fragmentadapter1", file);
File videoFile2Play = new File(file);
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(videoFile2Play), "application/pdf");
imageContext.startActivity(i);
I don't know if i am using the right file location to access the file.
Any help or suggestion will be appreciated.
If you are working for Lollopop and Below: You don't have to ask the user for permission on run-time. The manifest Permissions will do.
If you are working for Marshmellow and up: You have to ask the user for permission on run-time and act according to the users output.
Remember: You still have to give the Permissions on the Manifest too.
To Download a PDF on users Downloads folder :
DownloadManager downloadmanager;
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.mkdirs();
downloadmanager = (DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
String url = hardcode + bb ;
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri)
.setTitle(bb )
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
bb)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Log.i("Download1", String.valueOf(request));
downloadmanager.enqueue(request);
Reference
To View the Downloaded PDF from the Downloads folder of the Users device:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator +
"YOUR FILE NAME");
Uri path = Uri.fromFile(file);
Log.i("Fragment2", String.valueOf(path));
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
this.startActivity(pdfOpenintent);
} catch (ActivityNotFoundException e) {
}
Note: Make sure u get the permission granted before downloading the Viewing the PDF file for Marshmellow and UP.

Android, can't view file stored in external memory through intent

I have a function that downloads and extracts a zip file.
Its extracted to the external storage in: ../Android/data/packagename/..
When I try the following intent to view a .mp4 video for example, its opened in a video player and says that it can't open the file. (not only .mp4 files)
Uri uri = Uri.parse(Helper.getStorageDir(getActivity()) + "/" + mediaObject.getLinkOffline());
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(mediaObject.getLinkOffline().substring(mediaObject.getLinkOffline().lastIndexOf(".") + 1, mediaObject.getLinkOffline().length()));
newIntent.setDataAndType(uri, mimeType);
newIntent.setFlags(newIntent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(newIntent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No handler for this type of file.", 4000).show();
}
However, when I go through a file explorer and open the same file there is no problem.
I have there read/write permissions in my manifest. But thats obviously not the problem since I can read write the file and can also check the the file exists. It just wont let an external app open the file through an intent from my app.
Am I missing something?
EDIT: when I debug and check the mime type for the mp4 file it is "video/mp4".

get file path of sharedpreferences file

I am creating a sharedpreferences file in my android code. I then want to email that file in my code. For that I need to access the path of the sharedpreferences file. The code I am using is below. But it does not seem to work. I am able to open the email but there is no attachment there since I guess it could not get the file. Can someone suggest me any solution here.
File f = getDatabasePath("userPrefsFile.xml");
String filelocation=f.getAbsolutePath();
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("application/xml");
String[] to = {"test#test.com"};
email.putExtra(Intent.EXTRA_EMAIL, to);
email.putExtra(Intent.EXTRA_STREAM,filelocation);
email.putExtra(Intent.EXTRA_SUBJECT,"test file send");
startActivity(Intent.createChooser(email, "Send email"));
So SharedPreferences files are located at directory
/data/data/your.package/shared_prefs
So you need to use path above.
Pseudo-code:
File root = new File("/data/data/your.package/shared_prefs");
if (root.isDirectory()) {
for (File child: root.listFiles()) {
Toast.makeText(this, child.getPath(), Toast.LENGTH_SHORT).show();
}
}
Reason why you cannot use getDatabasePath() is that returns databases folder 1
/data/data/your.package/databases/
1 Same issue is also related to getFileStreamPath() method that returns
/data/data/your.package/files

Send data as Attachment to E-Mail without saving it on sd card

I am working on an application, where I am sending .vcf files to E-Mail as attachment thorugh my application,
I have used following code to achieve this,
try {
path = Environment.getExternalStorageDirectory().toString()+ File.separator +vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
mFileOutputStream.write(vCardString.toString().getBytes());
File filevcf = new File(path);
Log.d("file", "file" + filevcf);
} catch (Exception e4) {
Log.d("File", "File Error-->>" + e4);}
and I am using the following code to send this .vcf file to email using the default email application.
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
String to[] = "asd#gmail.com";
sharingIntent.putExtra(Intent.EXTRA_EMAIL, to);
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
startActivity(Intent.createChooser(sharingIntent, "Send email"));
In this case, I have to store the contact as .vcf file on the sd card and only then I am able to send it to email. in case, there is no sd card in the device, it throws excpetion.
I want the application to be able to send .vcf files even if there is no sd card in the device. Is there any way to do this, or if there is any way to store this .vcf file somewhere else and then send it.
You can use internal storage to store your .vcf file and can delete once the server response is OK.

Categories

Resources