转载请注明出处:https://blog.csdn.net/a512337862/article/details/80505128
本文主要介绍利用libaums在android上实现Android端读写U盘的功能,并将其进行了封装,写了个工具类,方便大家参考。
准备工作
在build.gradle文件中引用libaums:
compile ‘com.github.mjdev:libaums:+’
在AndroidManifest.xml中添加权限:
<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” />
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />
<uses-permission
android:name=”android.hardware.usb.host”
android:required=”false”/>
<uses-feature
android:name=”android.hardware.usb.host”
android:required=”true” />
代码
USBBroadCastReceiver
USBBroadCastReceiver用于监听U盘的插拔,代码如下:
/**
* Author : BlackHao
* Time : 2018/5/10 10:07
* Description : USB 广播
* Logs :
*/
public class USBBroadCastReceiver extends BroadcastReceiver {
private UsbListener usbListener;
public static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case ACTION_USB_PERMISSION:
//接受到自定义广播
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
//允许权限申请
if (usbDevice != null) {
//回调
if (usbListener != null) {
usbListener.getReadUsbPermission(usbDevice);
}
}
} else {
if (usbListener != null) {
usbListener.failedReadUsb(usbDevice);
}
}
break;
case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到存储设备插入广播
UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device_add != null) {
if (usbListener != null) {
usbListener.insertUsb(device_add);
}
}
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED: