I have a function that I want to automatically take a screenshot and then upload it to the users preferred email app.
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(Environment.getExternalStorageDirectory().getAbsolutePath() + now + mPath);
Uri path = Uri.fromFile(filelocation);
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, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Journey : ");
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 function. It is taking the screen shot automatically and its store it on my local device. It is also prompting the user to select their email app. Then I select an app it says "unable to attach file" . I have read and write permissions in my manifest.
The other app may not have access to external storage. Plus, your code will crash on Android 7.0+, once you raise your targetSdkVersion to 24 or higher.
Switch to using FileProvider and its getUriForFile() method, instead of using Uri.fromFile().
And, eventually, move that disk I/O to a background thread.
check this link -
https://www.javacodegeeks.com/2013/10/send-email-with-attachment-in-android.html
and How to send an email with a file attachment in Android
Hope this help.
The problem was :
Uri path = Uri.fromFile(filelocation);
Instead I used :
File filelocation = new File(MediaStore.Images.Media.DATA + mPath);
Uri myUri = Uri.parse("file://" + filelocation);
Hopefully this helps anyone facing the same problem.
Related
I have tried about 10 answers to a similar question, but none of them were successful. Something might be out of date. Please give an answer for today.
Simple task:
I want my app to be able to send a file with an image to e-mail or whatsapp.
I put the file with the image in the application resources in the folder Drawable.
Its size is 5 MB.
How to do this in Java?
I'm asking for code, not links to similar answers. I've tried most of them already.
Some decisions came to null.bin.
Some don't send anything at all and throw an error.
Perhaps I am not specifying any permissions.
Something else is possible.
I'm new.
I would like an answer with comments (what I am writing and why)
// step 1. I put the picture in the folder Drawable
// clicking on the button sends the picture through the messenger to other users
public void onClick_sendMyImage(View v) {
// Step 2.Convert PICTURE to Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
saveImage(bitmap); // 3. save the PICTURE in the internal folder
send(); // 4.sending PICTURE (function code below)
}
// step 3. Saving the image in the internal folder:
private static void saveImage(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
//Log.i("Directory", "==" + myDir);
myDir.mkdirs();
String fname = "image_test" + ".jpg";
File file = new File(myDir, fname);
if(file.exists()) file.delete();
try{
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Step 4. Sending the saved PICTURE
public void send(){
try{
File myFile = new File("/storage/emulated/0/saved_images/image_test.jpg");
// for something I create this type (so it is said in one of the answers)
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(type);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(myFile));
Intent intent1 = Intent.createChooser(intent, "what do you want to send ?");
startActivity(intent1);
}catch (Exception e){
Toast.makeText(this, "repeat sending", Toast.LENGTH_SHORT).show();
}
}
Sending an image from an app turned out to be not a good idea.
The image cannot be edited if necessary.
Over time, you may want to add more images, etc..
I did it differently, and it turned out better:
I put the image on GoogleDisk.(now I can change it at any time without having
to ask users to reinstall the application every time the picture changes).
I placed a link to the picture in the FireBase Database. (I also placed a banner with a picture here.).
I connected the application to the Firebase Database.
In the activity I made a RecyclingView, where I get a banner(s) and a link(s) to the original image(s). The user can download this link or send it through whatsapp anywhere and download the original picture in good quality (A1, 2.5Mb).
thanks, guys..
I thank the guys for the tips, especially mr.Blackapps. In this case, you really can't do without a FileProvider.
Generally a video is chosen from the gallery and cut with a library, the problem is that I need to convert that cut video (that it is stored in the external memory: /storage/emulated/0/test_video.mp4) to base64 and that's where it fails. How can I solve it?
I already put the permissions on the manifest and request for them programmatically.
//Getting video from previous activity
Uri selectedVideo = Uri.parse(intent.getStringExtra("trimmedVideo"));
Log.d(Global.getTag(), "path: "+selectedVideo.toString());
//Converting Selected video to base64
try {
InputStream in = getContentResolver().openInputStream(selectedVideo); <---This line fails
byte[] bytes = Global.getBytes(in);
Log.d(Global.getTag(), "bytes size= "+bytes.length);
video_base64 = Base64.encodeToString(bytes,Base64.DEFAULT);
Log.d(Global.getTag(), "Base64string= "+ video_base64);
} catch (Exception e) {
e.printStackTrace();
}
And all I get in logcast is:
I found the solution on a github post! Just need to include this:
//Getting video from previous activity
Uri selectedVideo = Uri.parse(intent.getStringExtra("trimmedVideo"));
Uri selectedVideoFinal = null;
if (selectedVideo.getScheme() == null){
selectedVideoFinal = Uri.fromFile(new File(selectedVideo.getPath()));
}else{
selectedVideoFinal = selectedVideo;
}
Log.d(Global.getTag(), "path: "+selectedVideoFinal);
MediaMetadataRetriever mMMR = new MediaMetadataRetriever(); ...continue code
//Save PDF file
//Create time stamp
Date date = new Date() ;
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss").format(date);
String filePath = Environment.getExternalStorageDirectory() +"/"+ "Allotment" +timeStamp+ ".pdf";
File myFile = new File(filePath);
try {
OutputStream output = new FileOutputStream(myFile);
pdfDocument.writeTo(output);
output.flush();
output.close();
Toast.makeText(AllotmentDoc.this, "PDF Created Succesfully", Toast.LENGTH_LONG).show();
Toast.makeText(AllotmentDoc.this, "PDF Saved On Memory", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
I want to save my pdf file that's why I wrote some line of code. But it works on some device and doesnt work on some other device. What is the problem. how can i solve it.
I think you are facing this problem in some deviece because of
Environment.getExternalStorageDirectory()
You can use
Environment.getExternalStorageDirectory().getAbsolutePath();
Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. Galaxy Tab 2, Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time.
I wanted to do an app for sharing pictures from the gallery for learning and i want the picture to be renamed so i use a bitmap that retrieve the data of the picture. But the thing is the file is always returning null.
I have a code and i don't know where is the problem.
File file = new File(this.getFilesDir().getAbsolutePath(), "logo");
if (!file.exists()) {
file.mkdirs();
}
File iconf = new File(file, "icon_launcher.png");
iconf.createNewFile();
OutputStream ios = new FileOutputStream(iconf);
example.compress(Bitmap.CompressFormat.PNG, 80, ios);
ios.flush();
ios.close();
//String uricon= MediaStore.Images.Media.insertImage(getContentResolver(),iconf.getAbsolutePath(),"icon_launcher.png","drawing");
Uri iconurl = Uri.parse(iconf.getAbsolutePath());
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("image/png");
email.putExtra(Intent.EXTRA_STREAM, iconurl);
startActivityForResult(Intent.createChooser(email, "Envoyer par mail"), 1);
Thank you in advance for the help :)
I have succeeded to make the code work, i forget to use a FileProvider because i didn't have an External Storage.So you have to use a FileProvider to use Internal Storage.
Helo guys,
I am using following Code.
String fileName = "image" + "_" + title.getText().toString()+"_" + val.toString();
photo = this.createFile(fileName, ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
uriOfPhoto = Uri.fromFile(photo);
startActivityForResult(intent, RESULT_CAMERA_SELECT);
}
}
catch(Exception e)
{
Log.v("Error", "Can't create file to take picture!");
displayAlert("Can't create file to take picture!","SDCard Error!");
}
}
private File createFile(String part, String ext) throws Exception
{
File tempDir = new File (Environment.getExternalStorageDirectory() + "/MyFolder/Images");
if(!tempDir.exists())
{
tempDir.mkdir();
}
tempDir.canWrite();
return new File(tempDir, part+ext);
}
});
The UriOfPhoto is giving me uriString not chached in debug. It is not storing uri of the file.How can i resolve this issue.
authority Uri$Part$EmptyPart (id=830004244032)
fragment Uri$Part$EmptyPart (id=830004245408)
host "NOT CACHED" (id=830003914304)
path Uri$PathPart (id=830067926736)
port -2
query Uri$Part$EmptyPart (id=830004245408)
scheme "file" (id=830002660688)
ssp null
uriString "NOT CACHED" (id=830003914304)
userInfo null
Best Regards
This isn't enough info. What action are you putting into the intent you send? Are you sure that createFile actually creates a file?
The error listing you give isn't very useful. Is it part of the listing of variable values from debug? If so, where are you in the code when you look at the values?
String fileName = Environment.getExternalStorageDirectory() + "/MyFolder/Images" + fileName + ".jpg";
UriOfPhoto = Uri.parse(fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra(MediaStore.EXTRA_OUTPUT, UriOfPhoto);
startActivityForResult(intent, RESULT_CAMERA_SELECT);
also the is no need of creating file for store photo you need to just pass the uri where the photo must be as above the Android OS create a file as you were trying to do and stores the captured image in that uri.