How detect the OTG cable already connected with device in android? - 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

Related

BluetoothManager getConenctedDevices returns an empty array

I've connected to Xiaomi air buds via bluetooth settings on my phone.
Then, I tried to use getConnectedDevices(BluetoothProfile.GATT_SERVER) and getConnectedDevices(BluetoothProfile.GATT) methods to get a list of connected devices, but in both cases I got an empty array as a result. If I try to use some other profile in getConnectedDevices() I get an exception that says that I'm using a wrong profile.
How can I correctly get a list of currently connected bluetooth devices to my phone.
code example, in onCreate:
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> connectedDevices = mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT_SERVER);
for (BluetoothDevice b :
connectedDevices) {
Log.e(TAG, "onStart: connectedDevice - " + b.toString() );
}
To get a list devices that you connected to ( in the past )
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedList = btAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedList )
{
Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());
}
To get the device you correctly connected to you will have to use a broadcast receiver like in the following
private final BroadcastReceiver btReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("Device",device.getName()+ "\n"+ device.getAddress()+"\n"+ device.getBondState());
}
}
};
There's a few more ways to just find out what the state of the connection of the headset as shown here.
if that still not answering your question then I'm sorry I probably misunderstood your question / need.

BluetoothDevice.getName() is null

I use the following receiver to get the surrounding bluetooth devices :
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Log.d(TAG, "Device hardware adress : " + deviceHardwareAddress);
if (deviceName != null){
Log.d(TAG, "Device name : " + deviceName);
if (deviceName.contains("GYDE")){
Log.d(TAG, "Stooping discovery : " + deviceName);
// Don't forget to unregister the ACTION_FOUND receiver.
unregisterReceiver(mReceiver);
}
}
}
}
};
I have 2 bluetooth devices in the area. I see their MAC Adress but they've got no names. I believe though they have names because :
1) I could see it when testing yesterday (nothing has been modified since then)
2) My phone can list their name after enabling bluetooth
3) I can actually see my phone name

Android : how to detect already connected usb device?

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);

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 {

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