Attach inputstream to email - android

I have an android apk expansion file and in there are some PDF's.
In the official documentation they access the files inside the .obb via Inputstream. I am able to access the files inside the .obb via the inputstream.
Now I want to attach one of the files to an email with Intent. The E-Mail Intent works perfectly fine with files from the assets, so the problem is attaching the Inputstream.
How can I attach the PDF into the mail directly from the .obb?

Solved it!
You have to convert the Inputstream to a Temorary File, get the Uri of that file and attach it to the email Intent.
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("application/pdf");
try {
ZipResourceFile expansionFile = new ZipResourceFile("Path to .obb file");
InputStream fileStream = expansionFile.getInputStream("Path inside .obb");
String downloadordner = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); //used for temp storage
File tempFile = new File(downloadordner+"/"+"filename.pdf");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(fileStream, out);
Uri theUri = Uri.fromFile(tempFile);
i.putExtra(Intent.EXTRA_STREAM, theUri);
startActivity(Intent.createChooser(i, "PDF versenden..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(preisliste.this, "Es wurde kein E-Mail Client gefunden.", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
Log.v("Datei nicht gefunden","Main Expansion");
}

Related

Share song on WhatsApp, always ends in "failed to send" message

I'm getting an input stream from a webservice and converting it to byte array so i can create a temporary file and play it using MediaPlayer (it is a .mp3). The problem is that i want to share the song on whatsapp, but i get the "failed to send" message whenever i try.
This is how i get and play the song:
if (response.body() != null) {
byte[] bytes = new byte[0];
try {
bytes = toByteArray(response.body().byteStream());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.reset();
try {
File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3);
fos.close();
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
}
catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
mediaPlayer.start();
This and a few similar ways is how i have tried to share it:
String sharePath = Environment.getExternalStorageDirectory().getPath()
+ "/tempfile.mp3";
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
The song is playing just fine and i have included the permission both for reading and writing in the external storage but i need help to share the song, be it as bytes or as file or as whatever works, please.
You will need to change from
File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir());
to
File tempMp3 = new File(Environment.getExternalStorageDirectory() + "/"+ getString(R.string.temp_file) + getString(R.string.dot_mp3)); //<- this is "tempfile" and ".mp3"
then you can share it like this
String sharePath = tempMp3.getAbsolutePath();
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, getString(R.string.share_song_file)));
The main problem was that where you were storing the file could NOT be shared with other apps, was only accessible from your own, since the getCacheDir() method is used to create cache files rather than storing data in files persistently, and is sort of private to the application (and createTempFile() generates random numbers at the end of the file's name, so you wouldn't be able to hard code the correct path like that).
Also, this solution makes use of the permissions you included (accessing external storage).

Can't read PDF downloaded from server

I'm downloading a PDF from my server.
The server send me a HttpResponse with the InputStream of file's body.
I'm able to write it into a file but, when I try to read it with a PDF reader, it tells me that the file might be corrupted.
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application.
The code I use to download and write the PDF file is this:
String fileName = //FILENAME + ".pdf";
fileName = fileName.replaceAll("/", "_");
String extPath = Environment.getExternalStorageDirectory().toString();
String folderName = //FOLDERNAME;
try {
File folder = new File(extPath, folderName);
folder.mkdir();
File pdfFile = new File(folder, fileName);
pdfFile.createNewFile();
URL url = new URL(downloadURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
byte[] buffer = new byte[MEGABYTE];
int bufferLength;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
//otherStuff
Where I go wrong?
I've also noticed that inside the Headers of HttpResponse contains Content-type:text/html. It shoudld be something like text/pdf?
Your Downloading code seems correct. Based on that and on your comment:
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application."
I would suggest checking your URL. It appears that you might be downloading an html page instead of the pdf. To verify you are downloading correctly, change the download directory as follows:
//Default download directory
String extPath = Environment.DIRECTORY_DOWNLOADS;
And check the directory (via the file system, e.g. mount the phone to your computer or a file manager app) for the downloaded content to verify it is a pdf.

Android assest folder image attachment to email failed

I'm trying to send a mail attaching assest folder image to the mail, mail is sent successfully, but when i checked it there was no image attached to the mail,
this is my code,
Uri uri = Uri.fromFile(new File("file:///android_asset/Hat_5.png"));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_EMAIL , new String[] { "some#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "New Order");
intent.putExtra(Intent.EXTRA_TEXT , "Order Id :" +imageId);
intent.putExtra(Intent.EXTRA_STREAM , uri);
startActivity(Intent.createChooser(intent, "Send mail..."));
permission,
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can only attach files from the SDCARD.
You'll need to copy the image to the SDCARD and change the URI the the file's path on the sdcard.
You could delete if afterwards.
You can do this if you want
String FILENAME = "avatar.png";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
Log.v("","FileNotFoundException: "+e1.getMessage());
}
try {
InputStream inputStream = getAssets().open("avatar.jpg");
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
fos.write(buf,0,len);
fos.close();
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
Log.v("","IOException: "+e1.getMessage());
}
// Get the file from internal storage
String filePath = getApplicationContext().getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, FILENAME);
then
Uri uri = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM , uri);
And send the attachment...

Android - Share file from sd using bluetooth

Im trying to send a file from my SD using Bluetooth. I'm using Share intent, I wanna send a file from my SD (.mp3). ok when I open the share menu, I can send file to email, dropbox, whatsapp, but if I select Bluetooth, My device shows a message "File null was not sent to ..."
My steps are:
1. Create SEND intent.
2. Copy my file from res/raw to SD
3. Add my file to putExtra
4. Delete the file (is temporal file)
The code:
Intent shareIntent=new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("audio/mp3");
//Copiamos archivo a compartir en la sd
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = sonidoActual+"-temp.mp3";
File newSoundFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024*500];
InputStream fis = getResources().openRawResource(contexto.getResources().getIdentifier(sonidoActual,"raw", contexto.getPackageName()));
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
////
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(newSoundFile.getAbsolutePath())/*Uri.parse("file:///sdcard/"+fileName)*//*Uri.parse("android.resource://com.genaut.instantbuttonsfreak/raw/"+texto)*/);
startActivity(Intent.createChooser(shareIntent,getString(R.string.share)));
//
newSoundFile.delete();
Anybody can help me with this? I read a lot but not found a working method, sorry my english.
I think your file is not release by File-I/O.
SO.. try flush() the FileOutPutStream.. like,
fos.flush();
fos.close();
then, use Uri.fromFile(File file) for uri to pass with Intent.. But before passing Uri to Intent just check whether file is exist or not..
like,
if(newSoundFile.exist())
{
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(newSoundFile))
startActivity(Intent.createChooser(shareIntent,getString(R.string.share)));
newSoundFile.delete();
}

I want my app to open pdf

my app downlods a pdf file from a link saving it to SD card, and it's working fine.. but what I'm struggeling at is I couldn't let my app views the pdf file..( although I've installed PDF viewer on my emulator)nothing happens after downloading the file...
here's my code for openning the pdf file
InputStream input = new BufferedInputStream(url.openStream());
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()
+ "/myapp/download");
dir.mkdirs();
File file = new File(dir, "application/pdf");
FileOutputStream output = new FileOutputStream(file);
Use below code to open pdf file.
File pdfFile = new File("/mnt/sdcard/path_to_file/yourpdf.pdf");
if(pdfFile.exists()) {
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch(ActivityNotFoundException e) {
Toast.makeText(yourActivityClass.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(yourActivityClass.this, "File not found", Toast.LENGTH_LONG).show();
}
yourActivityClass.this is application context make it correct while testing above code.

Categories

Resources