Code example for UsbManager

Methods: getAccessoryList, hasPermission, openAccessory, requestPermission

0
	// Sets up all the requests for permission and attaches the USB accessory if 
	// permission is already granted 
	public boolean setup(Context context)
	{ 
		mManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
		UsbAccessory[] accessoryList = mManager.getAccessoryList();
		PendingIntent mPermissionIntent =
			PendingIntent.getBroadcast(context, 0,
					new Intent(ACTION_USB_PERMISSION), 0);
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		context.registerReceiver(mUsbReceiver, filter);
		 
		if(accessoryList != null && accessoryList[0] != null) {
			 
			mManager.requestPermission(accessoryList[0], mPermissionIntent);
			mAccessory = accessoryList[0];
			if(mManager.hasPermission(mAccessory))
			{ 
				openAccessory(mAccessory);
				return true; 
			} 
		} 
		return false; 
		 
	} 
	 
	// This loop runs all the time, looking for new data in from the Accessory 
	@Override 
	public void run() { 
		byte[] lbuffer = new byte[16384];
		while(true) { 
			try { 
				int ret = mInputStream.read(lbuffer);
				buffer.add(lbuffer, 0, ret);
				if(mMessage != null) {
					mMessage.onNew();
				} 
			} catch(IOException e) {
				try { 
					mInputStream.close();
					openAccessory(); 
				} catch(IOException e1) {
					closeAccessory(); 
					disconnectedDialog(); 
					return; 
				} catch(NullPointerException e2) {
					closeAccessory(); 
					disconnectedDialog(); 
					return; 
				} 
			} catch(NullPointerException e) {
				return; 
			} 
		} 
	} 
	 
	public void onDestroy(Context context) {
		context.unregisterReceiver(mUsbReceiver);
		Log.e(TAG, "onDestroy");
		closeAccessory(); 
	} 
	 
	public void openAccessory() { 
		Log.e(TAG, "OpenAccesory");
		openAccessory(mAccessory);
	} 
	 
	// Attaches the file streams to their pointers 
	private void openAccessory(UsbAccessory accessory) {
		mAccessory = accessory;
		mFileDescriptor = mManager.openAccessory(accessory);
		if(mFileDescriptor != null) {
			FileDescriptor fd = mFileDescriptor.getFileDescriptor();
			mInputStream = new FileInputStream(fd);
			mOutputStream = new FileOutputStream(fd);
		}