如何防止使用媒体存储外部uri扫描路径



我已经用它扫描安卓上的所有视频文件

public class FileBrowser extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.file_browser);

TextView lists = findViewById(R.id.file_managerTextView);

List<File> files = getAllMediaFilesOnDevice(FileBrowser.this);

for(int i=0;i<files.size();i++){
lists.append(files.get(i).getAbsolutePath() + "n");
}

}
public static List<File> getAllMediaFilesOnDevice(Context context) {
List<File> files = new ArrayList<>();
try {
Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null);

cursor.moveToFirst();
files.clear();
while (!cursor.isAfterLast()){
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
int lastPoint = path.lastIndexOf(".");
path = path.substring(0, lastPoint) + path.substring(lastPoint).toLowerCase();
files.add(new File(path));
cursor.moveToNext();
}
} catch (Exception e) {
e.printStackTrace();
}
return files;
}
}

这是有效的,但问题是给定的输出来自路径/storage/emulated/0//sdcard,所以该函数返回重复的文件,因为/storage/emulated/0//sdcard中的文件相同所以,我的问题是如何防止这两条路径中的任何一条被mediastore 扫描

一个简单的解决方案是插入一个if条件:

String filepath = files.get(i).getAbsolutePath();
if(!filepath.startsWith("/sdcard"))
{
lists.append(filepath + "n");
}

根据要使用的路径,可以将/sdcard替换为/storage/emulated/0。警告一下——有些手机有不同的内部存储路径,使用其中的一个可能无法正常工作。为此,您需要首先检查File对象是否存在&然后继续。

最新更新