如何获取Android系统挂载U盘的路径

最近项目开发中碰到这样一个需求:用户在定制的 Android 设备上插入 U 盘,然后在应用内导入 U 盘里的文件内容。

问题在于如何获取 U 盘的路径,网上搜索后大多数都是采用广播监听的方式来获取 U 盘的路径。但是如果 U 盘在设备开机之前就插着,这样登录应用后就获取不到 U 盘的路径了,于是乎此种方法作罢。

这时候伟大同事告诉了另外一种方法,就是从文件中读取路径。

U 盘在插入系统后,如果系统检测到 U盘,便会在系统的 proc 目录的 mounts 文件内产生一条记录。

可以看到该文件记录了 U 盘每一次插入的相关信息(看不清楚?好吧,我摘取其中的一条用日志打印出来如下)。

很长的一条信息,可能你看不懂(其实我也看不懂),没关系,找到对自己有用的信息即可。是不是发现了 /mnt/sdaq/sdaq1 这样一条信息,没错,他就是我们需要的 U 盘挂载的路径。我们只需要把 /proc/mounts 文件内的带 vfat 的最后一行找到,截取其中的 U 盘路径即可。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
private void searchPath() {
String filePath = "/proc/mounts";
File file = new File(filePath);
List<String> lineList = new ArrayList<>();
InputStream inputStream =null;
try {
inputStream = new FileInputStream(file);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = "";
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("vfat")) {
lineList.add(line);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String editPath = lineList.get(lineList.size() - 1);
int start = editPath.indexOf("/mnt");
int end = editPath.indexOf(" vfat");
String path = editPath.substring(start, end);
Log.d("SelectBusLineDialog", "path: " + path);
}

最后,可能有小伙伴会问「既然是定制的 Android 设备,第一次插入的时候不是知道了 U 盘的路径了吗,只要以后写死这个路径不就好了吗」。好吧,其实当时我也是这么想的,但是实际上每次插拔 U 盘,路径是不断变化的,而且仔细看上面那张大图可以发现每条记录的 U 盘挂载路径都是不同的,这也是不能写死路径的原因。(PS:十分感谢同事「开志哥」在项目中给予的帮助)