Видео демонстрация: https://youtu.be/3HyXKzhbPP8
При нажатии на onClickStop - это вызывает serialPort для закрытия. Я проверил, если эта функция вызывается с помощью тоста. Из-за использования кабеля OTG я не могу просмотреть logcat. Вот моя функция onClickStop
fun onClickStop(@Suppress("UNUSED_PARAMETER") view: View?) {
setUiEnabled(false)
Toast.makeText(this, "Hi there! This is a Toast.", Toast.LENGTH_SHORT).show()
serialPort!!.close()
tvAppend(textView, "\nSerial Connection Closed! \n")
}
У меня также есть проблема с моей seekBar. Максимальная длина бара устанавливается в размере arrayList. В массиве listList содержатся данные, полученные с моей платы Arduino. Я использую свой Seekbar для фильтрации через arrayList и печатаю значение и вычисленный цвет в TextView ниже. Это работает отлично, в основном это работает как воспроизведение того, что было записано. Хотя, если моя панель поиска открыта до самого конца панели - мое приложение вылетает. Вот мой код поискаBar
private fun timescale(data: String) {
storeList.add(data.toInt())
seekBar!!.max = storeList.size
textView!!.text = storeList.size.toString()
seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
seekText!!.text = storeList[progress].toString()
if (storeList[progress] >= 1000) {
seekText?.setBackgroundColor(Color.GREEN)
} else if (storeList[progress] >= 750) {
seekText?.setBackgroundColor(Color.YELLOW)
} else if (storeList[progress] >= 500) {
seekText?.setBackgroundColor(Color.rgb(255, 165, 0))
} else if (storeList[progress] >= 250) {
seekText?.setBackgroundColor(Color.RED)
} else if (storeList[progress] >= 0) {
seekText?.setBackgroundColor(Color.BLACK)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
}
Вот остаток моего кода и XML
package com.example.surf10
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import android.os.Handler
import android.util.Log
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import com.felhr.usbserial.UsbSerialDevice
import com.felhr.usbserial.UsbSerialInterface
import com.felhr.usbserial.UsbSerialInterface.UsbReadCallback
import kotlinx.android.synthetic.main.activity_surfboard.*
import java.io.UnsupportedEncodingException
import java.util.*
import kotlin.text.Charsets.UTF_8
import kotlin.collections.ArrayList as ArrayList1
class Surfboard : AppCompatActivity() {
val ACTION_USB_PERMISSION = "com.surf10.USB_PERMISSION"
var startButton: Button? = null
var sendButton: Button? = null
var stopButton: Button? = null
var textView: TextView? = null
var textView2: TextView? = null
var seekText: TextView? = null
var statusText: TextView? = null
var usbManager: UsbManager? = null
var device: UsbDevice? = null
var serialPort: UsbSerialDevice? = null
var connection: UsbDeviceConnection? = null
var reading: String? = null
var seekBar: SeekBar? = null
var storeList = arrayListOf<Int>()
var mCallback = UsbReadCallback { arg0 ->
//Defining a Callback which triggers whenever data is read.
//var data: String? = null
try {
var data = String(arg0, UTF_8)
testing(data)
//tvAppend(textView, data)
timescale(data)
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
}
}
private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
//Broadcast Receiver to automatically start and stop the Serial connection.
override fun onReceive(
context: Context,
intent: Intent
) {
if (intent.action == ACTION_USB_PERMISSION) {
val granted = intent.extras!!.getBoolean(
UsbManager.EXTRA_PERMISSION_GRANTED
)
if (granted) {
connection = usbManager!!.openDevice(device)
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection)
if (serialPort != null) {
if (serialPort!!.open()) { //Set Serial Connection Parameters.
setUiEnabled(true)
serialPort!!.setBaudRate(9600)
serialPort!!.setDataBits(UsbSerialInterface.DATA_BITS_8)
serialPort!!.setStopBits(UsbSerialInterface.STOP_BITS_1)
serialPort!!.setParity(UsbSerialInterface.PARITY_NONE)
serialPort!!.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF)
serialPort!!.read(mCallback)
tvAppend(statusText, "Serial Connection Opened!\n")
} else {
Log.d("SERIAL", "PORT NOT OPEN")
}
} else {
Log.d("SERIAL", "PORT IS NULL")
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED")
}
} else if (intent.action == UsbManager.ACTION_USB_DEVICE_ATTACHED) {
onClickStart(startButton)
} else if (intent.action == UsbManager.ACTION_USB_DEVICE_DETACHED) {
onClickStop(stopButton)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_surfboard)
usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
startButton = findViewById<View>(R.id.buttonStart) as Button
sendButton = findViewById<View>(R.id.activate) as Button
stopButton = findViewById<View>(R.id.deactivate) as Button
textView = findViewById<View>(R.id.textView) as TextView
textView2 = findViewById<View>(R.id.test) as TextView
seekText = findViewById<View>(R.id.seekText) as TextView
statusText = findViewById<View>(R.id.statusText) as TextView
seekBar = findViewById<View>(R.id.seekBar) as SeekBar
setUiEnabled(false)
val filter = IntentFilter()
filter.addAction(ACTION_USB_PERMISSION)
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
registerReceiver(broadcastReceiver, filter)
}
fun setUiEnabled(bool: Boolean) {
startButton!!.isEnabled = !bool
sendButton!!.isEnabled = bool
stopButton!!.isEnabled = bool
textView!!.isEnabled = bool
}
fun onClickStart(@Suppress("UNUSED_PARAMETER") view: View?) {
val usbDevices = usbManager!!.deviceList
if (!usbDevices.isEmpty()) {
var keep = true
for ((_, value) in usbDevices) {
device = value
val deviceVID = device!!.vendorId
if (deviceVID == 0x2341) //Arduino Vendor ID
{
val pi =
PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_PERMISSION), 0)
usbManager!!.requestPermission(device, pi)
keep = false
} else {
connection = null
device = null
}
if (!keep) break
}
}
}
fun onClickSend(@Suppress("UNUSED_PARAMETER") view: View?) {
val string = "g"
serialPort!!.write(string.toByteArray())
//tvAppend(textView, "\nData Sent : " + string)
var circuit = 0
for (i in 1..100) {
Handler().postDelayed({
serialPort!!.write(string.toByteArray())
}, 1000)
}
}
fun onClickStop(@Suppress("UNUSED_PARAMETER") view: View?) {
setUiEnabled(false)
Toast.makeText(this, "Hi there! This is a Toast.", Toast.LENGTH_SHORT).show()
serialPort!!.close()
tvAppend(textView, "\nSerial Connection Closed! \n")
}
private fun tvAppend(tv: TextView?, text: CharSequence) {
runOnUiThread {
tv!!.append(text)
}
}
private fun testing(data: String) {
textView2?.text = data
if (data.toInt() >= 1000) {
textView2?.setBackgroundColor(Color.GREEN)
} else if (data.toInt() >= 750) {
textView2?.setBackgroundColor(Color.YELLOW)
} else if (data.toInt() >= 500) {
textView2?.setBackgroundColor(Color.rgb(255, 165, 0))
} else if (data.toInt() >= 250) {
textView2?.setBackgroundColor(Color.RED)
} else if (data.toInt() >= 0) {
textView2?.setBackgroundColor(Color.BLACK)
}
}
private fun timescale(data: String) {
storeList.add(data.toInt())
seekBar!!.max = storeList.size
textView!!.text = storeList.size.toString()
seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
seekText!!.text = storeList[progress].toString()
if (storeList[progress] >= 1000) {
seekText?.setBackgroundColor(Color.GREEN)
} else if (storeList[progress] >= 750) {
seekText?.setBackgroundColor(Color.YELLOW)
} else if (storeList[progress] >= 500) {
seekText?.setBackgroundColor(Color.rgb(255, 165, 0))
} else if (storeList[progress] >= 250) {
seekText?.setBackgroundColor(Color.RED)
} else if (storeList[progress] >= 0) {
seekText?.setBackgroundColor(Color.BLACK)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
}
}
Вот мой XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".Surfboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/surfboard"
>
<!--Table Layout with 3 rows and each row with 3 buttons-->
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:rowCount="3"
android:columnCount="3"
android:padding="8dp"
>
<Button
android:id="@+id/buttonStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickStart"
android:text="@string/Begin"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/statusText"
android:layout_below="@+id/buttonSend"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
<!--Row 1-->
<TableRow>
<Button
android:id="@+id/b00"
style="@style/Widget.AppCompat.Button"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="8dp"
android:gravity="center"
android:background="@color/colorAccent"
android:textColor="#FFFFFF"
android:textSize="22sp" />
<Button
android:id="@+id/b01"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="8dp"
android:background="@color/colorAccent"
android:gravity="center"
android:textColor="#FFFFFF"
android:textSize="22sp" />
<Button
android:id="@+id/b02"
android:layout_width="80dp"
android:layout_height="80dp"
android:textSize="22sp"
android:textColor="#FFFFFF"
android:background="@color/colorAccent"
android:gravity="center"
android:layout_margin="8dp"
style="@style/Widget.AppCompat.Button"
/>
</TableRow>
<Button
android:id="@+id/activate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/activate"
android:onClick="onClickSend"
tools:ignore="OnClick" />
<Button
android:id="@+id/deactivate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickStop"
android:text="@string/deactivate"/>
<TextView
android:id="@+id/test"
android:layout_width="80dp"
android:layout_height="80dp"
android:gravity="center"
android:textSize="32dp"
android:background="#E0E0E0"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_below="@+id/buttonSend"
android:layout_marginTop="20dp"
android:background="#E0E0E0" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:progressDrawable="@drawable/seek_bar"
android:thumb="@drawable/seek_thumb"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/seekText"
android:layout_below="@+id/buttonSend"
android:layout_marginTop="20dp"
android:background="#E0E0E0" />
</TableLayout>
</RelativeLayout>