Android : how to detect already connected usb device? - android

I'm trying to detect usb devices which are already connected to android.
I understand there are actions to detect when USB is either attached or detached.
But I don't really get how to check devices after connecting usb device to android.
Also, I've found that each USB device has it's device class code, but how do I figure out what kind of device is connected? For instance, I need to detect both usb mouse and keyboard; how do I differentiate them?

Try this:
First register Broadcast for USB connection.
manifest permission:
:
<intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> </intent-filter>
Get the List of USB Device with details by using this
public void getDetail() {
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 Model = device.getDeviceName();
int DeviceID = device.getDeviceId();
int Vendor = device.getVendorId();
int Product = device.getProductId();
int Class = device.getDeviceClass();
int Subclass = device.getDeviceSubclass();
}}

Just to answer Benny's question here is what the mPermissionIntent could look like:
string actionString = context.PackageName + ".action.USB_PERMISSION";
PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(context, 0, new
Intent(actionString), 0);
mUsbManager.RequestPermission(device, permissionIntent);

Related

How detect the OTG cable already connected with device in android?

I can detect whether the OTG cable attached or detached. But how to detect if OTG cable already connected when app runs. My app only detects if otg cable attached or detached.
public class BootUpReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("USB", "Decive Connected -> " + action);
if (action.equalsIgnoreCase(ACTION_USB_ATTACHED)) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
int vendorID = device.getVendorId();
int productID = device.getProductId();
//If Product and Vendor Id match then set boolean "true" in global variable
tv_otg.setText("External OTG storage device connected !");
Log.e("true", "true");
}
} else if (action.equalsIgnoreCase(ACTION_USB_DETACHED)) {
//When ever device Detach set your global variable to "false"
tv_otg.setText("External OTG storage device disconnected !");
Log.e("ACTION_USB_DETACHED", "ACTION_USB_DETACHED");
}
}
}
bootupreceiver = new BootUpReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_ATTACHED);
filter.addAction(ACTION_USB_DETACHED);
filter.setPriority(100);
registerReceiver(bootupreceiver, filter);
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();
//your code for check device check name logic
}
Check DOC

Check usb device if have been pluged

I used dynamic broadcast can receive UsbManager.ACTION_USB_DEVICE_ATTACHED and UsbManager.ACTION_USB_DEVICE_DETACHED event.
But when my app is not run,the usb device have been plugged,the dynamic broadcast is not receive it. So I want to when my app is first run, i can check it.
I used static broadcast can receive the event,but i don't want to use the method,is it have other method?
You can use UsbManager class and get list of connected device, Try using below method and call it in onCreate
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
intf = device.getInterface(0);
if(device != null && !device.equals(""))
Utils.writeIntoFile(getBaseContext(),"device =============>"+device+"\n"+"getInterface Count =============>"+device.getInterfaceCount());
// There is a device connected to our Android device. Try to open it as a Serial Port.
} else {
connection = null;
device = null;
}
}
if (!keep)
break;
}
if (!keep) {
// There is no USB devices connected.
}
} else {
// There is no USB devices connected.
}
}
If you want to get your app started when a device is attached, you have to register the VID/PID of the USB devices in your manifest
<activity
android:name="..."
...>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter" />
</activity>
and device_filter.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 0x0403 / 0x6001: FTDI FT232R UART -->
<usb-device vendor-id="1027" product-id="24577" />
...
e.g. as mentioned here

Connect Android to RambO (Reprap) via USB

