From:http://www.it165.net/pro/html/201304/5483.html
如题,现在的很多应用都有自动扫描sdcard文件的功能,例如天天动听等音乐播放器导入音乐的时候、还有一些阅读应用导入本地文本也有扫描功能。最近做一个练习,写到这个功能,只是简单的实现了扫描,并没有考虑手机内存等因素。
这里以扫描图片为例,扫描其它类型的文件,只需要换后缀名。
具体实现方法如下:
01.
private List> l = new ArrayList>();
02.
private HashMap hm;
03.
04.
private String[] img = new String[] { ".jpg", ".png", ".gif", ".bmp" };
05.
06.
private void checkFile(File file) {
07.
if (file.isDirectory()) {
08.
File[] files = file.listFiles();
09.
if (files != null) {
10.
for (int i = 0; i < files.length; i++) {
11.
File f = files[i];
12.
checkFile(f);
13.
}
14.
}
15.
} else if (file.isFile()) {
16.
int dot = file.getName().lastIndexOf(".");
17.
if (dot > -1 && dot < file.getName().length()) {
18.
String extriName = file.getName().substring(dot,
19.
file.getName().length());
20.
if (extriName.equals(img[0]) || extriName.equals(img[1])
21.
|| extriName.equals(img[2]) || extriName.equals(img[3])) {
22.
hm = new HashMap();
23.
hm.put("name", file.getName());
24.
hm.put("path", file.getPath());
25.
l.add(hm);
26.
}
27.
}
28.
}
29.
}
我把路径保存起来,以后方便建立Bitmap对象(BitmapFactory.decodeFile(path)方法)。
之前在网上看到,android系统启动的时候会自动扫描手机中的媒体文件,并把扫描的信息保存在某个文件中,而我们可以读取到这个文件的信息,具体请参看MediaStore类,通过这个类可以实现,这里就不做叙述。