Can't play mp3 file from internal storage into media player - android

I am downloading mp3 file from this url using DownloadManager. Here is my code.
// Downloading file from internet and save to internal storage.
private void downloadFromOnline() {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = null;
request = new DownloadManager.Request(Uri.parse("https://alquran.technobdapis.com/quranallaudio/arabic_with_bangla/arbn_001.mp3"));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("Downloading...");
request.setDescription("Downloading...arbn_001.mp3");
request.setVisibleInDownloadsUi(true);
File SDCardpath = getFilesDir();
File myDataPath = new File(SDCardpath.getAbsolutePath());
// Internal storage file path to save the downloaded file
// /data/data/com.technobd.internalstoragetest/files/arabic_with_bangla/arbn_001.mp3
if (!myDataPath.exists())
myDataPath.mkdir();
request.setDestinationInExternalFilesDir(getApplicationContext(), myDataPath.getPath() + "/arabic_with_bangla", "arbn_001.mp3");
long refid = downloadManager.enqueue(request);
id = refid;
}
I have tried to play the downloaded file in media player using this code. But unfortunately targetFile.exists() returns false although file exists in that path. Here is the code -
public BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
File SDCardpath = getFilesDir();
File myDataPath = new File(SDCardpath.getAbsolutePath());
File targetFile = new File(myDataPath.getPath() + "/arabic_with_bangla/" +"arbn_001.mp3");
Log.d("FileExists", targetFile.exists() + " ");
// Downloaded file path
// /data/data/com.technobd.internalstoragetest/files/arabic_with_bangla/arbn_001.mp3
// Although target file exists in device It's targetFile.exists() returning false
// TODO: This is the main problem.
if(targetFile.exists()){
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(MainActivity.this, Uri.parse(targetFile.getParent()));
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}else{
// File Not Exists
Log.d("FileExists", targetFile.exists() + " ");
}
}
};
File exists in my device.

Related

DownloadManager throws SecurityException on Android Q

Download Manager gets the error below on Android 10 devices. The target version is 29.
I added android:requestLegacyExternalStorage="true" tag to the Manifest, but it didn't work.
java.lang.SecurityException: Unsupported path /storage/emulated/0/Contents/Awesome App.apk
Here is the code
public static void startDownload(Context context, String url, String token, String subPath) {
DownloadManager.Request request;
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url); // A url to download a file
try {
request = new DownloadManager.Request(uri);
request.addRequestHeader("X-Auth-Token", token);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
try {
File downloadFileDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath() + "/Contents");
if (downloadFileDir != null) {
if (!downloadFileDir.exists()) {
downloadFileDir.mkdirs();
}
File file = new File(downloadFileDir.getAbsolutePath() + File.separator + subPath);
// subPath is name of the file to download. e.g. Awesome App.apk
if (file.exists()) {
file.delete();
}
Uri localUri = Uri.fromFile(file);
request.setDestinationUri(localUri);
if (localUri != null) {
request.setMimeType(MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(localUri.toString())));
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
request.setTitle(subPath);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
try {
manager.enqueue(request);
} catch (SecurityException e) {
e.printStackTrace();
//Got exception here
}
}
/storage/emulated/0/Contents/Awesome App.apk
In an Android 10 device the DownloadManager will not download to your own directories on external storage.
You need to use one of the already available public directories like Document, Download, DCIM, Music and so on.
So you can let download to
/storage/emulated/0/Music/Contents/Awesome App.apk
No need to create your subdirectory yourself as the download manager will do it.
You app does not need any permission to let the download manager execute its task.

Store media in internal storage using download manager

Want to store music file inside getFilesDir() using Uri. I had tried to store by this way
Uri Download_Uri = Uri.parse(songBean.vSongsFileName);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle(songBean.vTitle);
request.setDescription("Downloading File");
try {
request.setDestinationUri(Uri.parse(createDirectory("tmp.mp3").getPath()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadReference = mDownloadManager.enqueue(request);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
}, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Method for the create directory inside internal storage
public File createDirectory(String filename) throws FileNotFoundException {
File file = new File(context.getFilesDir(), filename);
Log.i("Tag", "createDirectory: " + file.getAbsolutePath());
return file;
}
Not able to store the file in internal storage.request.setDestinationUri(Uri.parse(createDirectory("tmp.mp3").getPath())); throwing not a file uri error.Please help me out for this
The getFilesDir() is private internal storage for your app only. You cannot ask another app to put files there as it has no access.
For DownloadManager use external storage.

How to save files with DownloadManager in private path?

I have downloaded some files with DownloadManager, I want to save them where that no one can access them, I mean they are private, just my application can access them and I want after uninstall my app they get deleted. but according to my search DownloadManager can save files just in SDCard that everyone can see my files.
can anyone tell me what to do?
You should probably use:
request.setDestinationInExternalFilesDir(context, DIRECTORY_DOWNLOADS, File.separator + folderName + File.separator + fileName);
Where request is your DownloadManager.Request
This folder (sdcard/Android/data/your.app.package) is accessible to the user, but not visible in galleries (not scanned by media scanner), it's only accessible using file manager. Also, this folder will be deleted when your app gets deleted.
You can use internal storage path to save data internally and it will get deleted when your app will get uninstalled
String dir = getFilesDir().getAbsolutePath();
For Set Your Path For Download File Use: Work For me (Android 11).
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
Complete Code:
First Check Directory
private boolean CreateDirectory() {
boolean ret = false;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getPath() + "/YOUR FOLDER/");
if (!dir.exists()) {
try {
dir.mkdirs();
ret = true;
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
Then:
String URL = " YOUR URL ";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("YOUR TITLE");
request.setDescription("YOUR DESCRIPTION");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
DownloadManager manager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Long downloadId= manager.enqueue(request);
ok,Finish

Downloads the same file twice?

Hi i've been looking through various parts of my code to try and find out whats happening but can't seem to figure it out. The following code is supposed to be downloading two files one called "clientraw" and one called "clientrawextra" but for some reason when i look in the directory there are 2 versions of each file "clientraw...1..." "clientrawextra...1..."
Therefore it seems like it's downloading the files multiple times and i have no idea why??
Thanks in advance!
distance dis = new distance();
dis.findURL(value);
String url = dis.findURL(value);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "clientraw.txt");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
/////////////////////////////////////////////////////
distance disextra = new distance();
disextra.findextra(value);
String urlextra = disextra.findextra(value);
DownloadManager.Request requestextra = new DownloadManager.Request(Uri.parse(urlextra));
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
requestextra.allowScanningByMediaScanner();
}
requestextra.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "clientrawextra.txt");
manager.enqueue(requestextra);
mDownload = new DownLoadComplte();
registerReceiver(mDownload, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
And the broadcast receiver...
private class DownLoadComplte extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(
DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
Intent myIntent = new Intent(splash.this, MainActivity.class);
myIntent.putExtra("key", value); //Optional parameters
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//unregisterReceiver(mDownload);
splash.this.startActivity(myIntent);
}
}
}
So if anyone has the same issue, apparently this is an ongoing and as of yet unresolved issue with the Download manager. I have used a little bit of a work around which you might want to use if your flow is similar to mine. Basically every time that the user opens the app two files are automatically downloaded to the SD card which overwrites the two files previously downloaded. So all i did was add a couple of extra functions to delete the duplicates...
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() +
"/Download/", client);
Log.d("file path", String.valueOf(file));
if(file.exists())
{
boolean flag = file.delete();
Log.d("file", "file deleted " + flag);
}
File sdCardextra = Environment.getExternalStorageDirectory();
File fileextra = new File(sdCardextra.getAbsolutePath() +
"/Download/", clientextra);
boolean exist = fileextra.exists();
Log.d("the file exists = ", String.valueOf(exist));
if(fileextra.exists())
{
boolean flag = fileextra.delete();
Log.d("file", "file deleted " + flag);
}
File sdCard2 = Environment.getExternalStorageDirectory();
File file2 = new File(sdCard2.getAbsolutePath() +
"/Download/", "clientraw-1.txt");
Log.d("file path", String.valueOf(file2));
if(file2.exists())
{
boolean flag = file2.delete();
Log.d("file", "file deleted " + flag);
}
File sdCardextra3 = Environment.getExternalStorageDirectory();
File fileextra3 = new File(sdCardextra3.getAbsolutePath() +
"/Download/", "clientrawextra-1.txt");
boolean exists = fileextra3.exists();
Log.d("the file exists = ", String.valueOf(exists));
if(fileextra3.exists())
{
boolean flag = fileextra3.delete();
Log.d("file", "file deleted " + flag);
}

