share audio on Android studio - java

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

Related

I'm getting an error while sending a screenshot

As soon as the user clicks the button, I ask him to take a screenshot and send it to another friend.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File file = store(bitmap,"File-Name");
shareImage(file);
}
});
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public static File store(Bitmap bm, String fileName){
final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No App Available", Toast.LENGTH_SHORT).show();
}
}
I see that the bitmap value is "" when I debug. I also have these in my error message.
Error Log Image
I used them in my manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_path" />
</provider>
Could you please help me?
You should use this code
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File file = store(bitmap, "name.png");
if (file.exists()) {
shareImage(file);
} else {
Log.e("file exist", "NO");
}
}
});
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public File store(Bitmap bm, String fileName) {
final String dirPath = getExternalCacheDir().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void shareImage(File file) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getPath()));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Screenshot"));
}
Use this to capture a bitmap from a view. Your method will not work anymore using the drawing cache.
public drawBitmap(View view, int width, int height) {
Bitmap bm = Bitmap.createBitmap(width,
height,
Bitmap.Config.ARGB_8888)
Canvas canvas = Canvas(bm)
canvas.drawColor(previewBgColor)
view.draw(canvas)
// Store bitmap in dest file,
File dstFile = File("path/to/file")
storeBitmap(dstFile, bm)
}
public String storeBitmap(File file, Bitmap bmp) {
FileOutputStream stream;
try {
stream = FileOutputStream(file, false)
bmp.compress(Bitmap.CompressFormat.JPEG,99,it)
} catch (e: Exception) {
} finally {
stream.close()
}
return file.path
}
If the file exception persists let us know. I am assuming it's giving that error because the bitmap file returns ""? The docs here should be enough to get you through.
I was able to solve the problem with such a structure. Thank you very much to P Fuster for all his help.
We add these permissions first to the manifests file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
then we add them to the onCreate method in mainActivity.
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Now let's give the click effect of our button.
share_friends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File file = store(bitmap, "name.png");
if (file.exists()) {
shareImage(file);
System.out.println(file.getPath());
} else {
Log.e("file exist", "NO");
}
}
});
Functions used in the button
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public File store(Bitmap bm, String fileName) {
final String dirPath = Environment.getExternalStorageDirectory().getPath() + "/Screenshots";
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void shareImage(File file) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share Screenshot"));
}
the problem was solved like this.

Call a Share button Image from another class onCreate method and onActivityResult android

