Android 监听 USB 接口的插拔状态

最近在Android机顶盒上开发一个应用需要动态监听USB接口的状态,所以开始研究。

现总结实现步骤如下。

第一部分:源码实现

按照网络上搜索的大部分文章,采取动态注册监听系统广播的方式来监听USB插拔,请看下面的实现代码。
实现代码:(已经本机测试通过)
package com.example.usbdevice;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;


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.util.Log;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MyUsbActivity extends Activity {

	protected String TAG = "MyUsbActivity";
	private UsbManager mUsbManager;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IntentFilter filter = new IntentFilter();
		filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		registerReceiver(mUsbReceiver, filter);
		
		//显示当前系统插入USB设备
		mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		Toast.makeText(this.getApplicationContext(), "getDeviceList().size() = "+mUsbManager.getDeviceList().size(), Toast.LENGTH_LONG).show();
		for (UsbDevice device : mUsbManager.getDeviceList().values()) {
			Log.d(TAG, "USB Device: " + device.toString());
		}
	}

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
			String deviceName = usbDevice.getDeviceName();
			Log.e(TAG,"--- 接收到广播, action: " + action);
			if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
				Log.e(TAG, "USB device is Attached: " + deviceName);
			} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
				Log.e(TAG, "USB device is Detached: " + deviceName);
			}
		}
	};
	
	protected void onStop() {
		super.onStop();
		unregisterReceiver(mUsbReceiver);
	};
}


第二部分:需要注意的地方

在上面的实现中,如果你的Android机顶盒监听不到USB的插拔状态,

或者机顶盒明明已经USB插入了设备(摄像头或U盘之类的),但是在运行程序过程中显示的 getDeviceList().size() = 0,

则需按照如下操作:

(参考: http://stackoverflow.com/questions/11183792/android-usb-host-and-hidden-devices)

1.1 新建文件:android.hardware.usb.host.xml,里面内容如下:


 

1.2 用adb push 命令将文件android.hardware.usb.host.xml上传到你的Android设备的目录:System/etc/permissions/
1.3 在目录:System/etc/permissions/  下找到 handheld_core_hardware.xml 或者 tablet_core_hardware.xml
并在文件的中添加:
1.4 重启Android机顶盒

















你可能感兴趣的:(JAVA,android,USB)