本文主要是介绍Android P检测USB插入拔出消息并基于libaums实现读取USB文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Android设备中检测USB插入消息,并且从USB中读取文件。
一、导入libaums包
libaums开源项目地址:https://github.com/magnusja/libaums
build.gradle文件中引用libaums:
implementation 'com.github.mjdev:libaums:+’
或者编译出libaums-0.6.0.jar,导入jar包:
implementation files(‘libs/libaums-0.6.0.jar’)
二、新建一个广播,接收USB插入消息,并读取Usb文件
检测到Usb插入:UsbManager.ACTION_USB_DEVICE_ATTACHED;
检测到Usb拔出:UsbManager.ACTION_USB_DEVICE_DETACHED.
readUsbDeviceList()获取Usb设备请申请访问权限或者调用readDevice读取Usb文件;
readDevice()为读取Usb中文件操作;
//Usb中要读取的文件
private static final String MCU_VERSION_FILE = "version.txt";public class UsbIntentReceiver extends BroadcastReceiver {private static final String TAG = "UsbIntentReceiver";private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";//Usb listprivate static UsbMassStorageDevice[] mStorageDevices;//Usb pathprivate UsbFile mUsbPath;@Overridepublic void onReceive(Context context, Intent intent) {final UsbDevice device = intent.getExtras().getParcelable(UsbManager.EXTRA_DEVICE);switch (intent.getAction()) {case UsbManager.ACTION_USB_DEVICE_ATTACHED://检测到USB插入,读取Usb设备readUsbDeviceList(context);break;case UsbManager.ACTION_USB_DEVICE_DETACHED://检测到Usb拔出break;case ACTION_USB_PERMISSION://通知一个弹框,询问用户对Usb的访问权限,用户选择ok,表示可以访问Usb设备//申请对USB的读写权限//返回true,表示用户选择了ok,同意进行读取Usbif(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,false)){if(device != null ){//已经获取到Usb访问权限,读取设备readDevice(context,getUsbMass(device));}}break;}}private void readUsbDeviceList(Context context) {//获取当前Usb设备mStorageDevices = UsbMassStorageDevice.getMassStorageDevices(context);//打印当前有几个Usb设备Log.i(TAG,"sunxiaolin,readUsbDeviceList,mStorageDevices.length=" + mStorageDevices.length);//创建一个弹框类型ACTION_USB_PERMISSIONUsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);for (UsbMassStorageDevice device : mStorageDevices) {if (usbManager.hasPermission(device.getUsbDevice())) {//已经获取到Usb访问权限,直接读取设备readDevice(context, device);}else {//通知一个弹框,询问用户对Usb的访问权限,用户选择ok,表示可以访问Usb设备//没有访问权限,申请权限usbManager.requestPermission(device.getUsbDevice(), pendingIntent);}}}private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice){Log.i(TAG,"sunxiaolin:getUsbMass,usbDevice=" + usbDevice);if( mStorageDevices != null && mStorageDevices.length > 0){for( UsbMassStorageDevice device : mStorageDevices){Log.i(TAG,"sunxiaolin:getUsbMass,device=" + device);if(usbDevice.equals(device.getUsbDevice())){return device;}}}return null;}private void readDevice(Context context, UsbMassStorageDevice device) {try {device.init();// Only uses the first partition on the devicePartition partion = device.getPartitions().get(0);Log.i(TAG,"sunxiaolin,partion=" + partion);FileSystem currentFs = partion.getFileSystem();//Toast.makeText(context, "getRootDirectory: " + currentFs.getRootDirectory().getName(), Toast.LENGTH_LONG).show();Log.d(TAG, "Capacity: " + currentFs.getCapacity());//Toast.makeText(context, "Capacity: " + currentFs.getCapacity(), Toast.LENGTH_LONG).show();Log.d(TAG, "Occupied Space: " + currentFs.getOccupiedSpace());//Toast.makeText(context, "Occupied Space: " + currentFs.getOccupiedSpace(), Toast.LENGTH_LONG).show();Log.d(TAG, "Free Space: " + currentFs.getFreeSpace());//Toast.makeText(context, "Free Space: " + currentFs.getFreeSpace(), Toast.LENGTH_LONG).show();Log.d(TAG, "Chunk size: " + currentFs.getChunkSize());//Toast.makeText(context, "Chunk size: " + currentFs.getChunkSize(), Toast.LENGTH_LONG).show();mUsbPath = currentFs.getRootDirectory();///< 读取当前目录下的文件readDataFromUsb(context);} catch (Exception e) {e.printStackTrace();}}private void readDataFromUsb(Context context) {UsbFile[] usbFiles = new UsbFile[0];try {usbFiles = mUsbPath.listFiles();} catch (IOException e) {e.printStackTrace();}if (null != usbFiles && usbFiles.length > 0) {for (UsbFile usbFile : usbFiles) {Log.i(TAG,"sunxiaolin,usbFile=" + usbFile);if (usbFile.getName().equals(VERSION_FILE)) {readTxtFromUsb(usbFile);Toast.makeText(context, "usbFile.getName(): " + usbFile.getName(), Toast.LENGTH_LONG).show();}}}}private void readTxtFromUsb(UsbFile usbFile) {UsbFile descFile = usbFile;//mMcuUpdateFile = usbFile;InputStream is = new UsbFileInputStream(descFile);StringBuilder sb = new StringBuilder();BufferedReader bufferedReader = null;try {bufferedReader = new BufferedReader(new InputStreamReader(is));String read;while ((read = bufferedReader.readLine()) != null) {sb.append(read);Log.i(TAG,"sunxiaolin,readTxtFromUDisk,readResult=" + read);}} catch (Exception e) {e.printStackTrace();} finally {try {if (bufferedReader != null) {bufferedReader.close();}} catch (IOException e) {e.printStackTrace();}}}
}
三、在AndroidManifest.xml中申请权限和配置广播
<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” />
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” /> <receiverandroid:name=".UsbIntentReceiver"android:exported="true"><intent-filter><action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /><action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" /><action android:name="com.android.example.USB_PERMISSION" /></intent-filter><meta-dataandroid:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"android:resource="@xml/device_filter" />
</receiver>
xml文件device_filter:
<resources><!-- filter for MTP/PTP devices --><usb-device class="255" subclass="255" protocol="0" /><usb-device class="6" subclass="1" protocol="1" />
</resources>
总结:其中有一个申请权限,弹出框然该用户选择允许访问usb设备,是安卓为了提高用户隐私采取的措施,提醒用户哪些权限被使用。如果去掉还是要在系统中去修改权限。
这篇关于Android P检测USB插入拔出消息并基于libaums实现读取USB文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!