how to share audio through share it from another app - android

I want to share audio file in different social apps from my app. I am using following code to share audios. it is working well for whatsapp but not working for shareit. shareit app opens but fails to retrieve the file and says "Sending this type of content is not supported". the file was of "mp3" format. I could share the file from file manager using the android generic share option and then selecting shareit.
public void shareAudio(String packageName, String platformName) {
checkAndPauseAudioPlayer();
try {
//Copy file to external ExternalStorage.
String mediaPath = audioFilePath;
Intent shareMedia = new Intent(Intent.ACTION_SEND);
shareMedia.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//set application package
shareMedia.setPackage(packageName);
shareMedia.setType("audio/*");
//set path of media file in ExternalStorage.
shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(mediaPath));
startActivity(Intent.createChooser(shareMedia, platformName+" Is Not Installed!"));
} catch (Exception e) {
showSnackBar("Please Install "+platformName+" First!",Snackbar.LENGTH_LONG);
}
}

add permission in manifest file :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Related

How to delete a file using the path

I'm building an app that allows the user to save the bitmap or share it without saving it. The 2nd functionality doesn't quite work. I understand that the app needs to save the file to the device before sharing it on a social media app so my idea was, immediately after the file was successfully shared, to automatically delete the file from the device. I've build a delete method trying 2 different approaches and neither have worked:
First approach:
public void deleteFile(String path){
File file = new File(path);
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
}
Second approach:
public void deleteFile(String path){
File file = new File(path);
boolean deleted = file.delete();
}
And I'm calling deleteFile(String) from the sharing method:
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
deleteFile(path);
}
With respect to your stated problem, insertImage() returns a string representation of a Uri. That Uri is not a file. Calling getPath() on it is pointless, and you cannot delete anything based on that path.
More broadly, if your intention is to delete the content right away:
Do not put it in the MediaStore
Do not share it, as you will be deleting it before the other app has a chance to do anything with it
If you want to share it, but then delete it:
Do not put it in the MediaStore
Delete it the next day, or in a few hours, or something, as you have no good way of knowing when the other app is done with the content
To share an image with another app without using the MediaStore:
Save the image to a file in getCacheDir() (call that on a Context, such as an Activity or Service)
Use FileProvider to make that file available to other apps
Beyond that:
Do not use wildcard MIME types in ACTION_SEND. You are the one who is supplying the content to send. You know the actual MIME type. Use it.
Note that there is no requirement for an ACTION_SEND activity to honor both EXTRA_TEXT and EXTRA_STREAM. Most seem to do so, but that behavior is outside of the ACTION_SEND specification.
Note that insertImage() is deprecated on Android Q.
First, you need to check if your file exists, (maybe you set the wrong path?). Then delete the file
File file = new File(path);
if (file.exists()){
if (file.delete()) {
Toast.makeText(this, "file Deleted :" + path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "file not Deleted :" + path, Toast.LENGTH_SHORT).show();
}
}

Open image from external public directory through intent

Recently I am developing a file sharing application and I created a GridView, where the downloaded files are being shown. From this View, I would like to be able to open the default application through an intent, to open the whole file. Currently I am testing the app with only image files. All the files are downloaded to the external public directory this way:
File externalFolder = new File(Environment.getExternalStorageDirectory(), "My application");
if(!externalFolder.exists()){
externalFolder.mkdir();
}
...
File folder = new File(externalFolder, "Images");
if(!folder.exists()){
folder.mkdir();
}
...
String filename = folder.getAbsolutePath() + "/" + fileToDownload.getName() + "." + fileToDownload.getExtension();
FileOutputStream fos = new FileOutputStream(filename);
When the file is downloaded, I scan it with MediaScannerConnection.scanFile. The scan is successful, the picture is visible among other files in Photos app.
After the file is downloaded, I am able to extract a thumbnail in the adapter of the GridView, so I surely have a valid path to the file.
And where the fun begins: I tried to set an onClickListener to the GridView items in the adapter to be able to open the picture in Photos app this way:
listItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if(new File(current.getPath()).exists()){
Log.e("path", "valid");
}else{
Log.e("path", "invalid");
}
Log.e("path", Uri.parse("content://"+current.getPath()).toString());
intent.setDataAndType(Uri.parse("content://"+current.getPath()), "image/*");
getContext().startActivity(intent);
}
});
The Intent is created successfully, I get the following in the log:
E/path: valid
E/path: content:///storage/emulated/0/My application/Images/best_picture_ever.jpeg
I have the option to choose among apps to open. When I select the app, it fails to open the image, like when it does not exist. All the 5 applications.
I tested this on my device with Oreo, and on two emulated devices with Nougat and Lollipop, all of them behaves the same way.
What am I doing wrong?
What am I doing wrong?
You are not creating a valid Uri. You cannot put content:// in front of arbitrary things and have a useful Uri, any more than you can put https:// in front of arbitrary things and have a usable URL.
Use FileProvider to serve up this file.

