前言
简单记录一监听和获取USB真实路径,记录一下方便自己查阅。
系统应用下测试!
正文
磁盘监听
监听磁盘挂载和卸载这个就是Android原生接口广播监听,这个之前有介绍过。
IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); //intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED); intentFilter.addDataScheme("file"); intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); registerReceiver(mMountedReceiver, intentFilter);
还有一种方式,监听设备USB_DEVICE_ATTACHED和USB_DEVICE_DETACHED
IntentFilter intentFilter= new IntentFilter(); intentFilter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED"); intentFilter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED"); registerReceiver(mDeviceReceiver, intentFilter);
收到USB_DEVICE_ATTACHED广播并不是表示磁盘挂载成功了
收到ACTION_MEDIA_MOUNTED广播才表示磁盘挂载成功
获取磁盘路径
遍历所有的VolumeInfo
//这里只是为了打印信息,没有对代码优化 private void findVolumePath() { if (null == mStorageManager) { mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE); } List<VolumeInfo> listVolumeInfo = mStorageManager.getVolumes(); if (null != listVolumeInfo) { for (VolumeInfo volumeInfo : listVolumeInfo) { Log.d(TAG, "findVolumePath volumeInfo : " + volumeInfo); if (null != volumeInfo) { DiskInfo diskInfo = volumeInfo.getDisk(); Log.d(TAG, "findVolumePath type : " + volumeInfo.getType() + " , diskInfo: " + diskInfo); if (null != diskInfo) { Log.d(TAG, "findVolumePath isUsb() : " + diskInfo.isUsb()); if (diskInfo.isUsb()) { Log.d(TAG, "findVolumePath sysPath : " + diskInfo.sysPath); } } } } } }
上面打印的sysPath就是磁盘真实的挂载路径。
完整日志
//磁盘卸载 mMountedReceiver 222 action : android.intent.action.MEDIA_EJECT findVolumePath volumeInfo : VolumeInfo{private}: findVolumePath type : 1 , diskInfo: null findVolumePath volumeInfo : VolumeInfo{emulated}: findVolumePath type : 2 , diskInfo: null findVolumePath volumeInfo : VolumeInfo{public:8,4}: findVolumePath type : 0 , diskInfo: DiskInfo{disk:8,0}: findVolumePath isUsb() : true findVolumePath sysPath : /sys//devices/platform/soc/13050000.usb/usb4/4-1/4-1:1.0/host0/target0:0:0/0:0:0:0/block/sda mDeviceReceiver 111 action : android.hardware.usb.action.USB_DEVICE_DETACHED
//磁盘挂载 mDeviceReceiver 111 action : android.hardware.usb.action.USB_DEVICE_ATTACHED mMountedReceiver 222 action : android.intent.action.MEDIA_MOUNTED findVolumePath volumeInfo : VolumeInfo{private}: findVolumePath type : 1 , diskInfo: null findVolumePath volumeInfo : VolumeInfo{emulated}: findVolumePath type : 2 , diskInfo: null findVolumePath volumeInfo : VolumeInfo{public:8,4}: findVolumePath type : 0 , diskInfo: DiskInfo{disk:8,0}: findVolumePath isUsb() : true findVolumePath sysPath : /sys//devices/platform/soc/13050000.usb/usb4/4-1/4-1:1.0/host0/target0:0:0/0:0:0:0/block/sda
参考文章
© 版权声明