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

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).

Related

Attach inputstream to email

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");
}

Android - Display PDF from server

Trying to display a PDF received from server but getting "Media not found error"
First I convert String to byte array:
byte[] data = Base64.decode(stringData, Base64.DEFAULT);
Then I write the byte[] to a file:
String path = getFilesDir() + "/myfile.pdf";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
stream.write(article.getFileDataBytes());
stream.close();
Then I try to display PDF:
Uri path2 = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path2, "application/pdf");
startActivity(intent);
But after calling startActivity I receive the "Media not found error"
I'm not sure what's wrong no exceptions are thrown when writing the file
You are writing the file to internal storage. No third-party apps have access to your internal storage directly. Use FileProvider to make the PDF available to third-party apps.
This sample app does pretty much what you need, except that I get the starting PDF from an asset.

Share audio file from the res/raw folder thorugh Share Intent in Android

I'm trying to share an audio file from my res/raw folder. What I've done so far is:
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound); //parse path to uri
Intent share = new Intent(Intent.ACTION_SEND); //share intent
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share sound to"));
When I choose to share it on GMail, for example, it says something like "Failed to attach empty file". Looks like I'm not getting the right file path, so I'm basically sharing nothing. What am I doing wrong?
Any help would be much appreciated.
Copy the audio file from the resource to external storage and then share it:
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.sound);
fileOutputStream = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/*");
startActivity(Intent.createChooser(intent, "Share sound"));
Add WRITE_EXTERNAL_STORAGE permission to AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
What am I doing wrong?
Few apps handle android.resource Uri values correctly. Your choices are:
Drop the feature, or
Copy the data from the resource into a file, then use FileProvider, perhaps in conjunction with my LegacyCompatCursorWrapper, or
Use my StreamProvider, which can serve raw resources directly, or
Copy the data from the resource into a file, then use Uri.fromFile(), but this looks like it will stop working with the next version of Android, based on preliminary results from testing with the N Developer Preview
EDIT: It was causing a NullPointException. This is what was I doing:
File dest = Environment.getExternalStorageDirectory();
InputStream in = getResources().openRawResource(R.raw.sound);
try
{
OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1){
out.write(buf, 0, len);
}
in.close();
out.close();
}catch (Exception e) {}
final Uri uri = FileProvider.getUriForFile(Soundboard.this, "myapp.folagor.miquel.folagor", dest); //NullPointerException right here!!
final Intent intent = ShareCompat.IntentBuilder.from(Soundboard.this)
.setType("audio/*")
.setSubject(getString(R.string.share_subject))
.setStream(uri)
.setChooserTitle(R.string.share_title)
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
The code was just fine. The only problem was that on the Manifest's permisions, I had "WRITE_EXTERNAL_STORAGE" instead of "android.permissions.WRITE_EXTERNAL_STORAGE". So I was not having permision to write in the external storage, which caused a FileNotFoundException due to the lack of permision. Now it works fine!

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();
}

Can't attach bitmap image. Android

I saw other questions about this, tried their answers, but don't work.
I am trying to use the second method from developer.android.com.
(the second white bullet).
I save an image to applications internal memory, with appropriate permissions.
The image (bitmap) is saved successfully, but I can't attach it to a new intent, to share it.
Here is my code:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("*/*");//Attach all types (images/text)
FileOutputStream fos;
try{
fos = openFileOutput(myfilename, Context.MODE_WORLD_READABLE);
mybitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
//Image is stored successfully (checked data/data/mypackage/files/myfilename)
Uri uri = Uri.fromFile(getFileStreamPath(myfilename));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
}
catch (Exception e){
// noth
//Log.e(TAG, e.getStackTrace().toString());
}
shareIntent.putExtra(Intent.EXTRA_TEXT, "some text also");
return shareIntent;
}
Applications say that can't attach media items.
Gmail seems to attach item, but it shows nothing when mail send!
Also the uri.getPath returns me:
/data/data/mypackage/files/myfilename,
which is correct
Any ideas?
Thank you!
Edit:
Modified code to use sd card. And still don't get it to work:
File imgDir;
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
imgDir = new File(
android.os.Environment.getExternalStorageDirectory(),
".MyAppName/Images");
else imgDir = MyActivity.this.getCacheDir();
if (!imgDir.exists()) imgDir.mkdirs();
File output = new File(imgDir, myFilename);
OutputStream imageFileOS;
try{
Uri uriSavedImage = Uri.fromFile(output);
imageFileOS = getContentResolver().openOutputStream(
uriSavedImage);
bitmapBookCover.compress(Bitmap.CompressFormat.PNG, 90,
imageFileOS);
imageFileOS.flush();
imageFileOS.close();
//Again image successfully saved
shareIntent.putExtra(Intent.EXTRA_STREAM, uriSavedImage);
}
catch (Exception e){
// noth
}
Please try usiing setData() instead of putExtra(), here android developer site - intent set data

Categories

Resources