要实现Android手机与Android Things之间的USB通信,可以按照以下步骤进行:
public class UsbPermissionActivity extends Activity {
private static final String ACTION_USB_PERMISSION = "com.example.USB_PERMISSION";
private PendingIntent mPermissionIntent;
private UsbManager mUsbManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
checkUsbDevice();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mUsbReceiver);
}
private void checkUsbDevice() {
HashMap deviceList = mUsbManager.getDeviceList();
Iterator deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
if (device.getVendorId() == YOUR_VENDOR_ID && device.getProductId() == YOUR_PRODUCT_ID) {
mUsbManager.requestPermission(device, mPermissionIntent);
break;
}
}
}
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) {
// USB设备权限已获取,可以进行USB通信
// 在这里启动与Android Things的通信逻辑
}
} else {
// 用户拒绝了USB设备的权限请求
}
}
}
}
};
}
dependencies {
implementation 'com.github.mik3y:usb-serial-for-android:4.5.0'
}
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
...
// 枚举并连接USB设备
private void enumerateAndConnectUsbDevice() {
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbSerialDriver driver = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager).get(0);
UsbDeviceConnection connection = usbManager.openDevice(driver.getDevice());
UsbSerialPort port = driver.getPorts().get(0);
try {
port.open(connection);
port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
startSerialCommunication(port);
} catch (IOException e) {
e.printStackTrace();
}
}
// 开始串口通信
private void startSerialCommunication(UsbSerialPort port) throws IOException {
SerialInputOutputManager manager = new SerialInputOutputManager(port, serialListener);
Executors.newSingleThreadExecutor().submit(manager);
}
//