其他分享
首页 > 其他分享> > 如何找到安装到android的USB路径?

如何找到安装到android的USB路径?

作者:互联网

我正在开发一个Android应用程序来读取USB数据.
usb可以通过串口连接到android,我的应用程序可以找到它.

现在,我想从USB读取数据文件和文件夹.我看过很多文章.我发现他们使用这段代码:

Environment.getExternalStorageDirectory();

但是在我的情况下,我得到的路径是/ storage / emulated / 0.
当我尝试读取路径中包含的所有文件时,我得到以下语句:

/storage/emulated/0/Android
/storage/emulated/0/Music
/storage/emulated/0/Podcasts
/storage/emulated/0/Ringtones

等等.

但找不到我的usb的路径.所以,我不确定这是从USB读取文件的正确方法吗?

这是我的代码:

File f = Environment.getExternalStorageDirectory();
File[] files = f.listFiles();
String fol = "";
for (File inFile : files) {
    if (inFile.isDirectory()) {
        fol += inFile.toString()+"\n";
    }
}
TextView tv = (TextView) findViewById(R.id.demoTitle);
tv.setText(fol);

解决方法:

使用此代码获取所有已安装的设备

public String getStoragepath() {
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec("mount");
        InputStream is = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        String line;
        String[] patharray = new String[10];
        int i = 0;
        int available = 0;

        BufferedReader br = new BufferedReader(isr);
        while ((line = br.readLine()) != null) {
            String mount = new String();
            if (line.contains("secure"))
                continue;
            if (line.contains("asec"))
                continue;

            if (line.contains("fat")) {// TF card
                String columns[] = line.split(" ");
                if (columns != null && columns.length > 1) {
                    mount = mount.concat(columns[1] + "/requiredfiles");

                    patharray[i] = mount;
                    i++;

                    // check directory is exist or not
                    File dir = new File(mount);
                    if (dir.exists() && dir.isDirectory()) {
                        // do something here

                        available = 1;
                        finalpath = mount;
                        break;
                    } else {

                    }
                }
            }
        }
        if (available == 1) {

        } else if (available == 0) {
            finalpath = patharray[0];
        }

    } catch (Exception e) {

    }
    return finalpath;
}

标签:android,usb-flash-drive,usbserial
来源: https://codeday.me/bug/20190629/1327574.html