Android APP 检测和监听当前USB设备插入拔出以及读取VID/PID

一、列出所有的usb device设备,打印vip pid

private boolean AllDeviceConnected(){
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> usbList = manager.getDeviceList();
        for(String key: usbList.keySet()){
            UsbDevice usbDevice = usbList.get(key);
            if(usbDevice != null){
                Log.d(TAG, "usb device: " + usbDevice.getProductId() + ": " + usbDevice.getVendorId());
            }
        }
        return false;
}

二、使用BroadcastReceiver 系统广播监听usb设备拔插动作,实际测试android.hardware.usb.action.USB_STATE之侦听otg usb口的,而且不管是接这usb线还是不接usb线,进入app的时候,都会有一次广播。UsbManager.ACTION_USB_ACCESSORY_ATTACHED和UsbManager.ACTION_USB_ACCESSORY_DETACHED是U盘插入和拔出的广播,进入app的时候不管接U盘还是不接U盘,都没有广播,进入app后插拔U盘才有广播。

private void detectUsbWithBroadcast() {
        Log.d(TAG, "listenUsb: register");
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction("android.hardware.usb.action.USB_STATE");
 
        registerReceiver(mUsbStateChangeReceiver, filter);
        Log.d(TAG, "listenUsb: registered");
    }
 
    private BroadcastReceiver mUsbStateChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: " + intent.getAction());
        }
 
    };

三、直接贴出测试代码MainActivity.java,MainActivity.java不要有任何的修改,USBBroadcastReceiver\app\src\main\java\com\example\usblistener\MainActivity.java

package com.example.usblistener;


import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "USBDEVICE";
    private USBBroadcastReceiver usbBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);

        intentFilter.addAction("android.hardware.usb.action.USB_STATE");
        usbBroadcastReceiver = new USBBroadcastReceiver();
        registerReceiver(usbBroadcastReceiver, intentFilter);

        detectUsbDeviceWithUsbManager();

        AllDeviceConnected();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (usbBroadcastReceiver != null) {
            unregisterReceiver(usbBroadcastReceiver);
        }
    }

    class USBBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            AllDeviceConnected();

            if (intent.getAction().equals("android.hardware.usb.action.USB_DEVICE_ATTACHED")  ||  intent.getAction().equals("android.hardware.usb.action.USB_DEVICE_DETACHED")) {
                UsbDevice usbDevice = (UsbDevice)intent.getExtras().get("device");
                Toast.makeText(MainActivity.this, "usb device status changed  action="+intent.getAction()+" pid="+usbDevice.getProductId()+" vid="+usbDevice.getVendorId(), Toast.LENGTH_SHORT).show();
            }

            if (intent.getAction().equals("android.hardware.usb.action.USB_STATE")) {
                if (intent.getExtras().getBoolean("connected")) {
                    // usb 插入
                    Toast.makeText(MainActivity.this, "usb insert", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"usb insert");
                } else {
                    //   usb 拔出
                    Toast.makeText(MainActivity.this, "usb pull out", Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"usb  pull out");
                }
            }
        }
    }

    private void detectUsbDeviceWithUsbManager() {
        HashMap<String, UsbDevice> deviceHashMap = ((UsbManager) getSystemService(USB_SERVICE)).getDeviceList();

        for (Map.Entry entry : deviceHashMap.entrySet()) {
            Log.d(TAG, "detectUsbDeviceWithUsbManager: " + entry.getKey() + ", " + entry.getValue());
        }
    }

    private boolean isCurrentDeviceConnected(){
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> usbList = manager.getDeviceList();
        for(String key: usbList.keySet()){
            UsbDevice usbDevice = usbList.get(key);
            if(usbDevice != null && usbDevice.getProductId() == 10304 && usbDevice.getVendorId() == 1060){
                return true;
            }
        }
        return false;
    }
    private boolean AllDeviceConnected(){
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> usbList = manager.getDeviceList();
        for(String key: usbList.keySet()){
            UsbDevice usbDevice = usbList.get(key);
            if(usbDevice != null){
                Log.d(TAG, "usb device: " + usbDevice.getProductId() + ": " + usbDevice.getVendorId());
            }
        }
        return false;
    }
}

四、拔插U盘时候的log,测试ok。

 五、在sdk frameworks中也会用到usb功能

       frameworks/base/services/usb/java/com/android/server/usb/UsbDeviceManager.java

六、参考文章

https://www.pianshen.com/article/73781409679/

https://my.oschina.net/u/4352543/blog/3551136

https://www.pianshen.com/article/9533757691/

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值