Search code examples
javaandroidandroid-intentusbhost

Android USB Host example not working in Android Studio


I have found the following example at http://mobilemerit.com/android-app-for-usb-host-with-source-code/#. This code is meant to list connected USB devices but it does not compile in Android Studio. I'm wondering what is necessary in order for it to compile and run?

activity_main.xml

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >
 
    <button android:id="@+id/check"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Check USB devices"></button>
    <textview android:id="@+id/info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></textview>
 
</linearlayout>

MainActivity.java

package com.mobilemerit.usbhost;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
 
import com.mobilemerit.usbhost.R;
 
public class MainActivity extends Activity {
    PendingIntent mPermissionIntent;
    Button btnCheck;
    TextView textInfo;
    UsbDevice device;
    UsbManager manager;
    private static final String ACTION_USB_PERMISSION = "com.mobilemerit.usbhost.USB_PERMISSION";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCheck = (Button) findViewById(R.id.check);
        textInfo = (TextView) findViewById(R.id.info);
        btnCheck.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                textInfo.setText("");
                checkInfo();
            }
        });
 
    }
 
    private void checkInfo() {
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        /*
         * this block required if you need to communicate to USB devices it's
         * take permission to device
         * if you want than you can set this to which device you want to communicate   
         */
        // ------------------------------------------------------------------
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
                ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, filter);
        // -------------------------------------------------------------------
        HashMap<string , UsbDevice> deviceList = manager.getDeviceList();
        Iterator<usbdevice> deviceIterator = deviceList.values().iterator();
        String i = "";
        while (deviceIterator.hasNext()) {
            device = deviceIterator.next();
            manager.requestPermission(device, mPermissionIntent);
            i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
                    + "DeviceName: " + device.getDeviceName() + "\n"
                    + "DeviceClass: " + device.getDeviceClass() + " - "
                    + "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
                    + "VendorID: " + device.getVendorId() + "\n"
                    + "ProductID: " + device.getProductId() + "\n";
        }
 
        textInfo.setText(i);
    }
 
    private 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
                        }
                    } else {
                        Log.d("ERROR", "permission denied for device " + device);
                    }
                }
            }
        }
    };
}

Manfest.xml

< ?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mobilemerit.usbhost"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses -feature android:name="android.hardware.usb.host"></uses>
    <uses -sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="19"></uses>
 
<application android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="com.mobilemerit.usbhost.MainActivity"
            android:label="@string/app_name" >
            <intent -filter>
                <action android:name="android.intent.action.MAIN"></action>
 
                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent>
        </activity>
    </application>
 
</manifest>


Solution

  • In Android Studio you can choose "Import Project" and select the folder that the USB example files are placed. Select the top level folder. After that Android Studio will build you the project. If you encounter errors or Android Studio needs to download files you should let it do that. Then click the menu: Build -> Rebuild Project. All done!

    Here's the file built and ready to run: Working AS USB example Courtesy of mobilemerit.

    Here's a screenshot takes from Android Studio while the app is running on my Samsung Note 3: Picture of USB example running on Note 3

    PS. I am in no way affiliated with mobilemerit.