i need share a audio.mp3 From my App to Whatsapp - java

When I run the app, it doesn't share audio in whatsapp.
pulsante2.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//condividere
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.suono2);
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/mpeg");
startActivity(Intent.createChooser(intent, "Share audio"));
return false;
}
});
I added <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></u‌​ses-permission>
so why doesn't it share audio mp3?

Related

How to set a file as a ringtone for Android 10 or higher?

Im working on an app and I need to set an mp3 file thats is include in the app as a ringtone.
The following code works well in debug mode (im testing on Android 11), but in the phone the seted ringtone name is a string numbers. Also i can't play the saved file on my phone.
If anyone knows the reason for this behavior I would appreciate your help :)
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pathi=Environment.getExternalStorageDirectory().getPath();
boolean exists = (new File(pathi)).exists();
if (!exists) {
new File(pathi).mkdirs();
}
File file_aux = new File(pathi, "name.mp3");
Uri mUri = Uri.parse("android.resource://com.package.name/"+R.raw.name);
ContentResolver mCr = getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile = mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile = null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(file_aux);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
Log.e("harrypopoter", io.getMessage());
io.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.TITLE, file_aux.getName());
values.put(MediaStore.MediaColumns.MIME_TYPE, getMIMEType(file_aux.getPath()));
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.MediaColumns.SIZE, file_aux.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri newUri = getContentResolver()
.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
try (OutputStream os = getContentResolver().openOutputStream(newUri)) {
int size = (int) file_aux.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file_aux));
buf.read(bytes, 0, bytes.length);
buf.close();
os.write(bytes);
os.close();
os.flush();
} catch (IOException e) {
Log.e("harrypopoter", e.getMessage());
e.printStackTrace();
}
} catch (Exception ignored) {
Log.e("harrypopoter", ignored.getMessage());
ignored.printStackTrace();
}
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
}
}
});

How to move/copy any type of file from asset file to scoped storage ANDROID Q in JAVA?

