1+ package com .boylab .example ;
2+
3+ import androidx .appcompat .app .AppCompatActivity ;
4+
5+ import android .os .Bundle ;
6+ import android .serialport .SerialPortManager ;
7+ import android .serialport .PortBean ;
8+ import android .view .View ;
9+ import android .widget .TextView ;
10+
11+ public class MainActivity extends AppCompatActivity {
12+
13+ private SerialPortManager serialPortManager = null ;
14+ private TextView text_Receive ;
15+
16+ @ Override
17+ protected void onCreate (Bundle savedInstanceState ) {
18+ super .onCreate (savedInstanceState );
19+ setContentView (R .layout .activity_main );
20+
21+ text_Receive = findViewById (R .id .text_Receive );
22+
23+ findViewById (R .id .btn_Init ).setOnClickListener (new View .OnClickListener () {
24+ @ Override
25+ public void onClick (View view ) {
26+ PortBean portBean = new PortBean ("/dev/ttyMT2" , 38400 , PortBean .PARITY_EVEN );
27+ SerialPortManager .DEBUG = true ;
28+ serialPortManager = new SerialPortManager (portBean , true ); //启动自动读数据
29+
30+ serialPortManager .setOnAutoReadListener (new SerialPortManager .OnAutoReadListener () {
31+ @ Override
32+ public void onAutoRead (byte [] bytes , int j ) {
33+ text_Receive .postDelayed (new Runnable () {
34+ @ Override
35+ public void run () {
36+ text_Receive .append (" 数量" +j +" " );
37+ for (int i = 0 ; i < bytes .length ; i ++) {
38+ text_Receive .append (" " );
39+ text_Receive .append (String .format ("%2x" , bytes [i ]));
40+ }
41+ }
42+ }, 0 );
43+ }
44+ });
45+ }
46+ });
47+
48+ findViewById (R .id .btn_ReadWeigh ).setOnClickListener (new View .OnClickListener () {
49+ @ Override
50+ public void onClick (View view ) {
51+ byte [] bytes = new byte []{0x01 , 0x04 , 0x00 , 0x00 , 0x00 , 0x02 , 0x71 , (byte ) 0xCB };
52+ serialPortManager .write (bytes );
53+ }
54+ });
55+ }
56+
57+ @ Override
58+ protected void onStop () {
59+ super .onStop ();
60+ serialPortManager .close ();
61+ }
62+ }
0 commit comments