JuniorThree JuniorThree - 4 months ago 23
Android Question

Android. To download mp3 properly

I faced with a weird problem. I write android application for downloading mp3 files. I download mp3 with url, it works fine. But any player except VLC can not find these downloaded mp3 files on device. And if I use any file manager I can find these files but they dont have mp3 tags.

For example.

This is a file downloaded with my application. I open its properties with FX file manager.

enter image description here

And it is mp3 downloaded with another program (not mine). As you can see the file has mp3 tags (shown in bottom of screen)

enter image description here

It is my code for downloading files:

@Override
protected Void doInBackground(String... params) {
InputStream inputStream = null;
FileOutputStream fileOutput = null;
try {
URL url = new URL(params[0]);
File file = new File(path);
URLConnection urlConnection = url.openConnection();

inputStream = urlConnection.getInputStream();
fileOutput = new FileOutputStream(file);

int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;

byte[] buffer = new byte[16384];
int bufferLength = 0;

while ((bufferLength = inputStream.read(buffer)) > 0 ) {

while(isPaused) {
sleep();
}

if(isCancelled()) {
if(file.exists())
file.delete();
return null;
}

fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
publishProgress(downloadedSize, totalSize);
}

if(totalSize > getFreeMemorySize()) {
//if(true) {
if(errorHandler != null)
errorHandler.onMemorySizeException();
cancel(true);
}
} catch (IOException e) {
int i = e.hashCode();
e.getStackTrace();
}
finally {
try {

if(inputStream != null)
inputStream.close();
if(fileOutput != null)
fileOutput.close();

} catch (IOException e) {
int i = e.hashCode();
e.getStackTrace();
}
}
return null;
}


Where I am wrong? Why mp3-files downloaded with my application can npt be found with mp3-players? How could I fix it?

Answer

What you are observing is the fact that MediaStore does not constantly update his database. Database is updated only after reboot and after sd card is mounted.

If you want your files to appear immediately you have to tell MediaStore to add them.

Use MediaScannerConnection.scanFile method to notify MediaStore. (MediaScannerConnection doucumentation) Note that you can add multiple files/paths at once. Also worth noting is that this method is asynchronous, files are added in a separate process and this can take some time - you are notified when operation is completed.

MediaScannerConnection.scanFile(
  context,
  new String[]{file.getAbsolutePath()},
  null,
  new OnScanCompletedListener() {
     @Override
     public void onScanCompleted(String path, Uri uri) {
         // only at this point are files in MediaStore
     }
  });
Comments