I have already succeeded with this operation with images, but I cannot do it with other type of file, in my case I try to insert a database.
Here is an example of the code for the images:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
try {
try {
pictures = assetManager.list("photos/dataset1");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (pictures != null) {
for (String filename : pictures) {
InputStream in;
OutputStream out;
InputStream inputStream = assetManager.open("photos/dataset1/"+filename);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
saveImageToGallery(bitmap);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
This method below works for the images :
public void saveImageToGallery(Bitmap bitmap) {
OutputStream outputStream;
Context myContext = requireContext();
try {
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.Q){
ContentResolver contentResolver = requireContext().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME,"Image_"+".jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
outputStream = contentResolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG,100, outputStream);
Objects.requireNonNull(outputStream);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
and there my try for the other type of file :
AssetManager assetManager = Objects.requireNonNull(requireContext()).getAssets();
Context myContext = requireContext();
//Essential for creating the external storage directory for the first launch
myContext.getExternalFilesDir(null);
File databasesFolder = new File(myContext.getExternalFilesDir(null).getParent(), "com.mydb.orca/databases");
databasesFolder.mkdirs();
if (files!= null) {
for (String filename : files) {
InputStream in;
OutputStream out;
try {
in = assetManager.open("database/test/" + filename);
File outFile = new File(databasesFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
} else {
Log.e("Error NPE", "files is null");
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
This code above is not working, I mean, I don't get any errors or the desired result. I want something like this or a function similary as the function for my images but for any type of file.
When I run my application I have no error however nothing happens
I finally find a solution, I pretty sure it's not the best way but it work.
I give me access to all files acccess by this way :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
try {
Intent intentFiles = new Intent();
intentFiles.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uriFiles = Uri.fromParts("package", myContext.getPackageName(), null);
intentFiles.setData(uriFiles);
myContext.startActivity(intentFiles);
} catch (Exception e)
{
Intent intentFiles = new Intent();
intentFiles.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
myContext.startActivity(intentFiles);
}
add this line to your manifest:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
after that, this code below work :
AssetManager assetManager = Objects.requireNonNull(requireContext()).getAssets();
Context myContext = requireContext();
//Essential for creating the external storage directory for the first launch
myContext.getExternalFilesDir(null);
File databasesFolder = new File(myContext.getExternalFilesDir(null).getParent(), "com.mydb.orca/databases");
databasesFolder.mkdirs();
if (files!= null) {
for (String filename : files) {
InputStream in;
OutputStream out;
try {
in = assetManager.open("database/test/" + filename);
File outFile = new File(databasesFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
} else {
Log.e("Error NPE", "files is null");
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
if someone have a best solution it should be nice
I tested on android 11 and it work

How can i share a gif file through intents from firebase storage

i am displaying a gif file in imageView from firebase.
and now i want to share it through intents when user clicks share button.
but i am not able to do it.
i am using this code but when user clicks the app is getting closed.
public void sharegif(){
String baseDir = MainActivity.this.getExternalCacheDir() + "/gm_gif_1.gif";
FileOutputStream out = null;
File file = new File(baseDir);
try {
byte[] readData = new byte[1024 * 500];
InputStream fis = getResources().openRawResource(getResources()
.getIdentifier("gm_gif_1.gif", null, null));
FileOutputStream fos = new FileOutputStream(file);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
baseDir = file.getPath();
Uri photoURI = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID +".provider", new File(baseDir));
Intent shareIntent = new Intent();
shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
shareIntent.setType("image/gif");
startActivity(Intent.createChooser(shareIntent, "Share with"));
}

I want to convert this code for sounds (trying to share audio files)

I examined similar subjects, but I couldn't do it. I'm trying to share .mp3 file with LongClick button. I found it for JPEG files. One guy created method for sharing jpeg file. How can I convert it for .mp3 files?
package com.example.tunch.trap;
import...
public class sansar extends AppCompatActivity {
private String yardik;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_sansar);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
yardik = createImageOnSDCard(R.raw.yardik_denizi);
final MediaPlayer yardikdenizi = MediaPlayer.create(this, R.raw.yardik_denizi);
Button btnYardik = (Button) findViewById(R.id.btnSansar_1);
btnYardik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yardikdenizi.isPlaying()){
yardikdenizi.seekTo(0);
}
yardikdenizi.start();
}
});
btnYardik.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Uri path= FileProvider.getUriForFile(sansar.this, "com.example.tunch.trap", new File(yardik));
Intent shareYardik = new Intent();
shareYardik.setAction(Intent.ACTION_SEND);
shareYardik.putExtra(Intent.EXTRA_TEXT,"Bu ses dosyasını gönderiyorum");
shareYardik.putExtra(Intent.EXTRA_STREAM, path);
shareYardik.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareYardik.setType("audio/mp3");
startActivity(Intent.createChooser(shareYardik, "Paylas.."));
return true;
}
});
}
private String createImageOnSDCard(int resID) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resID);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + resID +".mp3";
File file = new File(path);
try {
OutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e){
e.printStackTrace();
}
return file.getPath();
}
}
This is all Java code. createImageOnSDCard method is for images. I want to use it for my audio file (yardik_denizi.mp3). When I run this, it works but program is trying to send jpeg file. So it doesn't work literally :) How should I change that last part?
You need a method that copies a private raw resource content (R.raw.yardik_denizi) to a publicly readable file such that the latter can be shared with other applications:
public void copyPrivateRawResuorceToPubliclyAccessibleFile(#RawRes int resID,
#NonNull String outputFile) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resID);
outputStream = openFileOutput(outputFile, Context.MODE_WORLD_READABLE
| Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
and then:
copyPrivateRawResuorceToPubliclyAccessibleFile(R.raw.yardik_denizi, "sound.mp3");
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/*");
Uri uri = Uri.fromFile(getFileStreamPath("sound.mp3"));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Sound File"));
You should change the path for uri at
Uri path= FileProvider.getUriForFile(sansar.this, "com.example.tunch.trap", new File(change_it_path_to_yardik_denizi.mp3));
Finally i got the answer. I can send mp3 files to other apps with this code.
copyFiletoExternalStorage(R.raw.yardik_denizi, "yardik_denizi.mp3");
Uri path= FileProvider.getUriForFile(sansar.this,
"com.example.tunch.trap", new File(Environment.getExternalStorageDirectory() +
"/Android/data/yardik_denizi.mp3"));
Intent shareYardik = new Intent();
shareYardik.setAction(Intent.ACTION_SEND);
shareYardik.putExtra(Intent.EXTRA_TEXT,"Bu ses dosyasını gönderiyorum");
shareYardik.putExtra(Intent.EXTRA_STREAM, path);
shareYardik.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareYardik.setType("audio/mp3");
startActivity(Intent.createChooser(shareYardik, "Paylas.."));
And need to create a method to save data in external store.
private void copyFiletoExternalStorage (int resourceId, String resourceName){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/"
+ resourceName;
try{
InputStream in = getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

share audio on Android studio

Don't share mp3 audio in my app (in raw/suono.mp3) on whatapp app
final Button pulsante2 =(Button) findViewById(R.id.pulsante2);
pulsante2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
suono2=MediaPlayer.create(getApplicationContext(),R.raw.suono2);
suono2.start();
}
});
//tasto premuto piu a lungo
pulsante2.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
Uri uri = Uri.parse("android.resource://" + getPackageName()
+ "/raw/" + R.raw.suono2);
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
return true;
}
});
what app say me can't load file please reload
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.suono2);
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();
}

Categories