Set custom folder Android Download Manager

I've a question about Download Manager.
I'm going to download a file from a site. When I set the default directory for download (Environment.DIRECTORY_DOWNLOAD) all works fine and my download is started. But if I try to change the directory, my app doesn't download the file. In particular, I want my file to go into a folder inside a Download, for example /storage/sdcard/Download/myFolder. How can I fix that?
File mydownload = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/myFolder");
if (!mydownload.exists()){
mydownload.mkdir();
}
String url = sUrl[0];
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(mydownload.getAbsolutePath(),"Myfile.extension");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
check below code: its save file in "sdcard/dhaval_files/". just replace your folder name and give permission write_external_storage in android manifest file.
public void file_download(String uRl) {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/dhaval_files");
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/dhaval_files", "test.jpg");
mgr.enqueue(request);
}
There are two options available for you to use.
1) first setDestinationInExternalPublicDir this will let you download in any of the androids standard download folder based on media type eg DIRECTORY_DOWNLOADS, DIRECTORY_MUSIC. these files will remain after uninstall.
request.setDestinationInExternalPublicDir(DIRECTORY_DOWNLOADS,
File.separator + folderName + File.separator + fileName);
The first argument should be a standard downloads directory for this to work properly and cannot be anything else.
2) second is setDestinationInExternalFilesDir this is same as the previous method with the difference that these files will be deleted after app uninstall.
request.setDestinationInExternalFilesDir(context, DIRECTORY_DOWNLOADS,
File.separator + folderName + File.separator + fileName);
here the second argument can be null or any of the android download directories.
Try Below Code:.
String storagePath = Environment.getExternalStorageDirectory()
.getPath()
+ "/Directory_name/";
//Log.d("Strorgae in view",""+storagePath);
File f = new File(storagePath);
if (!f.exists()) {
f.mkdirs();
}
//storagePath.mkdirs();
String pathname = f.toString();
if (!f.exists()) {
f.mkdirs();
}
// Log.d("Storage ",""+pathname);
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Uri uri = Uri.parse(image);
checkImage(uri.getLastPathSegment());
if (!downloaded) {
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/Directory_name", uri.getLastPathSegment());
Long referese = dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_SHORT).show();
}
For Set Your Path For Download File Use: Work For me (Android 11).
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
Complete Code:
First Check Directory
private boolean CreateDirectory() {
boolean ret = false;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getPath() + "/YOUR FOLDER/");
if (!dir.exists()) {
try {
dir.mkdirs();
ret = true;
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
Then:
String URL = " YOUR URL ";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("YOUR TITLE");
request.setDescription("YOUR DESCRIPTION");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
DownloadManager manager= (DownloadManager)
getSystemService(Context.DOWNLOAD_SERVICE);
Long downloadId= manager.enqueue(request);
ok,Finish

Categories

Resources