First off – I haven’t had much experience with Java yet, and I’m a beginner when it comes to the Android SDK.
I’m trying to write a music player app, which when started scans the entire SD card for mp3 files.
Currently this is how I’m doing that:
// Recursively add songs in a directory
public void addSongsInDirectory(File dir, String filter) {
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
addSongsInDirectory(f, filter);
} else {
// Create new MimetypesFileTypeMap
MimetypesFileTypeMap mtfm = new MimetypesFileTypeMap();
// Add the mp3 mimetype
mtfm.addMimeTypes("audio/mpeg mp3");
// If current song is audio/mpeg, add it to the list
if (mtfm.getContentType(f).equals(filter)) {
songs.add(f.getName());
}
}
}
}
}
Unfortunately, on my handset with many songs on it, this process takes about 30 seconds. How can I optimize this function so that it works faster (and possibly in the background)?
An Android specific optimisation is to look for a file called
.nomediain a directory. This is an indication that there are no media files in a directory in any of its subdirectories. The idea is that applications can create a.nomediafile in their data directories to tell media applications that there’s no need to scan them because there’s no media in there (or possibly there are media files which are only used internally by the application, such as music from a game).Alternatively, you could skip writing your own scanner and use the Media Scanner built in to Android. It’s simply a matter of querying the appropriate
ContentProvider.Your code will look something like this: