Android并不会默认记录设备上连接过的所有USB闪存驱动器。但是,您可以使用USB Host API来获取USB设备的元数据并记录在本地存储器中。以下是一个示例代码:
首先,在AndroidManifest.xml文件中添加以下权限:
其次,创建一个类来获取USB设备的元数据并将其写入文件中:
public class USBMetadataLogger { private static final String FILE_NAME = "usb_metadata.txt"; // 文件名 private Context mContext;
public USBMetadataLogger(Context context) { mContext = context; }
public void logDeviceMetaData(UsbDevice device) { String metaData = "Device Name: " + device.getDeviceName() + "\n"; metaData += "Vendor ID: " + device.getVendorId() + "\n"; metaData += "Product ID: " + device.getProductId() + "\n";
// 获取外部存储路径
String storageDir = Environment.getExternalStorageDirectory().toString();
File file = new File(storageDir, FILE_NAME);
try {
// 将元数据写入文件中
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
writer.write(metaData);
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
最后,在Activity或Service中使用USBMetadataLogger类:
public class MainActivity extends AppCompatActivity { private UsbManager mUsbManager; private USBMetadataLogger mLogger;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
mUsbManager = (UsbManager) getSystemService(USB_SERVICE);
mLogger = new USBMetadataLogger(this);
}
@Override protected void onResume() { super.onResume();
// 获取已连接的所有USB设备并记录它们的元数据
HashMap deviceList = mUsbManager.getDeviceList();
for (UsbDevice device : deviceList.values()) {
mLogger.logDeviceMetaData(device);
}
} }
上面的代码将获取已连接设备的元数据并将其写入名为“usb_metadata.txt”的文本文件中,该文件将存储在设备的外部存储器上。