Skip to content

Commit

Permalink
🎉Release 1.2,聊天记录可保存(BETA)、聊天滚动显示、取消消息+1
Browse files Browse the repository at this point in the history
  • Loading branch information
Hny0305Lin committed Jul 1, 2024
1 parent a676127 commit a564acf
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 59 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

NLChat是专门为[小熊派BearPi的星闪代码](https://github.com/Hny0305Lin/Bearpi_Hi2821_Pico_NLChat)开发的一款基于SLE通讯的文本传输软件,目前还在开发中,敬请期待完整版向大家开放。

![IMG.SHIELD.IO](https://img.shields.io/badge/Hi2821_NLChat-Release1.2.1.2024.0701-gray.svg?colorA=007FFC&colorB=4DDDFC&style=for-the-badge)
![IMG.SHIELD.IO](https://img.shields.io/badge/Hi2821_NLChat-Release1.2.16.2024.0701-gray.svg?colorA=007FFC&colorB=4DDDFC&style=for-the-badge)

![NLChat](https://github.com/Hny0305Lin/NLChat/blob/master/DevSummary/NLChat.jpg)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,20 @@
package com.haohanyh.linmengjia.nearlink.nlchat.fun.ChatCore;

public class ChatUtils {
//这里设置的是UI相关,是否做到消息滚动展示在UI上,而不是全部展示,全部展示会占用大量UI资源
private static final boolean scrollingMessages = false; // 控制是否启用滚动消息功能
//这里设置的是数据库相关,是否做到消息保存进SQLite里
private static boolean sqlite = true; // 控制是否启用SQLite功能
//这里设置的是跟C代码相关的,白名单获取聊天文本,当这些文本出现在串口通讯里面的时候,提取这String后者即可,期间过滤掉前者和大量串口log。
private static final String PREFIX_SERVER = " Let's start chatting, This is the content of the server:";
private static final String PREFIX_CLIENT = " Let's start chatting, This is the content of the client:";
//控制是否启用滚动消息功能
public static boolean isScrollingMessages() { return scrollingMessages; }

//控制是否启用SQLite功能
public static boolean isSqlite() { return sqlite; }

public static void setSqlite(boolean sqlite) { ChatUtils.sqlite = sqlite; }

//对方为星闪服务端
public static String getPrefixServer() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Build;
Expand Down Expand Up @@ -52,6 +53,7 @@
import com.haohanyh.linmengjia.nearlink.nlchat.fun.WCHUart.WCHUartSettings;

import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.Objects;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Expand Down Expand Up @@ -89,7 +91,8 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
//手机常量,代码里设置
private final boolean MobileKeepScreenOn = false;


//调用SQLite
private SQLiteDataBaseAPP dbHelper;

/**
*
Expand Down Expand Up @@ -127,12 +130,16 @@ private void Init() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
Log.v(TAG,"Android 10以上设备是否获取最高读写文件权限?:" + Environment.isExternalStorageManager());
SQLiteDataBaseAPP.SQLiteData().CreateSql(getApplicationContext().getFilesDir().getAbsolutePath());
//既然有权限了,带上数据库初始化
if (ChatUtils.isSqlite()) {
dbHelper = SQLiteDataBaseAPP.SQLiteData();
dbHelper.CreateSql(getFilesDir().getPath());
loadMessagesFromDatabase();
}
} else {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);intent.setData(Uri.parse("package:" + this.getPackageName()));startActivityForResult(intent, 1024);
}
}

//创建CH34x设备对象
MainAPP.CH34X = new CH34xUARTDriver(
(UsbManager) getSystemService(Context.USB_SERVICE), this,
Expand Down Expand Up @@ -472,7 +479,7 @@ private void InitToOpen() {
if (MainAPP.CH34X.setConfig(WCHUartSettings.needGetData().getBaudRate(),
WCHUartSettings.needGetData().getDataBit(), WCHUartSettings.needGetData().getStopBit(),
WCHUartSettings.needGetData().getParity(), WCHUartSettings.needGetData().getFlowControl())) {
CH34xReadData();//配置成功后读数据
NearLinkChatReadData();//配置成功后读数据
HhandlerI.sendEmptyMessage(30);
SnackBarToastForDebug("请主动发送数据或静待接收数据!","谢谢",0,Snackbar.LENGTH_SHORT);
} else {
Expand All @@ -487,8 +494,38 @@ private void InitToOpen() {
}
}

public String TextOfServer = "";
private void CH34xReadData() {
private void loadMessagesFromDatabase() {
Cursor cursor = dbHelper.getAllMessages();
if (cursor != null) {
try {
while (cursor.moveToNext()) {
@SuppressLint("Range") String message = cursor.getString(cursor.getColumnIndex("message"));
@SuppressLint("Range") String sender = cursor.getString(cursor.getColumnIndex("sender"));
// 根据sender区分消息显示
if ("server".equals(sender)) {
NearLinkServerText.append(message + "\n");
} else {
NearLinkClientText.append(message + "\n");
}
}
} finally {
cursor.close();
}
}
}

private void saveMessageToDatabase(String message, String sender) {
String timestamp = dateFormat.format(new java.util.Date());
dbHelper.saveMessageToDatabase(message, sender, timestamp);
}

private StringBuilder buffer = new StringBuilder();
private LinkedList<String> serverMessageQueue = new LinkedList<>();
private LinkedList<String> clientMessageQueue = new LinkedList<>();
private static final int MAX_MESSAGES = 10; // 设置最大消息数量
@SuppressLint("SimpleDateFormat")
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
private void NearLinkChatReadData() {
//先播报星闪软件情况,已经UART接入星闪网络,再好好的处理字符
HhandlerI.sendEmptyMessage(10);
StringBuffer stringBuffer = new StringBuffer();
Expand All @@ -501,19 +538,33 @@ private void CH34xReadData() {
stringBuffer.append(processedString);
//处理完再打印到UI上
runOnUiThread(() -> {
NearLinkServerText.append(processedString);
if (NearLinkServerText.length() > 2048) {
String str = NearLinkServerText.getText().toString().substring(NearLinkServerText.getText().length() - 1024, NearLinkServerText.getText().length());
NearLinkServerText.setText("");
NearLinkServerText.append(str);
saveMessageToDatabase(processedString, "server");
if (ChatUtils.isScrollingMessages()) {
if (serverMessageQueue.size() >= MAX_MESSAGES * 3) {
serverMessageQueue.poll();
}
serverMessageQueue.add(processedString);
updateServerTextView();
} else {
NearLinkServerText.append(processedString);
if (NearLinkServerText.length() > 2048) {
String str = NearLinkServerText.getText().toString().substring(NearLinkServerText.getText().length() - 1024, NearLinkServerText.getText().length());
NearLinkServerText.setText("");
NearLinkServerText.append(str);
}
}
});
});
}

private StringBuilder buffer = new StringBuilder();
@SuppressLint("SimpleDateFormat")
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
private void updateServerTextView() {
StringBuilder allMessages = new StringBuilder();
for (String message : serverMessageQueue) {
allMessages.append(message);
}
NearLinkServerText.setText(allMessages.toString());
}

private String CH34xProcessingForReadData(String string) {
buffer.append(string);
String result = buffer.toString();
Expand Down Expand Up @@ -550,8 +601,7 @@ private String CH34xProcessingForReadData(String string) {
return "";
}

public String TextOfClient = "";
public void nearlinkChatSend(View view) {
public void NearLinkChatSendData(View view) {
HhandlerI.sendEmptyMessage(10);
byte[] to_send = StringUtils.needProcess().toByteArray(String.valueOf(EditChatSend.getText())); //以字符串方式发送
int retval = MainAPP.CH34X.writeData(to_send, to_send.length);//写数据,第一个参数为需要发送的字节数组,第二个参数为需要发送的字节长度,返回实际发送的字节长度
Expand All @@ -563,17 +613,34 @@ public void nearlinkChatSend(View view) {
runOnUiThread(new Runnable() {
@Override
public void run() {
NearLinkClientText.append(TextOfClient);
if (NearLinkClientText.length() > 2048) {
String str = NearLinkClientText.getText().toString().substring(NearLinkClientText.getText().length() - 1024, NearLinkClientText.getText().length());
NearLinkClientText.setText("");
NearLinkClientText.append(str);
saveMessageToDatabase(TextOfClient, "client");
if (ChatUtils.isScrollingMessages()) {
if (clientMessageQueue.size() >= MAX_MESSAGES) {
clientMessageQueue.poll(); // 移除最早的消息
}
clientMessageQueue.add(TextOfClient);
updateClientTextView();
} else {
NearLinkClientText.append(TextOfClient);
if (NearLinkClientText.length() > 2048) {
String str = NearLinkClientText.getText().toString().substring(NearLinkClientText.getText().length() - 1024, NearLinkClientText.getText().length());
NearLinkClientText.setText("");
NearLinkClientText.append(str);
}
}
}
});
}
}

private void updateClientTextView() {
StringBuilder allMessages = new StringBuilder();
for (String message : clientMessageQueue) {
allMessages.append(message);
}
NearLinkClientText.setText(allMessages.toString());
}

private String CH34xProcessingForSendData(String string) {
//添加时间戳
String timestamp = dateFormat.format(new java.util.Date());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
*/
package com.haohanyh.linmengjia.nearlink.nlchat.fun.SQLite;

import android.content.ContentValues;
import android.database.Cursor;

import io.requery.android.database.sqlite.SQLiteDatabase;

public class SQLiteDataBaseAPP {
Expand All @@ -20,6 +23,29 @@ public void CreateSql(String SDPath) {
sqLiteDataBaseForUser = SQLiteDatabase.openOrCreateDatabase(SDPath + "/NLChatUser.db", null);

sqLiteDataBaseForChat = SQLiteDatabase.openOrCreateDatabase(SDPath + "/NLChatChat.db",null);
createChatTable();
sqLiteDataBaseForDevice = SQLiteDatabase.openOrCreateDatabase(SDPath + "/NLChatDevice.db",null);
}

private void createChatTable() {
String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS messages (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"message TEXT, " +
"sender TEXT, " +
"timestamp TEXT);";
sqLiteDataBaseForChat.execSQL(TABLE_CREATE);
}

public void saveMessageToDatabase(String message, String sender, String timestamp) {
ContentValues values = new ContentValues();
values.put("message", message);
values.put("sender", sender);
values.put("timestamp", timestamp);
sqLiteDataBaseForChat.insert("messages", null, values);
}

public Cursor getAllMessages() {
return sqLiteDataBaseForChat.query("messages", null, null, null, null, null, "timestamp ASC");
}
}
38 changes: 3 additions & 35 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@
<TextView
android:id="@+id/readText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_height="180dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="10dp"
Expand Down Expand Up @@ -188,7 +188,7 @@
<TextView
android:id="@+id/writeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_height="180dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="10dp"
Expand Down Expand Up @@ -219,7 +219,7 @@
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:fontFamily="sans-serif-medium"
android:onClick="nearlinkChatSend"
android:onClick="NearLinkChatSendData"
android:text="@string/nearlinkChatSend"
android:textColor="#FFFFFFFF"
app:backgroundTint="@color/Pink_is_fancy"
Expand Down Expand Up @@ -859,38 +859,6 @@

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginStart="5dp"
android:gravity="center_vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="10dp"
android:layout_marginEnd="5dp"
android:fontFamily="sans-serif-medium"
android:text="@string/uiNearLinkSettingsForPlus1"
android:textColor="@color/teal_700"
android:textSize="14sp" />

<androidx.appcompat.widget.AppCompatCheckBox
android:id="@+id/cbSettingsForPlus1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="false"
android:fontFamily="sans-serif-medium"
android:text="@string/uiNearLinkSettingsForWord"
android:textColor="@color/Pink_is_fancy"
android:textSize="16sp"
android:theme="@style/MyCheckBox" />

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
Expand Down
3 changes: 1 addition & 2 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<resources>
<string name="app_name">NLChat</string>
<string name="app_package">com.haohanyh.linmengjia.nearlink.nlchat.fun</string>
<string name="app_version">1.2.1.2024.0701</string>
<string name="app_version">1.2.16.2024.0701</string>

<string name="appwarn">NLChat,浩瀚银河宗旨为用爱和魔法创造Android APP。</string>
<string name="thanks3q">友情感谢</string>
Expand Down Expand Up @@ -59,7 +59,6 @@
<string name="uiNearLinkSettingsForClearSCR">阅后即焚(默认2分钟清) </string>
<string name="uiNearLinkSettingsForEncryption">通讯加密(Dev) </string>
<string name="uiNearLinkSettingsForClip">聊天文本进入剪贴板 </string>
<string name="uiNearLinkSettingsForPlus1">聊天消息自动+1 </string>
<string name="uiNearLinkSettingsForPush">消息通知(手动开启) </string>
<string name="uiNearLinkSettingsForBackground">背景运行(Daemon) </string>
<string name="uiNearLinkSettingsForBackup">自动备份设置(JSON) </string>
Expand Down

0 comments on commit a564acf

Please sign in to comment.