创建C++工程
把工程由android转换为project状态下:
1),把android_serialport_qpi复制到main_java目录下;
2),把jin复制到main目录下,包括:
1,Android.mk;
2,Application.mk
3,gen_serialPort_h.sh
4,SrtialPort.c
5,SerialPort.h
3),在Gradle添加依赖:
externalNativeBuild {
ndkBuild {
path file('src/main/jni/Android.mk')
}
}
4),在Gradle添加依赖后删除如下:
externalNativeBuild {
// cmake {
// path file('src/main/cpp/CMakeLists.txt')
// version '3.10.2'
// }
ndkBuild {
path file('src/main/jni/Android.mk')
}
}
5),删除MainActivity.java三个地方:
1),// static {
// System.loadLibrary ("com232_240321");
//
2),// tv.setText(stringFromJNI());
3),// public native String stringFromJNI();
6), 1),把SerialPortUtil复制到MainActivity.java同一地方
2),在MainActivity.java创建:
public static void refreshTextView(String str){
}
package com.example.com232_240321;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.com232_240321.databinding.ActivityMainBinding;
import java.io.UnsupportedEncodingException;
//能成功连接电脑,发送接收数据
//https://blog.youkuaiyun.com/cau_eric/article/details/90712496?spm=1001.2101.3001.6650.4&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-4-90712496-blog-51066370.235%5Ev43%5Epc_blog_bottom_relevance_base9&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-4-90712496-blog-51066370.235%5Ev43%5Epc_blog_bottom_relevance_base9&utm_relevant_index=9
public class MainActivity extends AppCompatActivity {
private EditText et1,et2;
private Button btn1,btn2,btn3;
private static TextView tv1,tv2,tv3,tv4;
private static int i = 0;
private Handler handler;
// Used to load the 'com232_240321' library on application startup.
// static {
// System.loadLibrary("com232_240321");
// }
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
initbutton();
SerialPortUtil.openSrialPort();//
SerialPortUtil.sendSerialPort("1234567");
SerialPortUtil.sendSerialPort("240214d");
// tv.setText("发送字符成功");
SerialPortUtil.sendSerialPort("邵建雄串口测试中");
// back_init();
// Example of a call to a native method
TextView tv = binding.sampleText;
// tv.setText(stringFromJNI());
}
private void initbutton() {
btn3 = findViewById(R.id.btn3);
et1 = findViewById(R.id.et1);
et2 = findViewById(R.id.et2);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
//tv1 = findViewById(R.id.tv1);
tv2 = findViewById(R.id.tv2);
tv3 = findViewById(R.id.tv3);
tv4 = findViewById(R.id.tv4);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn3.setText("按键一按下");
clr_button_text();//按键工能提示清除
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn3.setText("按键二按下");
clr_button_text();//按键工能提示清除
}
});
}
/**
* A native method that is implemented by the 'com232_240321' native library,
* which is packaged with this application.
*/
// public native String stringFromJNI();
public static void refreshTextView(String str ){
tv2.setText("");
if(i % 2 == 0){
tv2.setTextColor(0x7f040000);
}
else{
tv2.setTextColor(0xffff4752);
}
if( ++i >2){i =0;}
tv2.setText(str);
}
public static void refreshTextView_test( byte[] readData ,int byte_size) {//显示原始数据和中文
byte[] readData_r = new byte[byte_size];//只要有用数据部分,如果每次都要转换1024次,很耗时,显示会出错
tv3.setText("");
tv4.setText("");
String temp1 = "";
for (int i = 0; i < byte_size; i++) {
Log.i("test", "自己接收到原来初始数据: " + i +"= "+ readData[i]);
temp1 += "" + readData[i];
readData_r[i] = readData[i];//
}
tv3.setText( temp1);
String gbk_sout = "";
try {//转换中文输出
gbk_sout = new String(readData_r,"GBK");
tv4.setText( gbk_sout);
Log.i("test", "转换后中文字符= " + gbk_sout);
} catch (UnsupportedEncodingException e) {
tv4.setText( "转换出错");
e.printStackTrace();
}finally {
}
// //batt_test.write_batt_data(gbk_sout);//把电池数据显示
// Batt_test batt_test = new Batt_test();
// //batt_test.write_batt_data(gbk_sout);
// String[] strarray = gbk_sout.split("[,]");//把字符串,以","分隔为一个字符串数组,
// if (strarray[0].equals("55") && strarray[1].equals("55") && strarray[2].equals("01") && strarray[3].equals("01")) {
// try {
// My_chaxun_chongdian.Query_charging(gbk_sout);//
// } catch (Exception e) {
// Log.i("test", "转换后中文字符跳转出错 " + gbk_sout);
// e.printStackTrace();
// }
// }
// if (strarray[0].equals("55") && (strarray[1].equals("aa") || strarray[1].equals("AA"))){
// try {
// batt_test.rx_string_to_batt_16_v_a_data(gbk_sout);//电池16个数据,总量,充电放电解译OK
// } catch (Exception e) {
// Log.i("test", "转换后中文字符跳转出错 " + gbk_sout);
// e.printStackTrace();
// }
// }
//
}
private void clr_button_text(){//按键工能提示清除
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
btn3.setText("功能提示");
}
},1 * 1000);//3秒清除工能提示字符
}
private void delay(int ms){//延时函数
try {
Thread.currentThread();
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
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">
<TextView
android:id="@+id/sample_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="串口240321测试..."
android:textSize="25sp"
/>
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="功能提示"
android:layout_marginLeft="10dp"
android:textSize="25sp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="请输入要发送的数字"
android:id="@+id/et1"/>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_marginLeft="8dp"
android:hint="请输入要发送的数字"
android:id="@+id/et2"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/btn1"
android:text="发送a"
android:textAllCaps="false"
android:layout_marginLeft="5dp"
android:textSize="30sp"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/btn2"
android:textAllCaps="false"
android:layout_marginLeft="5dp"
android:text="发送b"
android:textSize="30sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="显示原来的数据 "
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="接收到的数据显示"
android:textColor="#FF5722"
android:id="@+id/tv2"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="显示原始的数据 "
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="接收到的原始数据显示 "
android:textColor="#2285FF"
android:id="@+id/tv3"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="显示转换中文后 "
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="接收到的中文显示"
android:textColor="#592604"
android:id="@+id/tv4"
/>
</LinearLayout>
</LinearLayout>
package com.example.com232_240214ee;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android_serialport_api.SerialPort;
/**
* Created by Warwee on 2017/6/6.
*/
public class SerialPortUtil {
public static SerialPort serialPort = null;
public static InputStream inputStream = null;
public static OutputStream outputStream = null;
public static Thread receiveThread = null;
public static boolean flag = false;
public static String serialData;
/**
* 打开串口的方法
*/
public static void openSrialPort() {
Log.i("test", "打开串口");
try {
//serialPort = new SerialPort(new File("/dev/"+ IConstant.PORT),IConstant.BAUDRATE,0);
serialPort = new SerialPort(new File("/dev/" + "ttyMT2"), 9600, 0);//ttyMT0
Log.d("SerialPort", "三程序来到这里了... " );
//获取打开的串口中的输入输出流,以便于串口数据的收发
inputStream = serialPort.getInputStream();
Log.d("SerialPort", "程序来到取输入流这里了... " );
outputStream = serialPort.getOutputStream();
Log.d("SerialPort", "程序来到取输出流这里了... " );
flag = true;
receiveSerialPort();
Log.d("SerialPort", "程序来到最后一步这里了... " );
} catch (IOException e) {
Log.i("test", "无法进行_打开串口...");
e.printStackTrace();
}finally {
Log.i("test", "已以是打开串口了..胜利在望...");
}
}
/**
* 关闭串口的方法
* 关闭串口中的输入输出流
* 然后将flag的值设为flag,终止接收数据线程
*/
public static void closeSerialPort() {
Log.i("test", "关闭串口");
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
flag = false;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发送串口数据的方法
*
* @param data 要发送的数据
*/
public static void sendSerialPort(String data) {
Log.i("test", "发送串口数据");
try {
byte[] sendData = data.getBytes();
outputStream.write(sendData);
outputStream.flush();
Log.i("test", "串口数据发送成功");
} catch (IOException e) {
e.printStackTrace();
Log.i("test", "串口数据发送失败");
}
}
/**
* 接收串口数据的方法
*/
public static void receiveSerialPort() {
Log.i("test", "接收串口数据");
if (receiveThread != null)
return;
/*定义一个handler对象要来接收子线程中接收到的数据
并调用Activity中的刷新界面的方法更新UI界面
*/
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
MainActivity.refreshTextView(serialData);
}
}
};
/*创建子线程接收串口数据
*/
receiveThread = new Thread() {
@Override
public void run() {
while (flag) {
try {
byte[] readData = new byte[1024];
if (inputStream == null) {
return;
}
int size = inputStream.read(readData);
if (size > 0 && flag) {
serialData = new String(readData, 0, size);
Log.i("test", "接收到串口数据:" + serialData);
/*将接收到的数据封装进Message中,然后发送给主线程
*/
handler.sendEmptyMessage(1);//这里如果红了,就删除重新import
Thread.sleep(1000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
//启动接收线程
receiveThread.start();
}
}