Android App for USB Host (with source code)


 

Download APK Download Source Code Contact Us

 

When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, and enumerates connected USB devices. USB host mode is supported in Android 3.1 and higher.

Before you begin, it is important to understand the classes that you need to work with.

In most situations, you need to use all of these classes (UsbRequest is only required if you are doing asynchronous communication) when communicating with a USB device. In general, you obtain a UsbManager to retrieve the desired UsbDevice. When you have the device, you need to find the appropriate UsbInterface and the UsbEndpoint of that interface to communicate on. Once you obtain the correct endpoint, open aUsbDeviceConnection to communicate with the USB device.

Note:- In most of old phone USB hosting is not provided, only in new mobiles have inbuilt feature of USB Hosting. If you want to used it in old phones than you need to root your phone but it’s not advisable better you use USB Accessory in place of USB Host . it is similar to USB Host.

Here is a sample example to set USB Host in you android app
Layout Code: activity_main. Xml
When application is executed this is the first layout design that will run which will load width, height, load back ground details..etc.

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

Java File : MainActivity.java
MainActivity.java file in package com.mobilemerit.usbhost.
Main activity file will load design form like buttons, text view, on click functionality, display text.

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

Mainifest.xml

This is the main configuration file for USB Host android project. This xml code will load required permission and main activity by default.

< ?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>

This is a simple code to find usb connected devices. If you need to communicate with usb device means send or receive data between your phone and usb device than you can other classes and interface (UsbInterface, UsbEndpoint, UsbDeviceConnection, UsbRequest).

Android App for USB Host
Android App for USB Host
Android App for USB Host

Download APK Download Source Code Contact Us

Posted in All Tutorials, Android Tutorials | Tagged | 1 Comment

One Response to Android App for USB Host (with source code)

  1. makomori says:

    OK I got this. Need to convert to hexa from integer data type. Integer.toHexString(device.getVendorId())

Leave a Reply

Your email address will not be published. Required fields are marked *

Powered By: wpnova.com