package com.yw.sdkdemo.serial;
|
|
import static com.yw.serialport.SerialPortManager.DATA_BIT_8;
|
|
import android.os.Bundle;
|
import android.os.RemoteException;
|
import android.util.Log;
|
import android.view.View;
|
import android.widget.Button;
|
import android.widget.Toast;
|
|
import androidx.annotation.Nullable;
|
import androidx.appcompat.app.AppCompatActivity;
|
|
import com.yw.sdkdemo.R;
|
import com.yw.serialport.Port;
|
import com.yw.serialport.SerialPortManager;
|
|
|
/**
|
* Created by xushuang on 2024/5/10
|
* E-mail: mitgic92@gmail.com
|
* Description:
|
*/
|
public class SerialActivity extends AppCompatActivity implements View.OnClickListener {
|
private Button bt_open;
|
private Button bt_close;
|
private Button bt_send;
|
private static final String TAG = SerialActivity.class.getSimpleName();
|
|
@Override
|
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
super.onCreate(savedInstanceState);
|
setContentView(R.layout.activity_serial_port);
|
|
initView();
|
initListener();
|
}
|
|
private void initView() {
|
bt_open = (Button) findViewById(R.id.bt_open);
|
bt_close = (Button) findViewById(R.id.bt_close);
|
bt_send = (Button) findViewById(R.id.bt_send);
|
}
|
|
private SerialPortManager.Listener listener = new SerialPortManager.Listener() {
|
@Override
|
public void onData(Port port, byte[] data, int len) throws RemoteException {
|
Log.d(TAG, "onData: " + new String(data));
|
}
|
};
|
|
private void initListener() {
|
bt_open.setOnClickListener(this);
|
bt_close.setOnClickListener(this);
|
bt_send.setOnClickListener(this);
|
// SerialPortManager.getInstance().setBaudrate(Port.PORT1_T4,9600);
|
SerialPortManager.getInstance().register(Port.PORT1_T4, listener);
|
}
|
|
@Override
|
protected void onDestroy() {
|
super.onDestroy();
|
SerialPortManager.getInstance().unregister(Port.PORT1_T4, listener);
|
}
|
|
@Override
|
public void onClick(View v) {
|
switch (v.getId()) {
|
case R.id.bt_open:
|
boolean result = SerialPortManager.getInstance().open(Port.PORT1_T4, 9600, SerialPortManager.Parity.NoParity,
|
DATA_BIT_8, SerialPortManager.StopBits.OneStopBit, SerialPortManager.FlowCtrl.NoFlowCtrl);
|
Toast.makeText(this, result ? "打开成功" : "打开失败", Toast.LENGTH_SHORT).show();
|
break;
|
case R.id.bt_close:
|
boolean result1 =SerialPortManager.getInstance().close(Port.PORT1_T4);
|
Toast.makeText(this, result1 ? "关闭成功" : "关闭失败", Toast.LENGTH_SHORT).show();
|
break;
|
|
case R.id.bt_send:
|
boolean result2 =SerialPortManager.getInstance().sendData(Port.PORT1_T4, new byte[]{(byte) 0xAA, 0x01, (byte) 0xE1, 0x4A}, 4);
|
Toast.makeText(this, result2 ? "发送成功" : "发送失败", Toast.LENGTH_SHORT).show();
|
break;
|
|
}
|
}
|
|
|
}
|