Я смог прочитать данные из /dev/ttyACM0 с помощью команды cat.
Я создал базовое приложение с кнопками и текстовым полем просмотра в качестве счетчика, теперь я пытаюсь получить данные USB от поворотной ручки и показать их в текстовом поле просмотра в виде счетчика или символов.
Я написал код ниже после прочтения некоторых онлайн-блогов и руководства по студии Android.
https://developer.android.com/develop/c ... y/usb/host
когда я пытаюсь прочитайте данные, используя приведенный ниже код, я мог видеть вызов requestPermission(), но когда я даю разрешение, BroadcastReciever() не вызывается и ничего не происходит.
MainActivity.kt
Код: Выделить всё
package com.example.middisplaz
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
class MainActivity : AppCompatActivity() {
@SuppressLint("CutPasteId")
private val ACTION_USB_PERMISSION = "com.example.middisplaz.USB_PERMISSION"
private var usbManager: UsbManager? = null
private var device: UsbDevice? = null
private var connection: UsbDeviceConnection? = null
private val usbReceiver = object : BroadcastReceiver() {
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (ACTION_USB_PERMISSION == action) {
synchronized(this) {
val device = intent.getParcelableExtra(
UsbManager.EXTRA_DEVICE,
UsbDevice::class.java
)
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED,
false
)
) {
device?.apply {
setupDevice(this)
}
} else {
Log.d("USB", "Permission denied for device $device")
}
}
}
}
}
private fun setupDevice(device: UsbDevice) {
val usbInterface = device.getInterface(0)
val endpoint = usbInterface.getEndpoint(0)
connection = usbManager?.openDevice(device)
connection?.claimInterface(usbInterface, true)
Thread {
val buffer = ByteArray(64)
while (true) {
val bytesRead = connection?.bulkTransfer(/* endpoint = */ endpoint,
/* buffer = */ buffer, /* length = */
buffer.size, /* timeout = */ 1000
)
if (bytesRead != null && bytesRead > 0) {
val receiveData = String(buffer, 0, bytesRead)
Log.d("USB", "Received: $receiveData")
}
}
}.start()
}
@SuppressLint("NewApi")
override fun onCreate(savedInstanceState: Bundle?) {
var counter = 0
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val text = findViewById(R.id.counterValue)
val plusButton = findViewById(R.id.plusBtn)
plusButton.setOnClickListener {
counter++
text.text = counter.toString()
}
val minusButton = findViewById(R.id.minusBtn)
minusButton.setOnClickListener {
counter--
text.text = counter.toString()
}
val windowInsetsController =
WindowCompat.getInsetsController(window, window.decorView)
// Configure the behavior of the hidden system bars.
windowInsetsController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
usbManager = getSystemService(USB_SERVICE) as UsbManager
val filter = IntentFilter().apply {
addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
addAction(ACTION_USB_PERMISSION)
}
registerReceiver(usbReceiver, filter, RECEIVER_NOT_EXPORTED)
val deviceList = usbManager!!.deviceList
for (deviceEntry in deviceList.values) {
Log.d("USB", "Device name : ${deviceEntry.deviceName}")
if (deviceEntry.deviceClass == UsbConstants.USB_CLASS_COMM) {
device = deviceEntry
requestPermission(device!!)
break
}
}
}
@SuppressLint("MutableImplicitPendingIntent")
private fun requestPermission(device: UsbDevice) {
val permissionIntent = PendingIntent.getBroadcast(
this, 0, Intent(ACTION_USB_PERMISSION),
PendingIntent.FLAG_IMMUTABLE
)
usbManager!!.requestPermission(device, permissionIntent)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(usbReceiver)
connection?.close()
}
}
Код: Выделить всё
Спасибо
Попробовал указанный выше код.
Подробнее здесь: https://stackoverflow.com/questions/790 ... android-14
Мобильная версия