Hy Guys
i try to connect my Rambo Board (http://reprap.org/wiki/Rambo) with android using https://code.google.com/p/usb-serial-for-android/. The app allready starts when i plug in the usb port, but i cant open the device.
The testoutput of the vendor id and product id is right but "UsbSerialProber.acquire(mUsbManager, device);" returns null?
what can i do?
My App Works with an Arduino.
Thank you
Markus
protected void onResume() {
super.onResume();
//Markus K hinzugefügt um device zu finden
mUsbManager.getDeviceList();
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
mTitleTextView.setText(mTitleTextView.getText()+""+ deviceList.size()+"Geräte gefunden");
UsbDevice device=null;
while(deviceIterator.hasNext()){
device = deviceIterator.next();
mTitleTextView.setText(mTitleTextView.getText()+ device.getDeviceName()+" vendorid: "+device.getVendorId()+" productid"+device.getProductId());
//abfrage auf richtige vendor id!!
}
mSerialDevice = UsbSerialProber.acquire(mUsbManager, device);
mTitleTextView.setText(mTitleTextView.getText()+ "Resumed, mSerialDevice=" + mSerialDevice);
if (mSerialDevice == null) {
mTitleTextView.setText(mTitleTextView.getText()+ "No serial device.");
} else {

getDeviceList() always empty

I'm trying to use an Arduino Board along with my Odys Neo x8 tablet but it seems, that the UsbManager doesn't recognize the device alright. I connected the arduino to the tablet via an OTG-adapter so that the tablet will work in host mode, the Arduino is successfully receiving power from the device.
I'm fetching the list of available USB-devices on the tablet as follows:
sUsbController = new UsbController(this, mConnectionHandler, 0, 0);
HashMap<String, UsbDevice> devlist = sUsbController.mUsbManager.getDeviceList();
TextView t = ((TextView)findViewById(R.id.textView));
t.setText("Found " + Integer.toString(devlist.size()) + " devices");
And inside the class UsbController:
mUsbManager = (UsbManager) mApplicationContext
.getSystemService(Context.USB_SERVICE);
But unfortunately, the list remains empty, even if i start filtering using the VID and the PID (the two zeros).
Any suggestions on how to fix this?
I have used the following code which works very fine with keyboard, mouse and Mass Storage device to connect with Pandaboard,
UsbManager usbManager = (UsbManager) getSystemService(USB_SERVICE);
HashMap<String, UsbDevice> devicelist = usbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = devicelist.values().iterator();
while(deviceIterator.hasNext()) {
UsbDevice usbDevice = deviceIterator.next();
Log.i(Log_Tag, "Model : " +usbDevice.getDeviceName());
Log.i(Log_Tag, "Id : " +usbDevice.getDeviceId());
}
This should work with Arduino too.
The Arduino board needs a driver which needs to be installed before it can be accessed.
I am not sure if you have a port of the driver for Android.
Edit:
Also check out this answer in another thread.

Reading raw mouse data on android

In my Android app, I read the values from a 3DConnexion SpaceNavigator via USB-OTG to control an AR.Drone.
Now I want to do the same with a mouse. However, Android is grabbing the mouse and presenting a mouse-cursor. When I write a device-filter with the vendor and product ID of the mouse, I do not get it like with the SpaceNavigator (strangely, both are HID -- I get no cursor with the SpaceNavigator).
Is there a way to get the raw mouse data without the cursor?
Would be perfect with stock Android. but I would also consider altering the ROM for that.
As soon as your Application claims the Mouse (as a USB HID device while being Host), Android should hide the cursor and you can read the raw data. This should work on stock android, but your device has to support USB Host mode and a USB OTG cable will be needed to connect the mouse.
Basic procedure:
enumerate devices
ask for permission to access the USB device
claim the device
read a data package from the HID endpoint
parse the X and Y position, button clicks and scroll wheel rotation from the data package
Example Code that works for me (Android 5.0):
UsbManager usbManager;
UsbDevice usbDevice;
private void connect() {
this.usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
// just get the first enumerated USB device
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
if (deviceIterator.hasNext()) {
this.usbDevice = deviceIterator.next();
}
if (usbDevice == null) {
Log.w(TAG, "no USB device found");
return;
}
// ask for permission
final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
// call method to set up device communication
Log.i(TAG, "permission granted. access mouse.");
// repeat in a different thread
transfer(device);
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
// TODO:
// call your method that cleans up and closes communication with the device
// usbInterface.releaseInterface();
// usbDeviceConnection.close();
}
}
}
};
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
context.registerReceiver(mUsbReceiver, filter);
usbManager.requestPermission(usbDevice, mPermissionIntent);
}
private void transfer(UsbDevice device) {
int TIMEOUT = 0;
boolean forceClaim = true;
// just grab the first endpoint
UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(0);
UsbDeviceConnection connection = this.usbManager.openDevice(device);
connection.claimInterface(intf, forceClaim);
byte[] bytes = new byte[endpoint.getMaxPacketSize()];
connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT);
// depending on mouse firmware and vendor the information you're looking for may
// be in a different order or position. For some logitech devices the following
// is true:
int x = (int) bytes[1];
int y = (int) bytes[2];
int scrollwheel = (int) bytes[3]
// call a listener, process your data ...
}

Categories

Resources