一、USB連接概述
USB(Universal Serial Bus)是一種通用的計算機介面標準,可用於連接各種外部設備,並提供高速數據傳輸功能。USB介面具有熱插拔功能,插入USB設備後,計算機會自動識別設備並載入驅動程序。在Android上,USB介面可以用於連接各種外部設備,例如滑鼠、鍵盤、攝像頭、存儲設備、手機等,實現與設備的數據傳輸和交互。
二、USB連接方式
在Android上,USB連接可以採用以下兩種方式:
1、MTP方式(Media Transfer Protocol):MTP是一種基於USB的傳輸協議,可以實現設備和計算機之間的文件傳輸。使用MTP連接,設備只能作為文件傳輸的客戶端,無法進行其他操作。
2、ADB方式(Android Debug Bridge):ADB是一種通信方式,允許計算機通過USB連接到Android設備,進行開發和調試操作,例如獲取設備的日誌信息、推送文件到設備、安裝應用程序等。
三、USB連接實現
1、USB許可權配置
在使用USB連接時,需要在AndroidManifest.xml文件中添加以下許可權:
<uses-permission android:name="android.permission.USB_PERMISSION"/>
然後在代碼中獲取USB許可權:
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"; private void getUsbPermission(UsbDevice device) { // 請求USB許可權 PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); usbManager.requestPermission(device, permissionIntent); }
獲取USB許可權需要向系統發出請求,請求結果通過廣播方式返回。
2、USB設備查詢和連接
在使用USB功能之前,需要查詢設備並建立連接。
查詢USB設備列表:
private List findUSBDeviceList() { List deviceList = new ArrayList(); // 獲取USB設備列表 for (UsbDevice device : usbManager.getDeviceList().values()) { deviceList.add(device); } return deviceList; }
建立USB連接:
private void openUSBDevice(UsbDevice device) { // 打開USB設備 usbInterface = device.getInterface(0); usbEndpointIn = usbInterface.getEndpoint(0); usbEndpointOut = usbInterface.getEndpoint(1); usbConnection = usbManager.openDevice(device); if (usbConnection != null && usbConnection.claimInterface(usbInterface, true)) { Log.d(TAG, "成功打開設備!"); } else { Log.e(TAG, "打開設備失敗!"); } }
建立連接需要先獲取USB設備列表,選擇需要連接的設備,打開設備通道,並聲明要使用的介面。
3、USB數據傳輸
USB數據傳輸可以通過輸入輸出流實現。
發送數據:
private void sendData(byte[] data) { int ret = usbConnection.bulkTransfer(usbEndpointOut, data, data.length, 1000); if (ret < 0) { Log.e(TAG, "發送數據失敗!"); } }
接收數據:
private String receiveData() { byte[] buffer = new byte[64]; int ret = usbConnection.bulkTransfer(usbEndpointIn, buffer, buffer.length, 1000); if (ret < 0) { return null; } return new String(buffer, 0, ret); }
通過bulkTransfer函數可以實現批量數據傳輸,第一個參數是傳輸的端點,第二個參數是要傳輸的數據,第三個參數是數據長度,第四個參數是超時時間。函數返回值小於0表示傳輸失敗。
四、示例代碼
以下是一個簡單的USB連接示例代碼:
public class MainActivity extends AppCompatActivity { private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"; private static final String TAG = "MainActivity"; private UsbManager usbManager; private UsbInterface usbInterface; private UsbEndpoint usbEndpointIn; private UsbEndpoint usbEndpointOut; private UsbConnection usbConnection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); usbManager = (UsbManager)getSystemService(Context.USB_SERVICE); // 註冊USB廣播接收器 IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); registerReceiver(usbReceiver, filter); // 獲取USB設備列表 List deviceList = findUSBDeviceList(); if (deviceList.isEmpty()) { Log.e(TAG, "No USB devices found!"); } else { // 選擇第一個設備進行連接 UsbDevice device = deviceList.get(0); // 請求USB許可權 getUsbPermission(device); } } private BroadcastReceiver usbReceiver = new BroadcastReceiver() { @Override 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) { // 成功獲取USB許可權,建立連接 openUSBDevice(device); } } else { Log.e(TAG, "USB permission denied!"); } } } } }; private List findUSBDeviceList() { List deviceList = new ArrayList(); // 獲取USB設備列表 for (UsbDevice device : usbManager.getDeviceList().values()) { deviceList.add(device); Log.d(TAG, "USB device found: DeviceName=" + device.getDeviceName() + ", VendorId=" + device.getVendorId() + ", ProductId=" + device.getProductId() + ", InterfaceCount=" + device.getInterfaceCount()); } return deviceList; } private void getUsbPermission(UsbDevice device) { // 請求USB許可權 PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); usbManager.requestPermission(device, permissionIntent); } private void openUSBDevice(UsbDevice device) { // 打開USB設備 usbInterface = device.getInterface(0); usbEndpointIn = usbInterface.getEndpoint(0); usbEndpointOut = usbInterface.getEndpoint(1); usbConnection = usbManager.openDevice(device); if (usbConnection != null && usbConnection.claimInterface(usbInterface, true)) { Log.d(TAG, "成功打開設備!"); // 發送數據 sendData("Hello, USB!".getBytes()); // 接收數據 String data = receiveData(); if (data != null) { Log.d(TAG, "接收到數據:" + data); } else { Log.e(TAG, "接收數據失敗!"); } } else { Log.e(TAG, "打開設備失敗!"); } } private void sendData(byte[] data) { int ret = usbConnection.bulkTransfer(usbEndpointOut, data, data.length, 1000); if (ret < 0) { Log.e(TAG, "發送數據失敗!"); } } private String receiveData() { byte[] buffer = new byte[64]; int ret = usbConnection.bulkTransfer(usbEndpointIn, buffer, buffer.length, 1000); if (ret < 0) { return null; } return new String(buffer, 0, ret); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(usbReceiver); } }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/232341.html