【问题标题】: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();
}}