在Android 6.0中读取OTG_USB U盘中的数据
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
UsbDevice device_ = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device_ != null) {
try {
if (device != null) {
device.init();
FileSystem fs = device.getPartitions().get(0).getFileSystem();
// Log.d("TAG", "Capacity: " + fs.getCapacity());
// Log.d("TAG", "Occupied Space: " + fs.getOccupiedSpace());
// Log.d("TAG", "Free Space: " + fs.getFreeSpace());
//新增OTG目录 OTG_USB_TAG标示为OTG目录
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
list.add(0,new EntryItem(device_.getManufacturerName(), OTG_USB_TAG, ContextCompat.getDrawable(mainActivity, R.drawable.ic_sd_storage_white_56dp)));
} else {
list.add(0,new EntryItem(OTG_USB_TAG, OTG_USB_TAG, ContextCompat.getDrawable(mainActivity, R.drawable.ic_sd_storage_white_56dp)));
}
adapter = new DrawerAdapter(con, list, MainActivity.this, Sp);
mDrawerList.setAdapter(adapter);
//root.getName()
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(MainActivity.this);
if (devices.length == 0) {
return;
}
device = devices[0];
// Toast.makeText(MainActivity.this, "2:" + usbManager.hasPermission(usbDevice), Toast.LENGTH_LONG).show();
if (usbDevice != null && usbManager.hasPermission(usbDevice)) {
//Toast.makeText(MainActivity.this, "2:received usb device via intent::" + usbDevice, Toast.LENGTH_LONG).show();
// Log.d("TAG", "received usb device via intent");
} else {
PendingIntent permissionIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device.getUsbDevice(), permissionIntent);
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
//Toast.makeText(MainActivity.this, "3", Toast.LENGTH_LONG).show();
refreshDrawer();
}
}
};