gpt4 book ai didi

java - Android应用程序: scanning for music files in specified folders runs slowly and hangs.

转载 作者:行者123 更新时间:2023-12-01 05:15:24 25 4
gpt4 key购买 nike

我正在尝试扫描指定文件夹中的所有音乐文件,但遇到性能问题且应用程序关闭。

我的方法是首先使用以下方法从手机获取所有音乐文件:

String[] projection = { 
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TITLE
};

String selection = MediaStore.Audio.Media.IS_MUSIC + "!=" + 0;

cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
MediaStore.Audio.Media.TITLE + " ASC");

然后我使用以下方法获取每个获取的文件的位置:

columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);

如果文件位置位于指定文件夹中,我会将其添加到将在屏幕上显示的列表中。

这种方法的问题在于它的性能不佳。

它挂起 4-5 秒。

如果我滚动列表,应用程序就会关闭。

下面是我现在使用的完整代码:

private String[] getTrackList() {
String[] result = null;
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TITLE
};

String selection = MediaStore.Audio.Media.IS_MUSIC + "!=" + 0;

cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
MediaStore.Audio.Media.TITLE + " ASC");

result = new String[cursor.getCount()];
int position = 0;

for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
getSearchableDir("/mnt/sdcard/Music/"); //See below
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String currentDir = cursor.getString(columnIndex).substring(0,
cursor.getString(columnIndex).lastIndexOf("/") + 1);

if (searchableDir.contains(currentDir)) {
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
result[position] = cursor.getString(columnIndex);
position++;
}
}
return result;
}

// Function for recursively fetching all the sub-directories
private void getSearchableDir(String path) {
searchableDir.add(path);
File root = new File(path);
File[] list = root.listFiles();
for (File f : list) {
if (f.isDirectory()) {
searchableDir.add(f.getAbsolutePath());
getSearchableDir(f.getAbsolutePath());
}
}
}

最佳答案

我认为可以肯定地说 getSearchableDir 是这里的性能消耗者。

重构代码,以便不调用此函数。

关于java - Android应用程序: scanning for music files in specified folders runs slowly and hangs.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11291860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com