I am trying to share an image to other apps.
From the doc, I understand I have to create a ContentProvider to ensure access to my resource from outside the app. It works with most apps but Facebook Messenger and Messages (com.android.mms). I have the following errors:
FB Messenger: "Sorry, messenger was unable to process the file"
com.android.mms: "Unable to attach. File not supported"
The code I call in the activity to share:
Uri path = Uri.parse("content://com.myauthority/test.png");
Intent shareIntent = new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, path).setType("image/png");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
The in my content provider I only override openFile:
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
String fileName = uri.getLastPathSegment();
String resName = fileName.replaceAll(".png","");
int resId = getContext().getResources().getIdentifier(resName,"drawable",getContext().getPackageName());
File file = new File(getContext().getCacheDir(), fileName);
Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), resId);
FileOutputStream fileoutputstream = new FileOutputStream(file);
boolean flag = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileoutputstream);
try {
ParcelFileDescriptor parcelfiledescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY | ParcelFileDescriptor.MODE_WORLD_READABLE);
return parcelfiledescriptor;
} catch (IOException e) {
e.printStackTrace();
return null;
}
Has anyone an idea or experience to share regarding this issue?
Here am Including my code which i used to share data from my app to facebook app or messenger app.
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
final File cachePath = new File(root.getAbsolutePath()
+ "/DCIM/Camera/Avi.jpg");
try {
cachePath.createNewFile();
FileOutputStream ostream = new FileOutputStream(
cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.flush();
ostream.close();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(
Intent.EXTRA_STREAM,
Uri.fromFile(new File(cachePath
.getAbsolutePath())));
Log.e("Path for sending ",
""+Uri.fromFile(new File(cachePath
.getAbsolutePath())));
mContext.startActivity(intent);
}
}, 3000);
just provide your image uri and use this code.
Related
I would like to share a screenshot after user clicking "share" button.
I am trying to apply this solution: https://stackoverflow.com/a/30212385/9748825
Here are the three methods:
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public void store(Bitmap bm, String fileName) {
final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
shareImage(file);
}
public void shareImage(File file) {
Uri uri = FileProvider.getUriForFile(iv_ScoreBoard.this, iv_ScoreBoard.this.getApplicationContext().getPackageName() + ".my.package.name.provider", file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(iv_ScoreBoard.this, "No App Available", Toast.LENGTH_SHORT).show();
}
}
gameDate method:
public void generateNewGameDate() {
Date thisSecond = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd , HH:mm");
gameDate = df.format(thisSecond);
}
Trigger Point:
public void onClick(View v) {
Bitmap b = getScreenShot(rootView);
store(b, gameDate);
}
Error:
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Screenshots/2018-10-28 , 17:40
Appreciate any of your help, thanks!
Well I was stuck in external storage permission.
After applying this answer, I got it now. Appreciate stackoverflow so much!
https://stackoverflow.com/a/37672627/9748825
I am trying to get a image of a view (constraint-layout) and share it via an android send-intent.
I tried a lot of methods, but until now none have worked.
This is what I have so far:
public void shareStatsImage(){
constraintLayout.setDrawingCacheEnabled(true);
Bitmap bitmap = constraintLayout.getDrawingCache();
File path = null;
try {
path = saveImageToExternal(generateImageTitle(), bitmap);
} catch (IOException e) {
e.printStackTrace();
}
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/png");
final File photoFile = new File(Objects.requireNonNull(getActivity()).getFilesDir(), Objects.requireNonNull(path).getAbsolutePath());
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
public static String generateImageTitle(){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
return sdf.format(new Date());
}
public File saveImageToExternal(String imgName, Bitmap bm) throws IOException {
//Create Path to save Image
String appFolder = "test";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + File.separator + appFolder); //Creates app specific folder
path.mkdirs();
File imageFile = new File(path, imgName+".png"); // Imagename.png
FileOutputStream out = new FileOutputStream(imageFile);
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(getContext(),new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
throw new IOException();
}
return imageFile;
}
There are multiple problems with this solution, for example I am getting an error message ("Permission denied for the attachment") when sharing the image to gmail. When uploading the image to google drive I only get an "upload unsuccessful message".
One good thing is that the images seem to appear in the phone's gallery, just not when sharing them via the intent :(
Thanks for your help!
Convert Bitmap to Uri
private Uri getImageUri(Context context, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Image Title", null);
return Uri.parse(path);
}
You can send Image using Uri.
Uri imageUri = set your image Uri;
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
I have this code that gets an image from database as Bitmap and then writes this to a file and sends it with e-mail. This code works great.
I am trying to write this to a textfile that actually shows the picture.
Is this possible?
Do I need to write this to pdf file if I want a file that shows the image?
Here's my code
public void createBild(long x, String pathToFile, String fileName) {
Product product = dbHandler.findProductbyId(x);
Bitmap pic = BitmapFactory.decodeByteArray(dbHandler.fetchSingle(x), 0,
dbHandler.fetchSingle(x).length);
// create a file to write bitmap data
Bitmap bitmap = pic;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
File f = new File(pathToFile + "/"+fileName+".bmp");
try {
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Uri path = Uri.fromFile(f);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/*");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "test#live.se" });
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT, "body of email");
i.putExtra(Intent.EXTRA_STREAM, path);
try {
startActivity(Intent.createChooser(i, "Share"));
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(VisaData.this,
"There are no email clients installed.", Toast.LENGTH_SHORT)
.show();
}
}
Why don't you send it as a .png itself.
intent.setType("image/png");
Below code will capture the screen and store it in SD card. I want Then it will send this file via sharable apps.I want to store it in internal memory of phone instead but I am unable to do that.Please help me for the same.
WebView view = (WebView) findViewById(R.id.webView1);
#SuppressWarnings("deprecation")
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap( picture.getWidth(),
picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas( b );
picture.draw( c );
String filePath = Environment.getExternalStorageDirectory()
+ File.separator + "score.png";
File imagePath = new File(filePath);
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
if(fos!=null)
{
b.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
if(imagePath.exists())
{
sendMail(filePath);
}
else
{
Log.e("fie","file doesnt exist");
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
public void sendMail(String path) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
//emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
// new String[] { "youremail#website.com" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"My Score in Mock Test");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"PFA");
emailIntent.setType("image/png");
Uri myUri = Uri.parse("file://" + path);
emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);
startActivity(Intent.createChooser(emailIntent, "share score card..."));
}
I tried to achieve this with below code found on stack overflow but it is not working. This code is not showing any exception when I debug through it but file is not creating to internal memory and so sending is failing.
I have an app in which there is an email section where I have to entered text and image in body. I searched on net but did not find corresponding solution. Any help will would be appreciated.
Here is the View :
BitmapFactory.Options bitmapFatoryOptions=new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;
Bitmap myBitmap=BitmapFactory.decodeResource(getResources(),R.drawable.face4,bitmapFatoryOptions);
File mFile = savebitmap(myBitmap);
Uri u = null;
u = Uri.fromFile(mFile);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("image/*");
Intent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Send Mail");
emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_texthere));
emailIntent.putExtra(Intent.EXTRA_STREAM, u);
startActivity(Intent.createChooser(emailIntent,"Send"));
Code for saveBitmap() Method:
private File savebitmap(Bitmap bmp) {
String temp="SplashItShare";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
String path = Environment.getExternalStorageDirectory()
.toString();
new File(path + "/SplashItTemp").mkdirs();
File file = new File(path+"/SplashItTemp", temp + ".png");
if (file.exists()) {
file.delete();
file = new File(path+"/SplashItTemp", temp + ".png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
Hope It will work for you.