I am using this code for sharing text + message in android. This method works fine for g+ or email, but dont work for Facebook. It says cant load file.
public void Share(string title, string content)
{
if (ActivityContext.Current == null || Application.Context == null)
return;
if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(content))
return;
Bitmap bitmapToShare = BitmapFactory.DecodeResource(Application.Context.Resources, Resource.Drawable.icon_120);
File pictureStorage = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
File noMedia = new File(pictureStorage, ".nomedia");
if (!noMedia.Exists())
noMedia.Mkdirs();
string imageName = "shared_image" + DateTime.Now.ToBinary() + ".png";
File file = new File(noMedia, imageName);
Stream output = Application.Context.OpenFileOutput(imageName,FileCreationMode.WorldReadable);
bitmapToShare.Compress(Bitmap.CompressFormat.Png, 100, output);
output.Flush();
output.Close();
// var name = Application.Context.Resources.GetResourceName(Resource.Drawable.icon_120).Replace(':', '/');
// var imageUri = Uri.Parse("android.resource://" + name);
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.SetType("text/plain");
sharingIntent.SetType("image/png");
sharingIntent.PutExtra(Intent.ExtraTitle, title);
sharingIntent.PutExtra(Intent.ExtraText, content);
// sharingIntent.PutExtra(Intent.ExtraStream, imageUri);
sharingIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(file));
sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
ActivityContext.Current.StartActivity(Intent.CreateChooser(sharingIntent, title));
AnalyticsService.Instance.LogEvent("Share button clicked.");
}
Tried this post.
Am i doing something wrong?
Related
For my company i am trying to send email from my android app using email intent.
I'm using emulator to test my app. But the problem is when i'm trying to Add and Attachment (eg. pdf, image) it won't attaching yet.
here is my code:
private String SendEmail(String oid, final String img, final String party_code, final String order_by, final Bitmap attachimg, final String note) {
try {
String filename="DOAttachment.jpeg";
String subject ="Order "+oid+" has been sent successfully";
String body="\nDear Sir, \n"+"Please find the attached file herewith.\nThe D.O for the customer(party) "+party_code+" has been successfully done with the order number: "+oid+"\n\n\n"+"With regards \n \n Employee code/ID: "+order_by+"\n\nN.B:"+note;
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "DirName/"+filename;
File file = new File(root, pathToMyAttachedFile);
file.setReadable(true,false);
Log.e("File path"," "+file);
//using outlook
Intent intent = new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|FLAG_ACTIVITY_SINGLE_TOP);
intent.setType("image/*");
Uri data = Uri.parse("mailto:?subject=" + subject + "&body=" + body+ "&stream="+Uri.parse("file:///"+Environment.getExternalStorageDirectory().getAbsolutePath())+"/DirName/"+filename);
intent.setData(data);
intent .putExtra(Intent.EXTRA_EMAIL, toemail);
if (!file.exists() || !file.canRead()||!file.canWrite()) {
Log.e(" FILE ERROR ","File Not found");
Toast.makeText(getApplicationContext(),"File Not found",Toast.LENGTH_LONG).show();
}
else {
file.setReadable(true);
Log.e(" FILE OK ","File was found");
Uri uri = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
return "TRUE";
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
return "MAIL NOT SENT";
}
}
The result is email with empty attachment find screenshot : https://1drv.ms/i/s!AruisQQIx8MTgatuhJFmSaoArg_6Xw
Check whether you had provided READ_EXTERNAL_STORAGE permission for your application both in manifest and run-time.
Then Call the below method send mail assuming the full file path is saved in filePath.
File root = Environment.getExternalStorageDirectory();
String pathToMyAttachedFile = "DirName/"+filename;
File filePath = new File(root, pathToMyAttachedFile)
sendEmailAlert(filePath,subject,text);
CALLED METHOD
private void sendEmailAlert(File fileName,String subject,String text) {
final File file=fileName;
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream"); /* or use intent.setType("message/rfc822); */
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
if (!file.exists() || !file.canRead()) {
Toast.makeText(getContext(), "Attachment Error", Toast.LENGTH_SHORT).show();
return;
}
Uri uri = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Send email..."));
}
i want working on sharing .gif with available apps like whatsapp, but unable to get valid Uri of gif present in my drawable resource.
Uri path = Uri.parse("android.resource://my_package_name/" + R.drawable.gif_1);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
shareIntent.putExtra(Intent.EXTRA_STREAM, path);
there is lot of solution on sharing images but no solution on gif sharing, Please help
I found my answer, I just created a file with a .gif extension and it worked for me. See the code below:
private void shareGif(String resourceName){
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "sharingGif.gif";
File sharingGifFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024*500];
InputStream fis = getResources().openRawResource(getResources().getIdentifier(resourceName, "drawable", getPackageName()));
FileOutputStream fos = new FileOutputStream(sharingGifFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
Uri uri = Uri.fromFile(sharingGifFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Emoji"));
}
if you want to take image from internal storage.
//this is method having internal storage path.
private String getFilePath2() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Gifs temp/");
if (!myDir.exists())
myDir.mkdirs();
String fname = "temp_gif";
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyyMMdd_HHmmss");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);
File file = new File(myDir, fname + "_" + filename + ".gif");
if (file.exists()) {
file.delete();
}
String str = file.getAbsolutePath();
return str;
}
// Then take image from internal storage into the string.
String st = getFilePath2();
//And share this by this intent
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
Uri uri = Uri.fromFile(sharingGifFile);
shareIntent.putExtra(Intent.EXTRA_STREAM,
uri);
startActivity(Intent.createChooser(shareIntent, "Share Emoji"));
I have a pic inside my app in raw folder. I want to give option to users to set that image as an wallpaper or profile picture. A dialog should popup when the option is selected. Like this:
I tried showing this dialog with the following code
int resId = R.raw.a_day_without_thinking_mobile;
Resources resources = this.getResources();
Uri sendUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(resId) + '/' + resources.getResourceTypeName(resId) + '/' + resources.getResourceEntryName(resId));
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(sendUri, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Set As"));
But this showed me a dialog like this:
I don't want to set image directly as wallpaper instead a dialog should be shown from where user can select whether he/she wants to use the image as wallpaper or profile picture.
First you must download image file from raw folder to sd card and then use the sd card file to set the image as wallpaper
int resId = R.raw.a_day_without_thinking_mobile;
String filename = getResources().getResourceEntryName(resId );
String destfolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/Motivational Quotes";
createDirIfNotExists(destfolder);
String destinationPath = destfolder +"/"+ filename + ".jpg";
File destination = new File(destinationPath);
InputStream ins = getResources().openRawResource(
getResources().getIdentifier(filename,
"raw", getPackageName()));
try {
copy2(ins,destination);
//Toast.makeText(this, "Image Downloaded", Toast.LENGTH_SHORT).show();
File externalFile=new File(destinationPath);
Uri sendUri2 = Uri.fromFile(externalFile);
Log.d("URI:", sendUri2.toString());
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(sendUri2, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
startActivityForResult(Intent.createChooser(intent, "Set As"), 200);
} catch (IOException e) {
e.printStackTrace();
}
public void copy2(InputStream src, File dst) throws IOException {
InputStream in = src;
OutputStream out = new FileOutputStream(dst);
//InputStream in = new FileInputStream(src);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
addImageGallery(dst);
}
private void addImageGallery( File file ) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // setar isso
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Here is the code that you can use
Remove the put extra from your intent and use the following for data and type
intent.setDataAndType(sendUri, "image/*");
My app takes photos and I want to share it on Instagram.
My app save the image in this directory
File storagePath = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/tubagram");
Now I'm trying to get the last picture I took to share in Instagram using this code
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/*");
final ContentResolver cr = getContentResolver();
final String[] p1 = new String[] {MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATE_TAKEN};
Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");
if (c1.moveToFirst() ) {
Log.i("Test", "last picture (" + c1.getString(0) + ") taken on: " + new Date(c1.getLong(1)));
}
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+Environment.getExternalStorageDirectory() + "/DCIM/Camera/tubagram/" + c1.getString(0)));
shareIntent.setPackage("com.instagram.android");
c1.close();
startActivity(shareIntent);
I receive a Toast with this error message "Unable to download file".
This Toast is sent by Instagram.
I tried to use this link example - share a photo in instagram - but didn't work.
I solved my problem.
I add this line after the camera.takePicture.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
This line does a "refresh" and after the phone recognizes the news photos saved on your phone.
And I made some changes on my method
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/*");
final ContentResolver cr = getContentResolver();
final String[] p1 = new String[] {
MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.TITLE, MediaStore.Images.ImageColumns.DATE_TAKEN
};
Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");
if (c1.moveToFirst() ) {
Log.i("Test", "last picture (" + c1.getString(1) + ") taken on: " + new Date(c1.getLong(2)));
}
Log.i("Image path", "file://"+Environment.getExternalStorageDirectory()+ "/Tubagram/" + c1.getString(1) + ".png");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+Environment.getExternalStorageDirectory()+ "/Tubagram/" + c1.getString(1)+".png"));
shareIntent.setPackage("com.instagram.android");
c1.close();
startActivity(shareIntent);
And with this another method I verify if the Instagram is installed on the phone
private boolean verifyInstagram(){
boolean installed = false;
try {
ApplicationInfo info = getPackageManager().getApplicationInfo("com.instagram.android", 0);
installed = true;
} catch (NameNotFoundException e) {
installed = false;
}
return installed;
}
put this code in your button click listener it will redirect you into app and make sure your device have installed Instagram app.
String type = "image/*";
imageview.buildDrawingCache();
Bitmap bmap = imageview.getDrawingCache();
Uri bmpUri = getLocalBitmapUri(bmap);
Intent share = new Intent(Intent.ACTION_SEND);
if (Utils.isPackageExisted(this,"com.instagram.android")) {
share.setPackage("com.instagram.android");
}
share.setType(type);
share.putExtra(Intent.EXTRA_STREAM, bmpUri);
startActivity(Intent.createChooser(share, "Share to"));
Try the following code:
File mFileImagePath = " /storage/emulated/0/Image Editor/Media/FilterImages/Image_Editor_1547816365839.jpg "; // Just example you use file URL
private boolean checkAppInstall(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
//Error
}
return false;
}
private void shareInstagram(File mFileImagePath) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if (intent != null) {
Intent mIntentShare = new Intent(Intent.ACTION_SEND);
String mStrExtension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(mFileImagePath).toString());
String mStrMimeType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(mStrExtension);
if (mStrExtension.equalsIgnoreCase("") || mStrMimeType == null) {
// if there is no extension or there is no definite mimetype, still try to open the file
mIntentShare.setType("text*//*");
} else {
mIntentShare.setType(mStrMimeType);
}
mIntentShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFileImagePath));
mIntentShare.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mIntentShare.setPackage("com.instagram.android");
startActivity(mIntentShare);
} else {
Toast.makeText(mContext, "Instagram have not been installed.", Toast.LENGTH_SHORT).show();
}
}
This code works for me and will work on all Android devices.
How to attach multiple files in email in android?
Is there any permission required for multiple files attachment to an intent?
I am trying with putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList uriList) method but still in doubt whether Uri class is <? extends Parcelable> or not. I am not able to attach any file to email.
This is my code ::
Intent sendIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
sendIntent.setType("plain/text");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"soubhabpathak2010#gmail.com"});
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Accident Capture");
sendIntent.putExtra(Intent.EXTRA_TEXT, emailBody);
ArrayList<Uri> uriList = getUriListForImages();
sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList);
Log.d(TAG, "Size of the ArrayList :: " +uriList.size());
FormHolderActivity.this.startActivity(Intent.createChooser(sendIntent, "Email:"));
and getUriListForImages() this method is defined as bellow -----
private ArrayList<Uri> getUriListForImages() {
ArrayList<Uri> uriList = new ArrayList<Uri>();
String imageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/accident/";
File imageDirectory = new File(imageDirectoryPath);
String[] fileList = imageDirectory.list();
if(fileList.length != 0) {
for(int i=0; i<fileList.length; i++)
{
String file = "file://" + imageDirectoryPath + fileList[i];
Log.d(TAG, "File name for Uri :: " + file);
Uri uriFile = Uri.parse(file);
uriList.add(uriFile);
Log.d(TAG, "Image File for Uri :: " +(file));
}
}
return uriList;
}
To, subject and body of the email is coming and I have images in the accident folder in sdcard (I am using 2.1 API level 7) but nothing is attaching even there is also no exception in logcat.Arraylist is also ok(means length OK and name of the files are ok too). Can anyone help me to solve this problem?
After 1 day work finally I am able to attach multiple image files from \sdcard\accident\ folder to email client. For attaching multiple files I had to add the images to the ContentResolver which is responsible for gallery images provider.
Here is the Complete Code ---
Intent sendIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
sendIntent.setType("plain/text");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"soubhabpathak2010#gmail.com"});
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Accident Capture");
sendIntent.putExtra(Intent.EXTRA_TEXT, emailBody);
ArrayList<Uri> uriList = getUriListForImages();
sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList);
Log.d(TAG, "Size of the ArrayList :: " +uriList.size());
FormHolderActivity.this.startActivity(Intent.createChooser(sendIntent, "Email:"));
So there is no change in the First Section of Code -- But Change is in getUriListForImages() method which is as follows---
private ArrayList<Uri> getUriListForImages() throws Exception {
ArrayList<Uri> myList = new ArrayList<Uri>();
String imageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/accident/";
File imageDirectory = new File(imageDirectoryPath);
String[] fileList = imageDirectory.list();
if(fileList.length != 0) {
for(int i=0; i<fileList.length; i++)
{
try
{
ContentValues values = new ContentValues(7);
values.put(Images.Media.TITLE, fileList[i]);
values.put(Images.Media.DISPLAY_NAME, fileList[i]);
values.put(Images.Media.DATE_TAKEN, new Date().getTime());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.ImageColumns.BUCKET_ID, imageDirectoryPath.hashCode());
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, fileList[i]);
values.put("_data", imageDirectoryPath + fileList[i]);
ContentResolver contentResolver = getApplicationContext().getContentResolver();
Uri uri = contentResolver.insert(Images.Media.EXTERNAL_CONTENT_URI, values);
myList.add(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return myList;
}
This is working fine and I am able to attach multiple image files to emulator default email client and send them successfully .
EXTRA_STREAM says this:
A content: URI holding a stream of data associated with the Intent, used with
ACTION_SEND to supply the data being sent.
Constant Value: "android.intent.extra.STREAM"
You can not pass a set of file URIs: it will simply ignore the results (as you are observing).
EDIT: scratch that. I was wrong. This is the chunk of code in the standard Android Email client that handles multiple files.
if (Intent.ACTION_SEND_MULTIPLE.equals(mAction)
&& intent.hasExtra(Intent.EXTRA_STREAM)) {
ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (list != null) {
for (Parcelable parcelable : list) {
Uri uri = (Uri) parcelable;
if (uri != null) {
Attachment attachment = loadAttachmentInfo(uri);
if (MimeUtility.mimeTypeMatches(attachment.mMimeType,
Email.ACCEPTABLE_ATTACHMENT_SEND_INTENT_TYPES)) {
addAttachment(attachment);
}
}
}
}
}
Try doing this:
private ArrayList<Parcelable> getUriListForImages() {
ArrayList<Parcelable> uriList = new ArrayList<Parcelable>();
String imageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/accident/";
File imageDirectory = new File(imageDirectoryPath);
String[] fileList = imageDirectory.list();
if(fileList.length != 0) {
for(int i=0; i<fileList.length; i++)
{
String file = "file://" + imageDirectoryPath + fileList[i];
Log.d(TAG, "File name for Uri :: " + file);
Uri uriFile = Uri.parse(file);
uriList.add(uriFile);
Log.d(TAG, "Image File for Uri :: " +(file));
}
}
return uriList;
}