My first question would be, Is onCreate method needed on every new class in android ?
Next, can we use multiple onActivityResult method without causing distortion
?
For exemple my MainActivity and ShareActivity class both have their own onActivityResult and Oncreate method (code taken from git)
MainActivity is for opening camera and gallery
ShareActivity is for sharing images captured
Note : Both class check for permission first
I wanna call the ShareActivity in my MainActivity, the logical thing to do would be
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, ShareActivity.class);
startActivity(myIntent);
}
});
But my ShareActivity also has this
#OnClick(R.id.open_share)
void onShareTouched() {
boolean has_perms = EasyPermissions.hasPermissions(ShareActivity.this, perms);
if (has_perms) {
shareImageFromBitmap(this.bmp);
} else {
EasyPermissions.requestPermissions(
ShareActivity.this,
getString(R.string.rationale_storage),
SHARE_STORAGE_PERMS_REQUEST_CODE,
perms);
}
}
And then I thought about calling it like this
ShareActivity.getInstance().onShareTouched();
But the app keep crashing, everytime I call the Share class,
Edit : Should I use implement ?
Note :the Share class works fine without MainActivity (I tried in new project)
for better understanding I leave the complete code below
ShareActivity
public class ShareActivity extends AppCompatActivity {
private static ShareActivity instance;
private static final String TAG = "ShareActivity";
private final int SHARE_STORAGE_PERMS_REQUEST_CODE = 900;
private final int RESULT_LOAD_IMG_REQUEST_CODE = 778;
private final String[] perms = { android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE};
private static final String IMAGE_URL = null;
private Bitmap bmp;
#BindView(R.id.open_share)
SimpleDraweeView imageView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
bmp = getBitmapFromUrl(IMAGE_URL);
imageView2.setImageURI(Uri.parse(IMAGE_URL));
instance = this;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMG_REQUEST_CODE && resultCode == RESULT_OK) {
List<Image> images = ImagePicker.getImages(data);
if(images.size() > 0) {
String imagePath = images.get(0).getPath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagePath, options);
imageView2.setImageURI(Uri.fromFile(new File(imagePath)));
}
}
}
#OnClick(R.id.open_share)
void onShareTouched() {
boolean has_perms = EasyPermissions.hasPermissions(ShareActivity.this, perms);
if (has_perms) {
shareImageFromBitmap(this.bmp);
} else {
EasyPermissions.requestPermissions(
ShareActivity.this,
getString(R.string.rationale_storage),
SHARE_STORAGE_PERMS_REQUEST_CODE,
perms);
}
}
#AfterPermissionGranted(SHARE_STORAGE_PERMS_REQUEST_CODE)
private void shareImageFromBitmap(Bitmap bmp) {
Uri uri = getUriImageFromBitmap(bmp, ShareActivity.this);
if(uri == null) {
//Show no URI message
return;
}
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, IMAGE_URL);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/png");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
private Bitmap getBitmapFromUrl(String url) {
Uri uri = Uri.parse(url);
ImageRequest downloadRequest = ImageRequest.fromUri(uri);
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(downloadRequest, ShareActivity.this);
if (ImagePipelineFactory.getInstance().getMainFileCache().hasKey(cacheKey)) {
BinaryResource resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey);
byte[] data = null;
try {
data = resource.read();
} catch (IOException e) {
e.printStackTrace();
}
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
return null;
}
private Uri getUriImageFromBitmap(Bitmap bmp, Context context) {
if(bmp == null)
return null;
Uri bmpUri = null;
try {
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "IMG_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
bmpUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public static ShareActivity getInstance() {
return instance;
}
}
MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
if (requestCode == OPEN_THING) {
Uri uri = Objects.requireNonNull(data.getExtras()).getParcelable(ScanConstants.SCANNED_RESULT);
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
if (uri != null) {
getContentResolver().delete(uri, null, null);
}
scannedImageView.setImageBitmap(bitmap);
FileOutputStream outputStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/Scan Documents");
directory.mkdir();
String filename = String.format("d.jpg", System.currentTimeMillis());
File outFile = new File(directory, filename);
Toast.makeText(this, "Image Saved Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outFile));
sendBroadcast(intent);
try {
outputStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I found a better easier way
I had to completely change my method, I put everything in my button onClick
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable myDrawable = scannedImageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
try{
File file = new File(MainActivity.this.getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share Image Via"));
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
});
No need ShareActivity it works great

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

Get imageview from Adapter in Fragment

I have Image view list in adapter on click of image I show full screen image. Where I have one button outside of adapter in fragment.
Now I want to get that image in fragment onClick of button to share that image.
Below code this in adapter where my images are getting download.
I have using Android-Universal-Image-Loader library to show images.
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(callback != null) {
Bitmap bitmap = ((BitmapDrawable) img_main_bg.getDrawable()).getBitmap();
callback.onItemClicked(bitmap);
}
spinner.setVisibility(View.GONE);
}
How do I get image in fragment?
I already tried interface but onLoadingComplete downloading multiple image at time so I can't get right image on that.
you can do it following way
first make click listener in that ask for permission to save image
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
imgView = imageView;
boolean hasPermission = (ContextCompat.checkSelfPermission(ImagePagerActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(ImagePagerActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
112);
}else
{
showDialog();
}
}
});
if permission is applied then save image first then share it
private void showDialog()
{
new AlertDialog.Builder(ImagePagerActivity.this,R.style.MyAlertDialogStyle)
.setTitle("Select your option")
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
imgView.buildDrawingCache();
Bitmap bm = imgView
.getDrawingCache();
OutputStream fOut = null;
try {
File root = new File(
Environment
.getExternalStorageDirectory()
+ File.separator
+ "Beauty"
+ File.separator);
if (!root.exists())
root.mkdirs();
File sdImageMainDirectory = new File(
root,
System.currentTimeMillis()
+ ".jpg");
fOut = new FileOutputStream(
sdImageMainDirectory);
bm.compress(
Bitmap.CompressFormat.PNG,
100, fOut);
fOut.flush();
fOut.close();
Toast.makeText(
ImagePagerActivity.this,
"File saved at Beauty folder",
Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
Toast.makeText(
ImagePagerActivity.this,
"Error occured. Please try again later.",
Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
}
})
.setNegativeButton("Share",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
try {
imgView.buildDrawingCache();
Bitmap bm = imgView
.getDrawingCache();
OutputStream fOut = null;
File root = new File(
Environment
.getExternalStorageDirectory()
+ File.separator
+ " Beauty"
+ File.separator);
if (!root.exists())
root.mkdirs();
File sdImageMainDirectory = new File(
root, "1.jpg");
fOut = new FileOutputStream(
sdImageMainDirectory);
bm.compress(
Bitmap.CompressFormat.PNG,
100, fOut);
fOut.flush();
fOut.close();
Intent shareIntent = new Intent(
Intent.ACTION_SEND);
Uri phototUri = Uri
.fromFile(sdImageMainDirectory);
shareIntent.setData(phototUri);
shareIntent
.setType("image/png");
shareIntent.putExtra(
Intent.EXTRA_STREAM,
phototUri);
startActivityForResult(Intent
.createChooser(
shareIntent,
"share using"),
2);
} catch (Exception ce) {
ce.printStackTrace();
}
}
})
.show();
}

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

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?

Categories