I have the following code which scan a device for directories which contain mp3.
The following does the job, but unfortunately in some devices where the amount of directories is huge, it takes too long to scan.
Is there a way to speed it up?
scanDirectory(Environment.getExternalStorageDirectory());
private void scanDirectory(File dir) {
File[] files = dir.listFiles();
if( files != null ){
for( int i=0; i<files.length; i++ ){
File file = files[i];
if( file.isDirectory() ){
if( hasAudioFile(file) ){
mFolders.add(file.getAbsolutePath()); // this directory has a mp3 file
}
scanDirectory(file);
}
}
}
}
private boolean hasAudioFile(File dir){
File[] files = dir.listFiles();
if( files == null ){
return false;
}
for( int i=0; i<files.length; i++ ){
File file = files[i];
if( !file.isDirectory() ){
if( file.getName().toLowerCase().endsWith(".mp3") ){
return true;
}
}
}
return false;
}
I know that there is a method to scan all music files in a device which more faster(like this one), but in my case I want the folders not the files.
I encountered the same problem.
If you're loading these folders into a list, you could check the folder one level deep and see whether it contains audio, and just check it as the list is loaded - so you don't scan so many folders.
Alternatively, you could run this as a background task in a boot-service, saving the results into a database which you could update as files are added/updated/modified/removed.
Another way would be to use the method provided in your link, get a list of audio files from the MediaStore content provider, then traverse that list of files - obtain each file's parent - then add that to your list.