【问题标题】:How to call the UsbDevice.getDeviceName() method - without error (cannot be referenced from a static context)如何调用 UsbDevice.getDeviceName() 方法 - 没有错误(不能从静态上下文中引用)
【发布时间】:2020-03-20 03:15:40
【问题描述】:

为什么以下不起作用?

import android.hardware.usb.UsbDevice;

public class work {
    public String getDeviceName(){
        return UsbDevice.getDeviceName();
    };
}

返回“getDeviceName() 不能从静态上下文中引用。

如何正确调用 UsbDevice.getDeviceName();方法? - 我的班级“工作”不是静态的,为什么会出现这个错误?

【问题讨论】:

    标签: java android static non-static


    【解决方案1】:

    您需要创建UsbDevice 的对象并从中调用方法。

    UsbDevice usbDevice=//something;
    String deviceName = usbDevice.getDeviceName();
    

    例如:

    实时连接设备:

     private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            String deviceName = usbDevice.getDeviceName();
    
        }
    };
    

    获取已连接的设备:

    公共无效getConnectedDevices(){ UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            UsbDevice device = deviceIterator.next();
    
            manager.requestPermission(device, mPermissionIntent);
            String name= device.getDeviceName();
    
        }}
    

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      相关资源
      最近更新 更多