List downloaded files in Android using Spinner

My app involves downloading a few csv files and then choosing one of them to perform some functions. After the user downloads the required files, a spinner must display the files that have been downloaded. On selecting the required file, it must link to another activity where the path of the file chosen is the FileName. Is this possible using a spinner and how do I go about it?
File selected = new File("/storage/emulated/0/Download/");
String item_ext = "";
try {
item_ext = selected.getName().substring(selected.getName().lastIndexOf("."));
} catch (StringIndexOutOfBoundsException e) {
item_ext = "";
}
if(item_ext.equalsIgnoreCase(".csv")) {
Intent txtIntent = new Intent();
txtIntent.setAction(android.content.Intent.ACTION_VIEW);
txtIntent.setDataAndType(Uri.fromFile(selected), "text/csv");
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
try {
startActivity(txtIntent);
} catch(ActivityNotFoundException e) {
txtIntent.setType("text/*");
startActivity(txtIntent);
}
}
Since my application requirement mainly dealt with downloaded files, I linked the app to Downloads folder. By clicking on the file of interest, the path for the file was obtained. This link helped to get the absolute path and was suitably modified for the purpose.

Android, can't view file stored in external memory through intent

I have a function that downloads and extracts a zip file.
Its extracted to the external storage in: ../Android/data/packagename/..
When I try the following intent to view a .mp4 video for example, its opened in a video player and says that it can't open the file. (not only .mp4 files)
Uri uri = Uri.parse(Helper.getStorageDir(getActivity()) + "/" + mediaObject.getLinkOffline());
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(mediaObject.getLinkOffline().substring(mediaObject.getLinkOffline().lastIndexOf(".") + 1, mediaObject.getLinkOffline().length()));
newIntent.setDataAndType(uri, mimeType);
newIntent.setFlags(newIntent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(newIntent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No handler for this type of file.", 4000).show();
}
However, when I go through a file explorer and open the same file there is no problem.
I have there read/write permissions in my manifest. But thats obviously not the problem since I can read write the file and can also check the the file exists. It just wont let an external app open the file through an intent from my app.
Am I missing something?
EDIT: when I debug and check the mime type for the mp4 file it is "video/mp4".

How to open Context.MODE_PRIVATE files with external apps

I have a string (called comments) that contains some text that I want to display using an external app. I initially create the file like so:
String end = "rtf";
FileOutputStream outputStream;
try {
outputStream = openFileOutput("document." + end, Context.MODE_PRIVATE);
outputStream.write(comments.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
However I am unable to open the file with an external application when I try the following:
String type = "text/rtf";
Intent intent = new Intent (Intent.ACTION_VIEW);
File file = new File(getFilesDir() + "/document." + end);
Uri fileUri = Uri.fromFile(file);
intent.setDataAndType(fileUri,type);
startActivityForResult(intent, Intent.FLAG_GRANT_READ_URI_PERMISSION);
The message that I receive when I open try to the document with the external app is:
"open failed: EACCESS (Permission denied)."
Please advise. Thanks.
However I am unable to open the file with an external application when I try the following:
Correct. Intent.FLAG_GRANT_READ_URI_PERMISSION is for use with a ContentProvider, not for bare file:// Uri values, such as you are using. Use FileProvider to add such a ContentProvider to your app. See also the "Sharing Files" training module and this sample app.
Bear in mind that there's a good chance that your next problem will be an ActivityNotFoundException, as relatively few Android devices will have an app that will support the text/rtf MIME type.

Categories

Resources