Everytime the image is captured the folder creation section works fine but the image is not added to the folder
photoButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode != RESULT_CANCELED)
{
folder = new File(Environment.getExternalStorageDirectory() + File.separator+"folder/");
if(!folder.exists())
{
folder.mkdirs();
Log.d("SDcard", "Folder created");
}
else
{
Log.d("SDCard", "Folder already exists");
}
File file = new File(Environment.getExternalStorageDirectory() + File.separator +"folder/");
Uri photoPath = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath); `
}
}
If I add the folder creation and save image logic to the onclick() directly it shows error stating "Failure delivering result info"
*Please do help *
public void saveBitmapToFile(Bitmap bmp) {
File mAppBaseDir;
if (isExternalStorageWritable())
mAppBaseDir = new File(Environment.getExternalStorageDirectory(), "FolderName");
else
mAppBaseDir = new File(getApplicationContext().getFilesDir().getParent()).getAbsoluteFile();
if (!mAppBaseDir.exists()) {
mAppBaseDir.mkdirs();
}
File imageDir = new File(mAppBaseDir, "Profile");
if (!imageDir.exists())
imageDir.mkdirs();
File file = new File(imageDir + "/" + "profile.png");
if (file.exists()) {
file.delete();
}
try {
writeBytesToFile(file, bitmapToByte(bmp));
} catch (IOException e) {
// show alert for retry choose photo
e.printStackTrace();
}
}
public void writeBytesToFile(File file, byte[] bytes) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
Log.e("", e.getMessage());
} finally {
if (bos != null) {
try {
bos.flush();
bos.close();
} catch (Exception e) {
Log.e("", e.getMessage());
}
}
}
}
public byte[] bitmapToByte(Bitmap bitmapFinally) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapFinally.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
I answer this question based on your comment "can you please elaborate". CMIIW :
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
folder = new File(Environment.getExternalStorageDirectory() + File.separator + "folder/");
if (!folder.exists())
{
folder.mkdirs();
Log.d("SDcard", "Folder created");
} else {
Log.d("SDCard", "Folder already exists");
}
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "folder/");
Uri photoPath = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
"Ive declared the cameraIntent object before oncreate() method" that's no problem about that, but onActivityResult will be triggered after you call startActivityForResult, then the intent wont have the extra you give
Related
I have tried everything but Image is not showing in Gallery, but its
saved in Internal Storage. I have tried several tutorials, but unable
to solve it .How can I implement it so that it is shown in Gallery
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(FullScreenActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//to get the image from the ImageView (say iv)
BitmapDrawable draw = (BitmapDrawable) fullscreenimage.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/IslamicStatusPics");
Log.e("DIR", String.valueOf(dir));
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
AlertDialog alertDialog = new AlertDialog.Builder(FullScreenActivity.this).create();
alertDialog.setTitle("Success");
alertDialog.setMessage("Image Saved to IslamicStatusPics Folder Successfully !");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/storage/emulated/0/IslamicStatusPics/"))));
// Toast.makeText(getApplicationContext(), "Image Saved to IslamicStatusPics Successfully !", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
// intent.setData(Uri.fromFile(dir));
// sendBroadcast(intent);
}else {
requestStoragePermission();
}
Please help me Guide in the Right Path. Thanks
You can try below code with saved file uri:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(outFile)); //change here
activity.sendBroadcast(mediaScanIntent);
} else {
activity.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
I want to capture image using camera and send it as attachment in Email.
I tried everything on Internet nothing is working for me. If anyone could help with code please.
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
File file = savebitmap(thumbnail);
sendMail(file);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "abcd" + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "abcd" + ".jpg");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
void sendMail(File mFile){
Uri uri = null;
uri = Uri.fromFile(mFile);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"abc#gmail.com"});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "body");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share!"));
}
}
Saving the bitmap:
{
.....
File file = savebitmap(thumbnail);
sendMail(file);
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalFilesDir().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, temp + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, temp + ".jpg");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
//and then
void sendMail(File mFile){
Uri uri = null;
uri = Uri.fromFile(mFile);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {""});
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, EMAIL_SUBJECT);
intent.putExtra(android.content.Intent.EXTRA_TEXT, EMAIL_BODY);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share!"));
}
Here is an example from internet
https://androidexample.com/Camera_Photo_Capture_And_Show_Captured_Photo_On_Activity_/index.php?view=article_discription&aid=77&aaid=101
I am assuming you may not handle permission just like above link
when you run your app in 6.0 above like marshmallow device then need permission other wise no need to permission. that time your code work..
if run marshmallow device that time need permission then make below code ..
private void alertDialog(){
CharSequence menu[] = new CharSequence[]{"Take From Galery", "Open Camera"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Toast.makeText(getApplicationContext(), "galery", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
});
builder.show();
}
then above method put in permission code like below ..
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
add two permission into manifest file ..
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
your error main problem is permission if you add this below line is work.
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
I basically want to hide the imagesthe user clicks in my app from the user in the gallery, display them in a small imageview and send it to the server. I am doing it the below way. However Bitmap Factory decode gives me a null bitmap I dont know why. Any help would be appreciated.
For creating file to save image to and opening camera intent;
public void openCamera(View view) {
PermissionsClass.checkPermissions(DIalogActivity.this, AppConfig.REQ_WRITE_ACCESS);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(DIalogActivity.this.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
//resizeFile(mCurrentPhotoPath);
photoURI = FileProvider.getUriForFile(DIalogActivity.this,
"com.example.sandithaa.nfcreader.fileprovider",
photoFile);
Log.i("photouri", String.valueOf(photoURI));
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
startActivityForResult(intent, 1);
} else {
Toast.makeText(this, "Camera cannot be opened.", Toast.LENGTH_SHORT).show();
}
}
}
For creating the file:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoPath = image.getAbsolutePath();
Log.i("filepathin createbefore", mCurrentPhotoPath);
return image;
}
For uploading to the server :
private void uploadFile() {
final String path;
Log.i("uplaod pdf", "pdf");
Random r = new Random();
int randomNo = r.nextInt(100000000 + 1);
String name = "IMG" + randomNo;
//getting the actual path of the image
// path = FilePath.getPath(this, photoURI);
// Log.i("path is",path);
Log.i("current parh", mCurrentPhotoPath);
try {
final String uploadId = UUID.randomUUID().toString();
Log.i("in uplaod 1", String.valueOf(priority.getSelectedItem()));
Log.i("proti", incidentEt.getText().toString());
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, "http://technobyteinfo.in/filter-coffee/uploadAll.php")
.addFileToUpload(mCurrentPhotoPath, "pdf") //Adding file
.addParameter("name", name)
.addParameter("description", incidentEt.getText().toString().trim())
.addParameter("priority" +
"", priority.getSelectedItem().toString())
.addParameter("time", time)
.addParameter("longitude", MySharedPreferences.retrievePreferences("longitude", getApplicationContext(), "00.00"))
.addParameter("latitude", MySharedPreferences.retrievePreferences("latitude", getApplicationContext(), "00.00"))
.addParameter("deviceid", GetDeviceId.getMyAndroidDeviceId(getApplicationContext()))
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.setDelegate(new UploadStatusDelegate() {
#Override
public void onProgress(Context context, UploadInfo uploadInfo) {
}
#Override
public void onError(Context context, UploadInfo uploadInfo, Exception exception) {
Toast.makeText(context, "File could not be uploaded.", Toast.LENGTH_SHORT).show();
Log.i("exceptipn", exception.getMessage());
}
#Override
public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) {
Log.i("error is", serverResponse.getBodyAsString());
JSONObject jObj = null;
try {
jObj = new JSONObject(serverResponse.getBodyAsString());
boolean error = jObj.getBoolean("error");
if (error == false) {
Toast.makeText(context, "Details saved successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "File could not be uploaded.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(Context context, UploadInfo uploadInfo) {
}
})
.startUpload(); //Starting the upload
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Trying to compress the images this way:
public void compressImage() {
try {
OutputStream outStream = null;
Log.i("imagefiename",imageFileName);
outStream = new FileOutputStream(mCurrentPhotoPath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(imageFileName ,bmOptions);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, outStream);
outStream.flush();
outStream.close();
Log.i("file path compress", mCurrentPhotoPath);
} catch (Exception e) {
Log.i("exception", e.toString());
}
}
My onActivityResult after camera intent comes back:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
compressImage();
Picasso.get().load(photoURI).resize(300,300).into(imageView);
}
I want capture video from camera Intent and save in app directory (don't save video in Device Gallery) and insert video path into database to load and display in my app
i try in my activity :
public class VideoActivity extends Activity {
private TblVideo TBL_VIDEO;
private Uri fileUri;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
long date = System.currentTimeMillis();
String string_path = DATABASE_LOCATION + LAST_MOMENT_ID + "_" + date + ".mp4";
File mediaFile = new File(string_path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
Button buttonRecording = (Button) findViewById(R.id.photo_btn_take_video);
buttonRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
ContentValues values = new ContentValues();
fileUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
fileUri = Uri.fromFile(mediaFile);
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
getContentResolver().delete(fileUri, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private String SaveMediaFile(int type) {
if (type == MEDIA_TYPE_VIDEO) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mediaFile);
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو:" + "\n" + e.toString());
} finally {
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return string_path;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
try {
if (resultCode == RESULT_OK) {
insertVideo();
} else if (resultCode == RESULT_CANCELED) {
displayToast(this, "ضبط لغو شد");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
but when go to file directory , video size is 0Kb !! and save into device gallery
How to fix this problem ?
thanks
and try this but app is crash :
buttonRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
ContentValues values = new ContentValues();
fileUri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
fileUri = data.getData();
FileOutputStream fileOutputStream = null;
try {
FileInputStream fileInputStream = new FileInputStream(fileUri.getPath());
fileOutputStream = new FileOutputStream(mediaFile);
byte[] buf = new byte[1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
fileOutputStream.write(buf, 0, len);
}
fileInputStream.close();
fileOutputStream.close();
insertVideo();
getContentResolver().delete(fileUri, null, null);
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو:" + "\n" + e.toString());
} finally {
try {
assert fileOutputStream != null;
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == RESULT_CANCELED) {
displayToast(this, "ضبط لغو شد");
}
}
}
i use this and save video file after activity result is OK, save video in directory !
private String SaveMediaFile() {
try {
InputStream in = getContentResolver().openInputStream(fileUri); // Uri
OutputStream out = new FileOutputStream(mediaFile); // file
byte[] buf = new byte[1024];
int len;
assert in != null;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
displayToast(this, "خطای ذخیره ویدیو");
}
return string_path;
}
thanks
I am using this code to share an image:
File file = ImageLoader.getInstance().getDiskCache().get(imageUrl);
if (file != null && file.exists()) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(Intent.createChooser(intent, "Send"));
} else {
Toast.makeText(context, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
I used UIL to load the image previously, so mageLoader.getInstance().getDiskCache().get(imageUrl); returns the image file from disk cache.
Gmail, Hangouts, Messages, Drive etc can grab the file but on Google+, the grabbed is not gotten while Whatsapp says "This format is not supported". However if I save the file to Downloads folder and share via Gallery app, the same image is picked by both Google+ and Whatsapp.
You can try to save the file to the external cache, it's working for me. Example with Glide:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("image/*");
Glide.with(getContext())
.load("http://...url.here...")
.asBitmap()
.into(new SimpleTarget<Bitmap>(500, 500) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
try {
File file = new File(getContext().getExternalCacheDir(), "file_to_share.png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
resource.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().startActivity(Intent.createChooser(sendIntent, ""));
} catch (IOException e) {
Log.e("Share", e.getMessage(), e);
} finally {
}
}
});
In case you're using Universal Image Loader, I applied the accepted answer to save the image and delete it as soon as the user returns from sharing:
private File saveImage(String imageUri, String fileName) {
File file = new File(this.getExternalCacheDir(), fileName);
InputStream sourceStream = null;
File cachedImage = ImageLoader.getInstance().getDiskCache().get(imageUri);
if (cachedImage != null && cachedImage.exists()) {
Log.d(TAG, "Cache exists");
try {
sourceStream = new FileInputStream(cachedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Cache doesn't exist");
}
if (sourceStream != null) {
Log.d(TAG, "SourceStream is not null");
try {
OutputStream targetStram = new FileOutputStream(file);
try {
try {
IoUtils.copyStream(sourceStream, targetStram, null);
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
targetStram.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
sourceStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.d(TAG, "SourceStream is null");
Toast.makeText(this, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
return file;
}
private void shareImage(String imageUrl, String fileName) {
if (isSDReadableWritable()) {
file = saveImage(imageUrl, fileName);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(Intent.createChooser(intent, "Send"), 20);
} else {
Toast.makeText(this, "Storage cannot be accessed", Toast.LENGTH_SHORT).show();
}
}
To delete the file just override onActivityResult and it'll be deleted immediately after sharing
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 20 && file != null) {
boolean isDelete = file.delete();
Log.d(TAG, "isDelete is " + isDelete);
}
}