Android获取串口路径

使用 File::listFiles 遍历文件,查找读取 idProduct 和 idVendor 文件,然后找到 ttyUSB 路径。

 public String GetTtyUsbPath(){
  String root = "/sys/bus/usb/devices/";
  File dev = new File(root);
  File[] files = dev.listFiles();
  for(int i = 0;i < files.length;++i){
   if(files[i].isDirectory()){
    File fProduct = new File(files[i].getAbsolutePath() + "/idProduct");
    File fVendor = new File(files[i].getAbsolutePath() + "/idVendor");
    if(fProduct.exists() && fVendor.exists()){
     try {
      LineNumberReader readerProduct = new LineNumberReader(new FileReader(fProduct));
      String version = readerProduct.readLine();
      if(version != null && version.equals("2303")){
      }else{
       continue;
      }
      readerProduct.close();
     }catch (Exception e){
      e.printStackTrace();
     }
     try {
      LineNumberReader readerVendor = new LineNumberReader(new FileReader(fVendor));
      String version = readerVendor.readLine();
      if(version != null && version.equals("067b")){
      }else{
       continue;
      }
      readerVendor.close();
     }catch (Exception e){
      e.printStackTrace();
     }
     File fdev = new File(files[i].getAbsolutePath());
     File[] f = fdev.listFiles();
     for(int j = 0;j < f.length;++j){
      if(f[j].isDirectory() && f[j].getName().startsWith(files[i].getName())){
       File ttyDev = new File(f[j].getAbsolutePath());
       File[] fTty = ttyDev.listFiles();
       for (int k = 0;k < fTty.length;++k){
        if(fTty[k].getName().startsWith("ttyUSB")){
         Log.e(TAG, "Find GPS USB Dev Path:" + fTty[k].getName());
         return "/dev/" + fTty[k].getName();
        }
       }
      }
     }
    }
   }
  }
  return null;
 }

你可能感兴趣的:(Android)