Android监听USB设备并获取挂载路径

在 Android 开发中,如果你想要监听 USB 设备的连接和断开事件,通常会使用 UsbManager 类来管理和处理 USB 设备的连接。Android 提供了 BroadcastReceiver 来接收系统广播,监听 USB 设备的插拔。

  1. 首先,你需要在 AndroidManifest.xml 文件中声明 USB 权限和设备特性。

    <uses-feature android:name="android.hardware.usb.host" />
    
  2. 通过创建一个 BroadcastReceiver 来监听系统发送的与 USB 设备连接相关的广播事件

    class UsbReceiver : BroadcastReceiver() {
        private val TAG = "UsbReceiver"
        @RequiresApi(Build.VERSION_CODES.R)
        override fun onReceive(context: Context, intent: Intent) {
            // This method is called when the BroadcastReceiver is receiving an Intent broadcast.
            Log.i(TAG,"onReceive ${intent.action}")
            when(intent.action){
            UsbManager.ACTION_USB_DEVICE_ATTACHED->{
                Toast.makeText(context,"U盘已连接",Toast.LENGTH_SHORT).show()
                val path = UsbUtil.getUDiskPath(context)
            }
            UsbManager.ACTION_USB_DEVICE_DETACHED->{
                Toast.makeText(context,"U盘已断开连接",Toast.LENGTH_SHORT).show()
            }
            Intent.ACTION_MEDIA_MOUNTED->{
                Toast.makeText(context,"U盘已挂载",Toast.LENGTH_SHORT).show()
                val uri: Uri? = intent.data
                if (uri != null) {
                    val mountPath: String? = uri.path
                    Log.d(TAG, "USB device mounted at: $mountPath")
                }
            }
            Intent.ACTION_MEDIA_EJECT->{
                Toast.makeText(context,"U盘已卸载",Toast.LENGTH_SHORT).show()
            }
        }
    }
    
  3. 动态注册 BroadcastReceiver

    usbReceiver = UsbReceiver()
    var  filter = IntentFilter().apply {
                    addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            addAction(Intent.ACTION_MEDIA_MOUNTED);
            addAction(Intent.ACTION_MEDIA_EJECT);
            addDataScheme("file");
    }
    registerReceiver(usbReceiver, filter);
    
    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(usbReceiver)
    }
    
  4. 获取U盘挂载路径

        @RequiresApi(Build.VERSION_CODES.R)
        fun getUDiskPath(mContext:Context):String{
            val srgMgr = mContext.getSystemService(Context.STORAGE_SERVICE) as StorageManager
            val storagePaths = srgMgr.storageVolumes
            storagePaths.forEach {
                val usbPath = it.directory
                usbPath?.let {it1->
                    Log.i(TAG,"usb path ${it1.path} ${it.isRemovable}")
                    if (it.isRemovable){
                        return it1.path
                    }
                }
            }
            return ""
        }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值