Android USB Communication Implementation Tutorial

In modern mobile devices, USB interfaces are widely used in peripheral device connections in different fields, such as printers, cameras, mobile phone accessories, etc. This article will introduce how to implement USB communication in Android applications for data interaction with external devices.

foreword

Before we start, we need to clarify some prerequisites and requirements:

  1. Hardware device: an Android device that supports USB Host mode, and an external USB device compatible with the device.
  2. Development environment: The Android Studio development environment is set up.
  3. USB permission: Add the USB permission declaration in the AndroidManifest.xml file.
  4. USB Driver: Make sure the external USB device has a compatible USB driver.

Step 1: Add USB permission statement and feature statement

AndroidManifest.xmlAdd the following permission and attribute declarations to the file :

<uses-permission android:name="android.permission.USB_PERMISSION" />

<uses-feature android:name="android.hardware.usb.host" />
<uses-feature android:name="android.hardware.usb.accessory" android:required="false" />

These declarations will ensure that our application gets the necessary permissions to communicate with the USB device.

Step 2: Write USB communication code

First, in MainActivity.java, import the required classes and packages:

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.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.HashMap;
import java.util.Iterator;

Next, MainActivityadd the following member variables to the class:

private static final String TAG = "USB_COMMUNICATION";

private static final String ACTION_USB_PERMISSION = "com.example.usbcommunication.USB_PERMISSION";
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;

private PendingIntent permissionIntent;
private boolean permissionGranted = false;

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 usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (usbDevice != null) {
                        // 用户已授权访问USB设备
                        connectUsbDevice(usbDevice);
                    }
                } else {
                    Log.d(TAG, "用户未授权访问USB设备");
                }
            }
        }
    }
};

In onCreatethe method, initialize the USB manager ( UsbManager) and broadcast receivers for permission requests, and register the broadcast receivers:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(usbReceiver, filter);
}

In onResumethe method, get a list of connected USB devices and ask the user for access:

@Override
protected void onResume() {
    super.onResume();

    // 获取已连接的USB设备列表
    HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    if (deviceIterator.hasNext()) {
        device = deviceIterator.next();
        usbManager.requestPermission(device, permissionIntent);
    } else {
        Log.d(TAG, "没有找到已连接的USB设备");
    }
}

In connectUsbDevicethe method, open the device connection and perform USB communication operations:

private void connectUsbDevice(UsbDevice usbDevice) {
    if (usbDevice == null) {
        return;
    }

    connection = usbManager.openDevice(usbDevice);
    if (connection != null) {
        // 在此处执行USB通信操作
        Log.d(TAG, "USB设备已连接");
    } else {
        Log.d(TAG, "无法打开USB设备连接");
    }
}

Finally, in onPausethe method, close the device connection:

@Override
protected void onPause() {
    super.onPause();
    if (connection != null) {
        connection.close();
    }
}

Summarize

This article describes how to implement USB communication in Android applications. We first AndroidManifest.xmladded the required USB permission and feature declarations to the file. Then, MainActivity.javathe USB communication code is written in , including operations such as initializing the USB manager, requesting permission, and opening the device connection. Finally, we also need to handle USB device connection and disconnection appropriately.

Please note that this article only provides a simplified example, the actual USB communication implementation may require more error handling and exception checking. Once connected, you can connectiondo actual USB communication operations through the object, such as reading or writing data.

I hope this article is helpful to you, welcome to leave a message to discuss and ask questions!

Guess you like

Origin blog.csdn.net/CHEN_ZL0125/article/details/131570600