Home » Android » How to make an basic Android USB Host application?

How to make an basic Android USB Host application?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m trying to develop a application wich detects a USB device and shows a pop-up when it’s connected.
I followed the basic USB tutorial that you can find in Android Developers website (http://developer.android.com/guide/topics/connectivity/usb/host.html)

Here’s my Android Manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.com.habeis"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <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>
    </application>

</manifest>

And my device_filter.xml file:

    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <usb-device vendor-id="0x1BCF" product-id="0x0007" />
</resources>

My Activity

package br.com.habeis;
import java.util.HashMap;
import java.util.Iterator;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        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();
            Toast.makeText(this,"Value of device :" +device.getDeviceName(), Toast.LENGTH_LONG).show();

        }
    }



}

Does anyone know what is missing in my code?

How to&Answers:

My guess is that your vendor-id and product-id are in hex and they need to be integers. It’s not very well documented but checkout https://stackoverflow.com/a/8328814/1302183

Answer:

it should be in integers , convert them into integers and then use it the device filter file