安卓 串口开发
上图:上码:在APP grable添加// 串口需要配合在项目build.gradle中的repositories添加maven {url "https://jitpack.io" }implementation 'com.github.licheedev.Android-SerialPort-API:serialport:1.0.1'implementation 'com.jakewharton
·
下载地址:https://download.csdn.net/download/hdhhd/76292498
上图:
上码:
在APP grable添加
// 串口 需要配合在项目build.gradle中的repositories添加 maven {url "https://jitpack.io" }
implementation 'com.github.licheedev.Android-SerialPort-API:serialport:1.0.1'
implementation 'com.jakewharton:butterknife:8.4.0'
//XRecyclerView 框架
implementation 'com.jcodecraeer:xrecyclerview:1.3.2'
在项目 geable添加
allprojects {
repositories {
google()
jcenter()
maven {url "https://jitpack.io" }
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/edit_sendvalue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="@+id/btn_sendata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:orientation="horizontal">
<EditText
android:id="@+id/edit_rend"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cursorVisible="false"
android:hint="接受数据 " />
</LinearLayout>
<Button
android:id="@+id/brn_cleanLogcat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="清除日志" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/lv_AT"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/lv_AT_logcat"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
activity:
package youli.com.example.administrator.serialport;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText mEditSendvalue;
private Button mBtnSendata, brn_cleanLogcat;
private EditText mEditRend;
private RecyclerView mLvAT, lv_AT_logcat;
private RYAdapter ryAdapter;
private RYAdapterLogcat adapterLogcat;
private List<String> list_Log = new ArrayList<>();
private MSeriaLport seriaLport;
//14个药曹uid、电压
private String[] array = new String[]{
"555901080000EAFF",
"555902080000EAFF",
"555903080000EAFF",
"555904080000EAFF",
"555905080000EAFF",
"555906080000EAFF",
"555907080000EAFF",
"555908080000EAFF",
"555909080000EAFF",
"55590A080000EAFF",
"55590B080000EAFF",
"55590C080000EAFF",
"55590D080000EAFF",
"55590E080000EAFF",
"555901090000EAFF",
"555902090000EAFF",
"555903090000EAFF",
"555904090000EAFF",
"555905090000EAFF",
"555906090000EAFF",
"555907090000EAFF",
"555908090000EAFF",
"555909090000EAFF",
"55590A090000EAFF",
"55590B090000EAFF",
"55590C090000EAFF",
"55590D090000EAFF",
"55590E090000EAFF"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setReceiver();
}
private void initView() {
mEditSendvalue = (EditText) findViewById(R.id.edit_sendvalue);
brn_cleanLogcat = (Button) findViewById(R.id.brn_cleanLogcat);
mBtnSendata = (Button) findViewById(R.id.btn_sendata);
mBtnSendata.setOnClickListener(listener);
brn_cleanLogcat.setOnClickListener(listener);
seriaLport = MSeriaLport.getSeriaLport(this);
mEditRend = (EditText) findViewById(R.id.edit_rend);
mLvAT = findViewById(R.id.lv_AT);
mLvAT.setLayoutManager(new LinearLayoutManager(this));
ryAdapter = new RYAdapter(this, Array.getList_AT(), Array.getList_value());
mLvAT.setAdapter(ryAdapter);
ryAdapter.getMSeriaLportAT(new RYAdapter.MSeriaLportAT() {
@Override
public void setOnClickListenerAdapter(int position) {
final String ATValue = Array.getList_AT().get(position);
Log.i("TAG", "发送指令:" + ATValue);
new Thread(new Runnable() {
@Override
public void run() {
seriaLport.getWriteSeriaLportData(ATValue);
}
}).start();
ryAdapter.getPosition(position);
ryAdapter.notifyDataSetChanged();
}
});
lv_AT_logcat = findViewById(R.id.lv_AT_logcat);
lv_AT_logcat.setLayoutManager(new LinearLayoutManager(this));
adapterLogcat = new RYAdapterLogcat(this, list_Log);
lv_AT_logcat.setAdapter(adapterLogcat);
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sendata:
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < array.length; i++) {
Log.i("TAG", "发送指令:" + array[i]);
seriaLport.getWriteSeriaLportData(array[i]);
}
}
}).start();
// mEditSendvalue.setText("555902080000EAFF");
// String AT = mEditSendvalue.getText().toString().trim();
// seriaLport.getWriteSeriaLportData(AT);
break;
case R.id.brn_cleanLogcat:
list_Log.clear();
adapterLogcat.notifyDataSetChanged();
break;
default:
break;
}
}
};
private ReceiverData receiverData;
public static final String RECEIVER_REFRESH = "WWW.ANDROID.RECEIVER_REFRESH";
//注册广播
public void setReceiver() {
if (receiverData == null) {
receiverData = new ReceiverData();
IntentFilter filter = new IntentFilter();
filter.addAction(RECEIVER_REFRESH);
registerReceiver(receiverData, filter);
}
}
//注销广播
public void setCancellationReceiver() {
if (receiverData != null) {
unregisterReceiver(receiverData);
}
}
String value;
private class ReceiverData extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case RECEIVER_REFRESH:
value = intent.getStringExtra(RECEIVER_REFRESH);
mEditRend.setText(value);
list_Log.add(value);
adapterLogcat.notifyDataSetChanged();
//刷新后定位最后一条数据
int itemCount = adapterLogcat.getItemCount() - 1;
lv_AT_logcat.smoothScrollToPosition(itemCount);
default:
Log.i("TAG", "接受指令:" + value);
break;
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
setCancellationReceiver();
seriaLport.getClose();
}
}
MSeriaLport串口控制类:
package youli.com.example.administrator.serialport;
import android.content.Context;
import android.content.Intent;
import android.serialport.SerialPort;
import android.serialport.SerialPortFinder;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class MSeriaLport extends SerialPort {
private static Context contexts;
//device物理地址错误会报错 Caused by: java.lang.SecurityException
private static String device = "/dev/ttyS1"; //串口地址
private static int baudrate = (int) 115200l; // 波特率
private static int flags = 0; //奇偶校验
private boolean flag = true;
private static InputStream inputStream;
private static OutputStream outputStream;
private static MSeriaLport seriaLport;
public static MSeriaLport getSeriaLport(Context context) {
contexts = context;
if (seriaLport == null) {
try {
seriaLport = new MSeriaLport(new File(device), baudrate, flags);
} catch (IOException e) {
e.printStackTrace();
}
}
return seriaLport;
}
static Thread sp_Thread;
/**
* 打开串口
*
* @param device 串口的具体物理地址
* @param baudrate
* @param flags
* @throws SecurityException
* @throws IOException
*/
public MSeriaLport(File device, int baudrate, int flags) throws IOException {
super(device, baudrate, flags);
getRendSeriaLportData(); //读取数据
}
private String test;
/**
* 发送串口数据
*/
public void getWriteSeriaLportData(String valueS) {
outputStream = this.getOutputStream();
try {
while (!TextUtils.isEmpty(test)) {
Thread.sleep(100);
}
test = valueS;
byte[] b = utils.hexStr2bytes(valueS);
outputStream.write(b);
int abc = 0;
while (!AT_value.contains("56") && !AT_value.contains("EAFF")) {
Thread.sleep(200);
abc++;
if (abc == 10) {
break;//超时
}
}
Log.i("TAG"," AT接受:"+ AT_value);
AT_value = "";
test = "";
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private StringBuffer buffer = new StringBuffer();
private String valeu;
private String AT_value = "";
/**
* 读取串口数据
*/
private void getRendSeriaLportData() {
inputStream = this.getInputStream();
sp_Thread = new Thread(new Runnable() {
@Override
public void run() {
while (flag) {
int index;
try {
Thread.sleep(100);
index = inputStream.available();
if (index > 0) {
byte[] bytes = new byte[index];
inputStream.read(bytes, 0, bytes.length);
valeu = utils.bytes2HexStr(bytes);
// Log.i("TAG", "读取到的数据:" + valeu);
buffer = buffer.append(valeu);
AT_value = buffer.toString();
if (AT_value.contains("56") && AT_value.contains("EAFF")) {
sendReceive(AT_value);
buffer = new StringBuffer();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
sp_Thread.start();
}
/**
* 发送广播
*
* @param value
*/
void sendReceive(String value) {
Intent intent = new Intent();
intent.setAction(MainActivity.RECEIVER_REFRESH);
intent.putExtra(MainActivity.RECEIVER_REFRESH, value);
contexts.sendBroadcast(intent);
}
/**
* 关闭流
*/
public void getClose() {
if (seriaLport != null) {
seriaLport.close();
flag = false;
}
}
/**
* 获取在设备目录下的,所有串口的具体物理地址
* /dev/ttyGS3
* /dev/ttyGS2
* /dev/ttyGS1
* /dev/ttyGS0
* /dev/ttyS0
* /dev/ttyS1
*/
public static String[] getAllDevicesPath() {
String[] devices = new SerialPortFinder().getAllDevicesPath();
for (int i = 0; i < devices.length; i++)
Log.i("TAG", devices[i]);
return devices;
}
}
东西不多 ,没啥可说的。有不会的小伙伴可以提问。
更多推荐
已为社区贡献6条内容
所有评论(0)