下面列出了android.hardware.usb.UsbAccessory#android.hardware.usb.UsbManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 接続されているUSBの機器リストをLogCatに出力
* @param context
*/
public static void dumpDevices(@NonNull final Context context) {
final UsbManager usbManager = ContextUtils.requireSystemService(context, UsbManager.class);
final HashMap<String, UsbDevice> list = usbManager.getDeviceList();
if ((list != null) && !list.isEmpty()) {
final Set<String> keys = list.keySet();
if (keys != null && keys.size() > 0) {
final StringBuilder sb = new StringBuilder();
for (final String key: keys) {
final UsbDevice device = list.get(key);
final int num_interface = device != null ? device.getInterfaceCount() : 0;
sb.setLength(0);
for (int i = 0; i < num_interface; i++) {
sb.append(String.format(Locale.US, "interface%d:%s",
i, device.getInterface(i).toString()));
}
Log.i(TAG, "key=" + key + ":" + device + ":" + sb.toString());
}
} else {
Log.i(TAG, "no device");
}
} else {
Log.i(TAG, "no device");
}
}
public synchronized void connectRC(Context mContext) {
if (!this.isTryConnect) {
this.isTryConnect = true;
UsbManager usbManager = (UsbManager) mContext.getSystemService("usb");
this.mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
if (usbManager != null) {
UsbAccessory[] accessories = usbManager.getAccessoryList();
UsbAccessory accessory = accessories == null ? null : accessories[0];
if (accessory != null) {
if (usbManager.hasPermission(accessory)) {
CommunicationManager.getCommunicationManager().setAccessory(accessory);
CommunicationManager.getCommunicationManager().startConnectThread(mContext, ConnectType.Aoa);
} else if (!this.isRequestPermission) {
usbManager.requestPermission(accessory, this.mPermissionIntent);
this.isRequestPermission = true;
}
}
}
this.isTryConnect = false;
}
}
/**
* register BroadcastReceiver to monitor USB events
* @throws IllegalStateException
*/
public synchronized void register() throws IllegalStateException {
if (destroyed) throw new IllegalStateException("already destroyed");
if (mPermissionIntent == null) {
if (DEBUG) Log.i(TAG, "register:");
final Context context = mWeakContext.get();
if (context != null) {
mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
final IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
// ACTION_USB_DEVICE_ATTACHED never comes on some devices so it should not be added here
filter.addAction(ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
context.registerReceiver(mUsbReceiver, filter);
}
// start connection check
mDeviceCounts = 0;
mAsyncHandler.postDelayed(mDeviceCheckRunnable, 1000);
}
}
@ReactMethod
public void openDeviceAsync(ReadableMap deviceObject, Promise p) {
try {
int prodId = deviceObject.getInt("productId");
UsbManager manager = getUsbManager();
UsbSerialDriver driver = getUsbSerialDriver(prodId, manager);
if (manager.hasPermission(driver.getDevice())) {
WritableMap usd = createUsbSerialDevice(manager, driver);
p.resolve(usd);
} else {
requestUsbPermission(manager, driver.getDevice(), p);
}
} catch (Exception e) {
p.reject(e);
}
}
private void setupUsbDevice() {
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mSerialDevice = UsbSerialProber.acquire(mUsbManager);
if (mSerialDevice == null) {
Toast.makeText(this, "Cannot find USB device", Toast.LENGTH_SHORT)
.show();
} else {
try {
mSerialDevice.open();
} catch (IOException e) {
Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
try {
mSerialDevice.close();
} catch (IOException e2) {
// Ignore.
}
mSerialDevice = null;
return;
}
}
mSerialIoManager = new SerialInputOutputManager(mSerialDevice,
mListener);
mExecutor.submit(mSerialIoManager);
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice dev = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (dev != null) {
if (String.format("%04X:%04X", dev.getVendorId(), dev.getProductId())
.equals(VID_PID)) {
if (usbIf != null && conn != null) {
conn.releaseInterface(usbIf);
conn.close();
}
}
}
}
}
public void checkForDJIAccessory() {
mUsbManager = (UsbManager) BridgeApplication.getInstance().getSystemService(Context.USB_SERVICE);
UsbAccessory[] accessoryList = mUsbManager.getAccessoryList();
if (accessoryList != null
&& accessoryList.length > 0
&& !TextUtils.isEmpty(accessoryList[0].getManufacturer())
&& accessoryList[0].getManufacturer().equals("DJI")) {
BridgeApplication.getInstance().getBus().post(new RCConnectionEvent(true));
//Check permission
mAccessory = accessoryList[0];
if (mUsbManager.hasPermission(mAccessory)) {
Log.d(TAG, "RC CONNECTED");
} else {
Log.d(TAG, "NO Permission to USB Accessory");
DJILogger.e(TAG, "NO Permission to USB Accessory");
//mUsbManager.requestPermission(mAccessory, null);
}
} else {
BridgeApplication.getInstance().getBus().post(new RCConnectionEvent(false));
Log.d(TAG, "RC DISCONNECTED");
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (usbDevice == null) {
logger.log("USB device was not properly opened");
return;
}
if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) &&
usbDevice.equals(intent.getParcelableExtra(UsbManager.EXTRA_DEVICE))){
usbConnection = usbManager.openDevice(usbDevice);
BaseUsbConnection.this.context.registerReceiver(disconnectReceiver,
new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
onConnect();
broadcastManager.sendBroadcast(new Intent(getConnectIntent()));
} else {
logger.log("Could not get permission to open the USB device");
}
BaseUsbConnection.this.context.unregisterReceiver(respondToUsbPermission);
}
GoldLeaf(ResultReceiver resultReceiver,
Context context,
UsbDevice usbDevice,
UsbManager usbManager,
ArrayList<NSPElement> nspElements) throws Exception {
super(resultReceiver, context, usbDevice, usbManager);
this.nspElements = nspElements;
String fileName;
InputStream fileInputStream;
fileInputStream = context.getContentResolver().openInputStream(nspElements.get(0).getUri());
fileName = nspElements.get(0).getFilename();
pfsElement = new PFSProvider(fileInputStream, fileName);
if (! pfsElement.init())
throw new Exception("GL File provided have incorrect structure and won't be uploaded.");
}
public UsbDevice findDexcom() {
Log.i("CALIBRATION-CHECK-IN: ", "Searching for dexcom");
mUsbManager = (UsbManager) getApplicationContext().getSystemService(Context.USB_SERVICE);
Log.i("USB MANAGER = ", mUsbManager.toString());
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Log.i("USB DEVICES = ", deviceList.toString());
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
Log.i("USB DEVICES = ", String.valueOf(deviceList.size()));
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
if (device.getVendorId() == 8867 && device.getProductId() == 71
&& device.getDeviceClass() == 2 && device.getDeviceSubclass() ==0
&& device.getDeviceProtocol() == 0){
dexcom = device;
Log.i("CALIBRATION-CHECK-IN: ", "Dexcom Found!");
return device;
} else {
Log.w("CALIBRATION-CHECK-IN: ", "that was not a dexcom (I dont think)");
}
}
return null;
}
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
synchronized (this) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
onGranted(device);
}
} else {
Log.d(TAG, "permission denied for device " + device);
}
xdrip.getAppContext().unregisterReceiver(this);
}
}
}
@Override
public void onResume() {
super.onResume();
mActiveNetwork.setText(getString(R.string.id_s_network, networkData.getName()));
final Intent intent = getIntent();
if (ACTION_USB_ATTACHED.equalsIgnoreCase(intent.getAction())) {
onUsbAttach(intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
}
if (mUsb != null || mInLedgerDashboard) {
// Continue displaying instructions until the user opens the
// correct wallet app, or log in completes/errors out
return;
}
// No hardware wallet, jump to PIN or 1st screen entry
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (AuthenticationHandler.hasPin(this))
startActivityForResult(new Intent(this, PinActivity.class), 0);
else
startActivityForResult(new Intent(this, FirstScreenActivity.class), 0);
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Consts.ACTION_USB_PERMISSION.equals(action)) {
setDevice(intent);
}
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
setDevice(intent);
if (device == null) {
onDeviceConnected(device);
}
}
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
if (device != null) {
device = null;
if (usbThreadDataReceiver != null) {
usbThreadDataReceiver.stopThis();
}
eventBus.post(new DeviceDetachedEvent());
onDeviceDisconnected(device);
}
}
}
@Override
public void onCreate() {
this.context = this;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
builder = SerialPortBuilder.createSerialPortBuilder(this);
boolean ret = builder.openSerialPorts(context, BAUD_RATE,
UsbSerialInterface.DATA_BITS_8,
UsbSerialInterface.STOP_BITS_1,
UsbSerialInterface.PARITY_NONE,
UsbSerialInterface.FLOW_CONTROL_OFF);
if(!ret)
Toast.makeText(context, "No Usb serial ports available", Toast.LENGTH_SHORT).show();
}
/**
* initialize ch340 parameters.
*
* @param context Application context.
*/
public static void initCH340(Context context) {
if (context == null) return;
Context appContext = context.getApplicationContext();
mUsbManager = (UsbManager) appContext.getSystemService(Context.USB_SERVICE);
if (mUsbManager != null) {
HashMap<String, UsbDevice> deviceHashMap = mUsbManager.getDeviceList();
LogUtils.e(TAG, "deviceHashMap.size()=" + deviceHashMap.size());
for (UsbDevice device : deviceHashMap.values()) {
LogUtils.i(TAG, "ProductId:" + device.getProductId() + ",VendorId:" + device.getVendorId());
if (device.getProductId() == 29987 && device.getVendorId() == 6790) {
mUsbDevice = device;
if (mUsbManager.hasPermission(device)) {
loadDriver(appContext, mUsbManager);
} else {
if (listener != null) {
listener.result(false);
}
}
break;
}
}
}
}
static public boolean isG4Connected(Context c){
UsbManager manager = (UsbManager) c.getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Log.i("USB DEVICES = ", deviceList.toString());
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
Log.i("USB DEVICES = ", String.valueOf(deviceList.size()));
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
if (device.getVendorId() == 8867 && device.getProductId() == 71
&& device.getDeviceClass() == 2 && device.getDeviceSubclass() ==0
&& device.getDeviceProtocol() == 0){
Log.i("CALIBRATION-CHECK-IN: ", "Dexcom Found!");
return true;
}
}
return false;
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
Toast.makeText(MainActivity.this, "EXTRA_PERMISSION_GRANTED~", Toast.LENGTH_SHORT).show();
InitCH340.loadDriver(MyApplication.getContext(), InitCH340.getmUsbManager());
}
} else {
Toast.makeText(MainActivity.this, "EXTRA_PERMISSION_GRANTED null!", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
unregisterPermissionReceiver(context);
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
connect(context, device);
} else {
//TODO report
}
}
}
}
void refresh() {
UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
UsbSerialProber usbDefaultProber = UsbSerialProber.getDefaultProber();
UsbSerialProber usbCustomProber = CustomProber.getCustomProber();
listItems.clear();
for(UsbDevice device : usbManager.getDeviceList().values()) {
UsbSerialDriver driver = usbDefaultProber.probeDevice(device);
if(driver == null) {
driver = usbCustomProber.probeDevice(device);
}
if(driver != null) {
for(int port = 0; port < driver.getPorts().size(); port++)
listItems.add(new ListItem(device, port, driver));
} else {
listItems.add(new ListItem(device, 0, null));
}
}
listAdapter.notifyDataSetChanged();
}
@Override
protected void onStart() {
super.onStart();
/* Setup USB */
usb = new Usb(this);
usb.setUsbManager((UsbManager) getSystemService(Context.USB_SERVICE));
usb.setOnUsbChangeListener(this);
// Handle two types of intents. Device attachment and permission
registerReceiver(usb.getmUsbReceiver(), new IntentFilter(Usb.ACTION_USB_PERMISSION));
registerReceiver(usb.getmUsbReceiver(), new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
registerReceiver(usb.getmUsbReceiver(), new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
// Handle case where USB device is connected before app launches;
// hence ACTION_USB_DEVICE_ATTACHED will not occur so we explicitly call for permission
usb.requestPermission(this, Usb.USB_VENDOR_ID, Usb.USB_PRODUCT_ID);
}
/**
* USB機器情報(ベンダー名・製品名・バージョン・シリアル等)を取得する
* @param manager
* @param device
* @param out
* @return
*/
@SuppressLint("NewApi")
public static UsbDeviceInfo getDeviceInfo(
@NonNull final UsbManager manager,
@Nullable final UsbDevice device, @Nullable final UsbDeviceInfo out) {
final UsbDeviceConnection connection
= (device != null && manager.hasPermission(device))
? manager.openDevice(device) : null;
try {
return getDeviceInfo(connection, device, out);
} finally {
if (connection != null) {
connection.close();
}
}
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (StkWriter.ACTION_USB_PERMISSION.equals(action)) {
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
// USBを閉じる
/*
mStkWriter.closeUsb();
mTextViewComment.setText(R.string.disconnect_usb);
mButtonConnect.setEnabled(false);
mButtonSend.setVisibility(Button.INVISIBLE);
mButtonBack.setVisibility(Button.INVISIBLE);
*/
}
}
private void registerDetachReceiver() {
detachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
unregisterDetachReceiver();
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
Timber.i("Ledger detached!");
if (device != null)
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(LoginActivity.this,
getString(R.string.toast_ledger_detached, device.getProductName()),
Toast.LENGTH_SHORT)
.show();
}
});
Ledger.disconnect();
onLedgerAction();
}
}
};
registerReceiver(detachReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(intent.getAction())) {
// a new USB device has been attached
DbgLog.msg("USB Device attached; app restart may be needed");
}
}
@PhonkMethod(description = "starts serial", example = "")
public void start() {
getAppRunner().whatIsRunning.add(this);
mUsbManager = (UsbManager) getContext().getSystemService(Context.USB_SERVICE);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
// filter.addAction(ACTION_USB_DETACHED);
// filter.addAction(ACTION_USB_ATTACHED);
getContext().registerReceiver(usbReceiver, filter);
findSerialPortDevice();
}
public void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(ACTION_USB_PERMISSION);
mContext.registerReceiver(this, filter);
}
public static UsbDevice getUsbDevice(final int vendorId, final int productId, final String search) {
final UsbManager manager = (UsbManager) xdrip.getAppContext().getSystemService(Context.USB_SERVICE);
if (manager == null) return null;
final HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
for (Map.Entry<String, UsbDevice> entry : deviceList.entrySet()) {
final UsbDevice device = entry.getValue();
if (device.getVendorId() == vendorId && device.getProductId() == productId
&& device.toString().contains(search)) {
Log.d(TAG, "Found device: " + entry.getKey() + " " + device.toString());
return device;
}
}
return null;
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
if (usbManager.hasPermission(device)) {
debugLog("We have permission, good!");
if (enabled) {
openConnection(device);
}
}
}
} else {
debugLog("permission denied for device " + device);
}
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
synchronized (this) {
if (connectedGps != null && enabled) {
connectedGps.close();
}
}
}
}
/**
* ACTION_USB_ACCESSORY_ATTACHED is an Activity Broadcast.
* Thus this needs to be here not inside {@link USBConnectionManager}
*/
@Override
protected void onNewIntent(Intent intent) {
if (intent.getAction() != null)
switch (intent.getAction()) {
case UsbManager.ACTION_USB_ACCESSORY_ATTACHED:
BridgeApplication.getInstance().getBus().post(new USBConnectionManager.USBConnectionEvent(true));
break;
}
super.onNewIntent(intent);
}
@Override
public void onCreate() {
this.context = this;
serialPortConnected = false;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
findSerialPortDevice();
}