蓝牙连接
This commit is contained in:
@@ -92,6 +92,12 @@ android {
|
||||
|
||||
|
||||
dependencies {
|
||||
// Espressif 官方 ESP32 配网 SDK(BLE / SoftAP)
|
||||
implementation 'com.github.espressif:esp-idf-provisioning-android:lib-2.4.4'
|
||||
// 官方配网 SDK 的连接事件使用新版 EventBus;与框架现有的 de.greenrobot 包并存。
|
||||
implementation 'org.greenrobot:eventbus:3.3.1'
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation files('libs/QWeather_Public_Android_V5.1.2.jar')
|
||||
implementation 'com.google.android.material:material:1.6.0'
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
|
||||
android:usesPermissionFlags="neverForLocation"
|
||||
tools:targetApi="31" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
@@ -126,12 +133,17 @@
|
||||
android:exported="false"
|
||||
android:screenOrientation="portrait" />
|
||||
<activity
|
||||
android:name="com.ckkj.griddle.main.activity.MainActivity"
|
||||
android:launchMode="singleTask"
|
||||
android:name=".device.WifiListActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="portrait"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
<activity
|
||||
android:name="com.ckkj.griddle.chat.ChatHistoryActivity"
|
||||
android:name=".device.DeviceConnectingActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="portrait" />
|
||||
<activity
|
||||
android:name="com.ckkj.griddle.main.activity.MainActivity"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="portrait"
|
||||
android:windowSoftInputMode="adjustResize"/>
|
||||
<activity
|
||||
|
||||
@@ -1,973 +0,0 @@
|
||||
package com.ckkj.griddle.chat;
|
||||
|
||||
import static android.app.Activity.RESULT_OK;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Color;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.text.Editable;
|
||||
import android.text.TextUtils;
|
||||
import android.text.TextWatcher;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.core.widget.NestedScrollView;
|
||||
import androidx.recyclerview.widget.GridLayoutManager;
|
||||
|
||||
import com.chad.library.adapter.base.BaseQuickAdapter;
|
||||
import com.ckkj.griddle.AppConfig;
|
||||
import com.ckkj.griddle.EventMessage;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.base.BaseFragment;
|
||||
import com.ckkj.griddle.chat.adapter.ChatQuestionDetailAdapter;
|
||||
import com.ckkj.griddle.chat.adapter.ChatZixunAdapter;
|
||||
import com.ckkj.griddle.chat.entity.ChatQuestionEntity;
|
||||
import com.ckkj.griddle.custom.GridSpacingItemDecoration;
|
||||
import com.ckkj.griddle.databinding.IndexLayoutBinding;
|
||||
import com.ckkj.griddle.chat.adapter.IndexChatAdapter;
|
||||
import com.ckkj.griddle.chat.adapter.IndexOptionAdapter;
|
||||
import com.ckkj.griddle.chat.adapter.IndexEnterHintAdapter;
|
||||
import com.ckkj.griddle.chat.adapter.IndexQuickAskAdapter;
|
||||
import com.ckkj.griddle.chat.entity.CharHistoryEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatAiMsgEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatMultiItem;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
import com.ckkj.griddle.chat.mvp.IndexContract;
|
||||
import com.ckkj.griddle.chat.mvp.IndexImpl;
|
||||
import com.ckkj.griddle.chat.mvp.IndexPresenter;
|
||||
import com.ckkj.griddle.dialog.ContentReportDialog;
|
||||
import com.ckkj.griddle.login.LoginActivity;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.plate.entity.BaziResultBean;
|
||||
import com.ckkj.griddle.plate.entity.PaipanCache;
|
||||
import com.ckkj.griddle.utils.click.ClickUtil;
|
||||
import com.ckkj.griddle.utils.manager.ColorManage;
|
||||
import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
import com.lxj.xpopup.XPopup;
|
||||
import com.lxj.xpopup.interfaces.OnSelectListener;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import butterknife.OnClick;
|
||||
import de.greenrobot.event.Subscribe;
|
||||
import de.greenrobot.event.ThreadMode;
|
||||
import android.content.ClipData;
|
||||
import android.content.ClipboardManager;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class ChatFragment extends BaseFragment<IndexLayoutBinding, IndexPresenter> implements IndexContract.IndexView {
|
||||
|
||||
//顶部 adapter
|
||||
private IndexOptionAdapter mOptionAdapter;
|
||||
private ChatZixunAdapter mZixunQuestAdapter;
|
||||
private ChatQuestionDetailAdapter mQuesDetailAdapter;
|
||||
//快速提问 adapter
|
||||
private IndexQuickAskAdapter mQuickAskAdapter;
|
||||
private List<IndexTemplateEntity> mQuickAskList = new ArrayList<>();
|
||||
|
||||
private List<ChatMultiItem> mChatMsgList = new ArrayList<>();
|
||||
//聊天 adapter
|
||||
private IndexChatAdapter mChatAdapter;
|
||||
//欢迎语 adapter
|
||||
private IndexEnterHintAdapter mHintAdapter;
|
||||
//输入的内容
|
||||
private String mCurrentInputContent = "";
|
||||
//当前options 的 pos
|
||||
private int mCurrentStreamPos = 0;
|
||||
//模板数据 list
|
||||
private List<IndexTemplateEntity> mIndexTemList = new ArrayList<>();
|
||||
//输出是否完成
|
||||
private boolean mIsStreamStop = true;
|
||||
//当前选中 option 的 typeID
|
||||
private String mSelectTypeID = "1";
|
||||
//会话 ID
|
||||
private String mSessionId = "";
|
||||
|
||||
// 添加流式数据累积变量
|
||||
private StringBuilder mStreamContentBuilder = new StringBuilder();
|
||||
private ChatAiMsgEntity mCurrentStreamEntity = null;
|
||||
|
||||
// 智能滚动管理
|
||||
private boolean mIsUserScrolling = false;
|
||||
|
||||
// 优化防抖机制
|
||||
private Handler mUpdateHandler = new Handler();
|
||||
private Runnable mUpdateRunnable;
|
||||
|
||||
private List<ChatQuestionEntity> mQuesTypeList = new ArrayList<>();
|
||||
private boolean mIsShowQuestions = true;
|
||||
|
||||
@Override
|
||||
public void initData(Bundle state) {
|
||||
|
||||
mOptionAdapter = new IndexOptionAdapter(mContext, R.layout.index_home_option_item, mIndexTemList);
|
||||
viewBinding.rvOptions.setAdapter(mOptionAdapter);
|
||||
mQuickAskAdapter = new IndexQuickAskAdapter(mContext, R.layout.index_home_quick_ask_item, mQuickAskList);
|
||||
viewBinding.rvQuickAsk.setAdapter(mQuickAskAdapter);
|
||||
mChatAdapter = new IndexChatAdapter(mContext, mChatMsgList, viewBinding.rvChat);
|
||||
viewBinding.rvChat.setAdapter(mChatAdapter);
|
||||
//提问类型
|
||||
GridLayoutManager manager = new GridLayoutManager(mContext, 2);
|
||||
viewBinding.rvChatQuick.setLayoutManager(manager);
|
||||
List<ChatQuestionEntity.SubheadingsDTO> subList = new ArrayList<>();
|
||||
mQuesDetailAdapter = new ChatQuestionDetailAdapter(R.layout.chat_quest_detail_item, subList);
|
||||
viewBinding.rvChatQuick.setAdapter(mQuesDetailAdapter);
|
||||
viewBinding.rvChatQuick.addItemDecoration(new GridSpacingItemDecoration(2, 10, true));
|
||||
mZixunQuestAdapter = new ChatZixunAdapter(mContext, R.layout.chat_zixun_type_item, mQuesTypeList);
|
||||
viewBinding.rvChatType.setAdapter(mZixunQuestAdapter);
|
||||
|
||||
// 设置聊天RecyclerView的LayoutManager(禁用滚动)
|
||||
androidx.recyclerview.widget.LinearLayoutManager chatLayoutManager =
|
||||
new androidx.recyclerview.widget.LinearLayoutManager(mContext);
|
||||
chatLayoutManager.setStackFromEnd(false);
|
||||
viewBinding.rvChat.setLayoutManager(chatLayoutManager);
|
||||
|
||||
// 禁用RecyclerView的滚动,让NestedScrollView处理滚动
|
||||
viewBinding.rvChat.setNestedScrollingEnabled(false);
|
||||
|
||||
mHintAdapter = new IndexEnterHintAdapter(mContext, R.layout.index_enter_hint_item, new ArrayList<>());
|
||||
viewBinding.rvEnterHint.setAdapter(mHintAdapter);
|
||||
|
||||
setAdapterClick();
|
||||
|
||||
// 添加EditText的焦点监听器
|
||||
viewBinding.editInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
|
||||
@Override
|
||||
public void onFocusChange(View v, boolean hasFocus) {
|
||||
if (hasFocus) {
|
||||
// EditText获取焦点时,延迟滚动到底部,确保键盘弹出后再滚动
|
||||
new Handler().postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
scrollNestedScrollViewToBottom();
|
||||
}
|
||||
}, 300); // 延迟300ms,等待键盘弹出
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
viewBinding.editInput.addTextChangedListener(new TextWatcher() {
|
||||
@Override
|
||||
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTextChanged(CharSequence s, int start, int before, int count) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTextChanged(Editable s) {
|
||||
if (s != null) {
|
||||
mCurrentInputContent = s.toString().trim();
|
||||
if (TextUtils.isEmpty(s.toString().trim())) {
|
||||
viewBinding.imgSend.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_index_send));
|
||||
viewBinding.editInput.setHint("请输入您的问题");
|
||||
} else {
|
||||
viewBinding.imgSend.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_index_send_b));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//请求页面模板数据
|
||||
mPresenter.getIndexTemplateDatas();
|
||||
mPresenter.getChatTemplateDatas();
|
||||
//组件增加点击区域
|
||||
ClickUtil.addClickPart(viewBinding.imgCloseQuick, 30);
|
||||
ClickUtil.addClickPart(viewBinding.imgRefresh, 30);
|
||||
ClickUtil.addClickPart(viewBinding.imgHistory, 30);
|
||||
|
||||
// 设置智能滚动监听
|
||||
setupSmartScrollListener();
|
||||
// 设置页面点击监听,用于隐藏键盘
|
||||
setupPageClickListener();
|
||||
// 检查是否有传递过来的参数
|
||||
checkAndHandleBundle();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查并处理传递过来的Bundle参数
|
||||
*/
|
||||
private void checkAndHandleBundle() {
|
||||
Bundle args = getArguments();
|
||||
if (args != null) {
|
||||
handleBirthInfoBundle(args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理出生信息Bundle参数
|
||||
*
|
||||
* @param bundle 包含出生信息的Bundle
|
||||
*/
|
||||
public void handleBirthInfoBundle(Bundle bundle) {
|
||||
if (bundle != null) {
|
||||
BaziResultBean baseEntity = PaipanCache.get();
|
||||
// 获取出生信息
|
||||
BaziResultBean.BaseInfoDTO birthInfo = baseEntity.getBaseInfo();
|
||||
BaziResultBean.DetailInfoDTO.SizhuInfoDTO sizhuInfoDTO = baseEntity.getDetailInfo().getSizhuInfo();
|
||||
BaziResultBean.DetailInfoDTO.DayunInfoDTO defaulLiunian = (BaziResultBean.DetailInfoDTO.DayunInfoDTO) bundle.getSerializable("defaul_liunian");
|
||||
if (birthInfo != null) {
|
||||
viewBinding.editInput.setText("我叫" + birthInfo.getName() + "," +
|
||||
((birthInfo.getSex().equals("乾造") ? "男" : "女") + "," +
|
||||
"生于公历" + birthInfo.getGongli() + "," + "当前大运为" + defaulLiunian.getDayunStartYear() + "--" +
|
||||
defaulLiunian.getDayunEndYear() + "," + defaulLiunian.getDayunStartGanzhi() + "大运,四柱为"
|
||||
+ sizhuInfoDTO.getYear().getTg() + sizhuInfoDTO.getYear().getDz() + "、" +
|
||||
sizhuInfoDTO.getMonth().getTg() + sizhuInfoDTO.getMonth().getDz() + "、" +
|
||||
sizhuInfoDTO.getDay().getTg() + sizhuInfoDTO.getDay().getDz() + "、" +
|
||||
sizhuInfoDTO.getHour().getTg() + sizhuInfoDTO.getHour().getDz() + "," +
|
||||
"现在需要你根据我的八字,给我具体分析一下我的事业、感情、健康、财富、格局、喜用神"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当Fragment参数更新时调用(用于处理onNewIntent的情况)
|
||||
*/
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
|
||||
// 检查是否有新的参数需要处理
|
||||
Bundle args = getArguments();
|
||||
if (args != null && args.getBoolean("goto_index_fragment", false)) {
|
||||
// 处理参数
|
||||
handleBirthInfoBundle(args);
|
||||
|
||||
// 清除标记,避免重复处理
|
||||
args.remove("goto_index_fragment");
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe(threadMode = ThreadMode.MainThread)
|
||||
public void onGetMessage(EventMessage message) {
|
||||
//用户添加地址成功
|
||||
if (message.getEventStrKey().equals(EventMessage.HISTORY_SESSIONID_DELETE_SUCCESS)) {
|
||||
if (message.getMsg().equals(mSessionId)) {
|
||||
// viewBinding.linearOptionHint.setVisibility(View.VISIBLE);
|
||||
mChatMsgList.clear();
|
||||
mChatAdapter.setNewData(mChatMsgList);
|
||||
mSessionId = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置页面点击监听器
|
||||
*/
|
||||
private void setupPageClickListener() {
|
||||
viewBinding.rvChat.setOnTouchListener(new View.OnTouchListener() {
|
||||
@Override
|
||||
public boolean onTouch(View v, MotionEvent event) {
|
||||
// 当用户触摸NestedScrollView时,隐藏键盘并清除焦点
|
||||
if (event.getAction() == MotionEvent.ACTION_DOWN) {
|
||||
hideKeyboardAndClearFocus();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐藏键盘并清除EditText焦点
|
||||
*/
|
||||
private void hideKeyboardAndClearFocus() {
|
||||
// 清除EditText焦点
|
||||
viewBinding.editInput.clearFocus();
|
||||
|
||||
// 隐藏键盘
|
||||
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
if (imm != null) {
|
||||
imm.hideSoftInputFromWindow(viewBinding.editInput.getWindowToken(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 滚动NestedScrollView到底部
|
||||
*/
|
||||
private void scrollNestedScrollViewToBottom() {
|
||||
if (viewBinding.nestedScrollChat != null) {
|
||||
// 获取NestedScrollView的子视图(RecyclerView)
|
||||
View childView = viewBinding.nestedScrollChat.getChildAt(0);
|
||||
if (childView != null) {
|
||||
// 滚动到底部
|
||||
viewBinding.nestedScrollChat.smoothScrollTo(0, childView.getHeight());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置智能滚动监听器(修改为监听NestedScrollView)
|
||||
*/
|
||||
private void setupSmartScrollListener() {
|
||||
// 监听NestedScrollView的滚动
|
||||
viewBinding.nestedScrollChat.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
|
||||
@Override
|
||||
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
|
||||
// 检测用户是否向上滑动
|
||||
if (scrollY < oldScrollY) {
|
||||
// 用户向上滑动
|
||||
mIsUserScrolling = true;
|
||||
} else if (scrollY > oldScrollY) {
|
||||
// 用户向下滑动
|
||||
mIsUserScrolling = true;
|
||||
}
|
||||
|
||||
// 检查是否滚动到底部
|
||||
if (scrollY >= (v.getChildAt(0).getHeight() - v.getHeight())) {
|
||||
// 滚动到底部,恢复自动滚动
|
||||
mIsUserScrolling = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private void setAdapterClick() {
|
||||
//顶部的选项 adapter 点击事件
|
||||
mOptionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
|
||||
if (mCurrentStreamPos != position) {
|
||||
if (mIsStreamStop) {
|
||||
viewBinding.rlQuickAsk.setVisibility(View.GONE);
|
||||
mOptionAdapter.setSelectPos(position);
|
||||
setOptionSelStyle(position);
|
||||
mCurrentStreamPos = position;
|
||||
mSessionId = "";
|
||||
mSelectTypeID = mIndexTemList.get(position).getId();
|
||||
} else {
|
||||
ToastUtil.showShort(mContext, "Ai解答中,请稍后操作");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//咨询类型 adapter
|
||||
mZixunQuestAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
|
||||
if (mIsStreamStop) {
|
||||
mZixunQuestAdapter.setSelectPos(position);
|
||||
mQuesDetailAdapter.setNewData(mQuesTypeList.get(position).getSubheadings());
|
||||
} else {
|
||||
ToastUtil.showShort(mContext, "Ai解答中,请稍后操作");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//快速提问
|
||||
mQuesDetailAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
|
||||
if (!AppConfig.USER_LOGIN) {
|
||||
goTo(mContext, LoginActivity.class, null);
|
||||
return;
|
||||
}
|
||||
if (!mIsStreamStop) {
|
||||
ToastUtil.showShort(mContext, "Ai解答中,请稍后操作");
|
||||
return;
|
||||
}
|
||||
String quickAskContent = mQuesTypeList.get(mZixunQuestAdapter.getmSelPos()).
|
||||
getSubheadings().get(position).getContent();
|
||||
sendMsgToAi(quickAskContent);
|
||||
}
|
||||
});
|
||||
|
||||
//流式输出,是否完成
|
||||
mChatAdapter.setOnStreamCompleteListener(new IndexChatAdapter.OnStreamCompleteListener() {
|
||||
@Override
|
||||
//此时已经流式输出完成
|
||||
public void onStreamComplete(int position) {
|
||||
mCurrentStreamPos = position;
|
||||
viewBinding.imgSend.setVisibility(View.VISIBLE);
|
||||
viewBinding.imgStop.setVisibility(View.GONE);
|
||||
mIsStreamStop = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStreamStop() {
|
||||
viewBinding.imgSend.setVisibility(View.VISIBLE);
|
||||
viewBinding.imgStop.setVisibility(View.GONE);
|
||||
mIsStreamStop = true;
|
||||
}
|
||||
});
|
||||
mChatAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
|
||||
@Override
|
||||
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
|
||||
switch (view.getId()) {
|
||||
case R.id.img_jb:
|
||||
ContentReportDialog cancelDialog = new ContentReportDialog(mContext, R.layout.dialog_report_reason, "");
|
||||
cancelDialog.show();
|
||||
cancelDialog.setOnDialogListener(new ContentReportDialog.DialogListener() {
|
||||
@Override
|
||||
public void callBackDatas(String reason) {
|
||||
showLoadingDialog();
|
||||
//举报
|
||||
mPresenter.commitReport(reason);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 设置长按菜单监听器
|
||||
mChatAdapter.setOnItemLongClickMenuListener(new IndexChatAdapter.OnItemLongClickMenuListener() {
|
||||
@Override
|
||||
public void onCopyClick(ChatMultiItem item, int position) {
|
||||
// 处理复制操作
|
||||
String content = item.getMessage().getContent();
|
||||
if (!TextUtils.isEmpty(content)) {
|
||||
ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
ClipData clip = ClipData.newPlainText("chat_content", content);
|
||||
clipboard.setPrimaryClip(clip);
|
||||
ToastUtil.showShort(mContext, "内容已复制");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReportClick(ChatMultiItem item, int position) {
|
||||
// 处理举报操作
|
||||
ContentReportDialog cancelDialog = new ContentReportDialog(mContext, R.layout.dialog_report_reason, "");
|
||||
cancelDialog.show();
|
||||
cancelDialog.setOnDialogListener(new ContentReportDialog.DialogListener() {
|
||||
@Override
|
||||
public void callBackDatas(String reason) {
|
||||
showLoadingDialog();
|
||||
//举报
|
||||
mPresenter.commitReport(reason);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 添加长按监听器
|
||||
// mChatAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
|
||||
// @Override
|
||||
// public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
|
||||
// switch (view.getId()) {
|
||||
// case R.id.tv_text: // 文本内容的view id
|
||||
// XPopup.fixLongClick(view); // 能保证弹窗弹出后,下层的View无法滑动
|
||||
//
|
||||
// // 获取当前消息内容
|
||||
// ChatMultiItem item = mChatMsgList.get(position);
|
||||
// String content = item.getMessage().getContent();
|
||||
//
|
||||
// // 使用链式调用,确保atView在asAttachList之前
|
||||
// new XPopup.Builder(getContext())
|
||||
// .hasShadowBg(false)
|
||||
// .atView(view) // 使用atView而不是watchView
|
||||
// .asAttachList(new String[]{"复制", "举报"},
|
||||
// null,
|
||||
// new OnSelectListener() {
|
||||
// @Override
|
||||
// public void onSelect(int selectPosition, String text) {
|
||||
// switch (selectPosition) {
|
||||
// case 0: // 复制
|
||||
// if (!TextUtils.isEmpty(content)) {
|
||||
// ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
// ClipData clip = ClipData.newPlainText("chat_content", content);
|
||||
// clipboard.setPrimaryClip(clip);
|
||||
// ToastUtil.showShort(mContext, "内容已复制");
|
||||
// }
|
||||
// break;
|
||||
// case 1: // 举报
|
||||
// ContentReportDialog cancelDialog = new ContentReportDialog(mContext, R.layout.dialog_report_reason, "");
|
||||
// cancelDialog.show();
|
||||
// cancelDialog.setOnDialogListener(new ContentReportDialog.DialogListener() {
|
||||
// @Override
|
||||
// public void callBackDatas(String reason) {
|
||||
// showLoadingDialog();
|
||||
// //举报
|
||||
// mPresenter.commitReport(reason);
|
||||
// }
|
||||
// });
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// .show();
|
||||
// return true;
|
||||
// }
|
||||
// return false;
|
||||
// }
|
||||
// });
|
||||
}
|
||||
|
||||
@OnClick({R.id.img_send, R.id.img_stop, R.id.img_close_quick, R.id.img_refresh, R.id.img_history, R.id.img_title_icon,
|
||||
R.id.img_close})
|
||||
public void onClick(View v) {
|
||||
switch (v.getId()) {
|
||||
case R.id.img_send://发送1
|
||||
if (!AppConfig.USER_LOGIN) {
|
||||
goTo(mContext, LoginActivity.class, null);
|
||||
return;
|
||||
}
|
||||
if (TextUtils.isEmpty(mCurrentInputContent.trim())) {
|
||||
ToastUtil.showShort(mContext, "请输入您的问题");
|
||||
return;
|
||||
}
|
||||
if (!mIsStreamStop) {
|
||||
ToastUtil.showShort(mContext, "Ai解答中,请稍后操作");
|
||||
return;
|
||||
}
|
||||
sendMsgToAi(mCurrentInputContent.trim());
|
||||
break;
|
||||
|
||||
case R.id.img_stop://停止输出
|
||||
stopSteamOutput();
|
||||
break;
|
||||
|
||||
case R.id.img_close_quick://关闭快速提问
|
||||
viewBinding.rlQuickAsk.setVisibility(View.GONE);
|
||||
break;
|
||||
|
||||
case R.id.img_refresh://刷新
|
||||
if (!mIsStreamStop) {
|
||||
ToastUtil.showShort(mContext, "Ai解答中,请稍后操作");
|
||||
return;
|
||||
}
|
||||
// viewBinding.linearOptionHint.setVisibility(View.VISIBLE);
|
||||
mChatMsgList.clear();
|
||||
mChatAdapter.setNewData(mChatMsgList);
|
||||
mSessionId = "";
|
||||
mChatAdapter.setPendingTipsCheckPos(null);
|
||||
break;
|
||||
|
||||
case R.id.img_history://历史记录
|
||||
if (!AppConfig.USER_LOGIN) {
|
||||
goTo(mContext, LoginActivity.class, null);
|
||||
return;
|
||||
}
|
||||
goToForResult(mContext, ChatHistoryActivity.class, REQUEST_EVENT_CODE_10001, null);
|
||||
break;
|
||||
|
||||
case R.id.img_title_icon:
|
||||
goTo(mContext, LoginActivity.class, null);
|
||||
break;
|
||||
|
||||
case R.id.img_close:
|
||||
if (!mIsStreamStop) {
|
||||
ToastUtil.showShort(mContext, "Ai解答中,请稍后操作");
|
||||
return;
|
||||
}
|
||||
if (mIsShowQuestions) {
|
||||
viewBinding.cardQuestion.setVisibility(View.GONE);
|
||||
viewBinding.imgClose.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_chat_down));
|
||||
mIsShowQuestions = false;
|
||||
} else {
|
||||
viewBinding.cardQuestion.setVisibility(View.VISIBLE);
|
||||
viewBinding.imgClose.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_chat_up));
|
||||
mIsShowQuestions = true;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止输出
|
||||
*/
|
||||
private void stopSteamOutput() {
|
||||
// 停止当前网络请求
|
||||
mPresenter.stopCurrentRequest();
|
||||
|
||||
// 获取当前正在流式输出的位置
|
||||
int currentPosition = mChatMsgList.size() - 1;
|
||||
|
||||
// 标记当前消息为被停止状态
|
||||
mChatAdapter.markAsStopped(currentPosition);
|
||||
|
||||
// 停止适配器中的流式输出
|
||||
mChatAdapter.setStreamerStop(currentPosition);
|
||||
|
||||
// 清除当前流式输出位置
|
||||
mChatAdapter.setCurrentStreamingPosition(-1);
|
||||
|
||||
// 强制更新当前item以显示停止标识
|
||||
mChatAdapter.notifyItemChanged(currentPosition);
|
||||
|
||||
// 恢复UI状态
|
||||
viewBinding.imgSend.setVisibility(View.VISIBLE);
|
||||
viewBinding.imgStop.setVisibility(View.GONE);
|
||||
mIsStreamStop = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (data != null) {
|
||||
if (resultCode == RESULT_OK) {
|
||||
switch (requestCode) {
|
||||
case REQUEST_EVENT_CODE_10001:
|
||||
String sessionId = data.getStringExtra("session_id");
|
||||
String numerologyType = data.getStringExtra("numerology_type");
|
||||
int showSelPos = -1;
|
||||
for (int i = 0; i < mIndexTemList.size(); i++) {
|
||||
if (numerologyType.equals(mIndexTemList.get(i).getId())) {
|
||||
showSelPos = i;
|
||||
}
|
||||
}
|
||||
if (mCurrentStreamPos != showSelPos) {
|
||||
|
||||
}
|
||||
if (mIsStreamStop) {
|
||||
viewBinding.rlQuickAsk.setVisibility(View.GONE);
|
||||
mOptionAdapter.setSelectPos(showSelPos);
|
||||
setOptionSelStyle(showSelPos);
|
||||
mCurrentStreamPos = showSelPos;
|
||||
mSelectTypeID = mIndexTemList.get(showSelPos).getId();
|
||||
if (!TextUtils.isEmpty(sessionId)) {
|
||||
mPresenter.getChatDetailByID(sessionId);
|
||||
}
|
||||
} else {
|
||||
ToastUtil.showShort(mContext, "Ai解答中,请稍后操作");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息给 AI
|
||||
*/
|
||||
private void sendMsgToAi(String senMsg) {
|
||||
if (!AppConfig.USER_LOGIN) {
|
||||
goTo(mContext, LoginActivity.class, null);
|
||||
return;
|
||||
}
|
||||
viewBinding.cardQuestion.setVisibility(View.GONE);
|
||||
viewBinding.imgClose.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_chat_down));
|
||||
mIsShowQuestions = false;
|
||||
viewBinding.linearOptionHint.setVisibility(View.GONE);
|
||||
// 重置滚动状态
|
||||
mIsUserScrolling = false;
|
||||
// 清理适配器缓存
|
||||
mChatAdapter.clearCache();
|
||||
|
||||
// 创建用户消息
|
||||
ChatAiMsgEntity chatMsgEntity = new ChatAiMsgEntity();
|
||||
chatMsgEntity.setSessionId(mSessionId);
|
||||
chatMsgEntity.setType(mSelectTypeID);
|
||||
chatMsgEntity.setContent(senMsg);
|
||||
ChatMultiItem userEntity = new ChatMultiItem(ChatMultiItem.TYPE_TEXT_RIGHT, chatMsgEntity);
|
||||
mChatMsgList.add(userEntity);
|
||||
mChatAdapter.notifyItemInserted(mChatMsgList.size() - 1);
|
||||
|
||||
// 创建AI回复消息(初始为空)
|
||||
mCurrentStreamEntity = new ChatAiMsgEntity();
|
||||
mCurrentStreamEntity.setSessionId(mSessionId);
|
||||
mCurrentStreamEntity.setType(mSelectTypeID);
|
||||
mCurrentStreamEntity.setContent(""); // 初始为空
|
||||
ChatMultiItem aiEntity = new ChatMultiItem(ChatMultiItem.TYPE_TEXT_LEFT, mCurrentStreamEntity);
|
||||
mChatMsgList.add(aiEntity);
|
||||
|
||||
// 设置当前流式输出位置
|
||||
int aiMessagePosition = mChatMsgList.size() - 1;
|
||||
mChatAdapter.setCurrentStreamingPosition(aiMessagePosition);
|
||||
mChatAdapter.notifyItemInserted(aiMessagePosition);
|
||||
|
||||
// 重置流式数据累积器
|
||||
mStreamContentBuilder.setLength(0);
|
||||
|
||||
// 清空输入框
|
||||
viewBinding.editInput.setText("");
|
||||
|
||||
// 设置UI状态
|
||||
viewBinding.imgSend.setVisibility(View.GONE);
|
||||
viewBinding.imgStop.setVisibility(View.VISIBLE);
|
||||
|
||||
// 发送消息后自动滚动到底部
|
||||
scrollToBottomAfterSend();
|
||||
|
||||
// 发起流式请求
|
||||
mPresenter.talkToAi(senMsg, mSelectTypeID, mSessionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IndexPresenter createPresenter() {
|
||||
return new IndexPresenter(new IndexImpl());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getTalkResultSuccess(ChatAiMsgEntity bean) {
|
||||
hideDialogLoading();
|
||||
}
|
||||
|
||||
/**
|
||||
* 首页数据获取成功
|
||||
*
|
||||
* @param list
|
||||
*/
|
||||
@Override
|
||||
public void getIndexTemplateSuccess(List<IndexTemplateEntity> list) {
|
||||
if (list != null && list.size() != 0) {
|
||||
mIndexTemList = list;
|
||||
mOptionAdapter.setNewData(mIndexTemList);
|
||||
setAdapterClick();
|
||||
setOptionSelStyle(0);
|
||||
mSelectTypeID = mIndexTemList.get(0).getId();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换设置显示内容
|
||||
*
|
||||
* @param pos
|
||||
*/
|
||||
private void setOptionSelStyle(int pos) {
|
||||
try {
|
||||
mChatMsgList.clear();
|
||||
mChatAdapter.setNewData(mChatMsgList);
|
||||
// 清理缓存
|
||||
mChatAdapter.clearCache();
|
||||
// viewBinding.linearOptionHint.setVisibility(View.VISIBLE);
|
||||
IndexTemplateEntity defaulEntity = mIndexTemList.get(pos);
|
||||
viewBinding.tvTitleExpert.setText(defaulEntity.getTitle() + "专家");
|
||||
viewBinding.tvSelectOptionLable.setText(defaulEntity.getTitle() + "专家");
|
||||
viewBinding.tvSelectOptionSlogan.setText(defaulEntity.getSubheading());
|
||||
if (ColorManage.getInstance().isParsableColor(defaulEntity.getColor())) {
|
||||
viewBinding.tvSelectOptionSlogan.setTextColor(Color.parseColor(defaulEntity.getColor()));
|
||||
} else {
|
||||
viewBinding.tvSelectOptionSlogan.setTextColor(ContextCompat.getColor(mContext, R.color.color_zhu));
|
||||
}
|
||||
//提示语
|
||||
List<String> hintMsgList = new ArrayList<>();
|
||||
hintMsgList = Arrays.asList(defaulEntity.getIntermediateContent().split("#"));
|
||||
mHintAdapter.setNewData(hintMsgList);
|
||||
//快速提问
|
||||
mQuickAskList.clear();
|
||||
List<String> quickAskList = new ArrayList<>();
|
||||
quickAskList = Arrays.asList(defaulEntity.getQuickQuestions().split("#"));
|
||||
for (String content : quickAskList) {
|
||||
IndexTemplateEntity entity = new IndexTemplateEntity();
|
||||
entity.setColor(defaulEntity.getColor());
|
||||
entity.setBlackcolor(defaulEntity.getBlackcolor());
|
||||
entity.setSpliteItemContent(content);
|
||||
mQuickAskList.add(entity);
|
||||
}
|
||||
mQuickAskAdapter.setNewData(mQuickAskList);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNetChange(int netModel) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showError(String message) {
|
||||
hideDialogLoading();
|
||||
ToastUtil.showShort(mContext, message);
|
||||
// 流式传输完成,恢复UI状态
|
||||
viewBinding.imgSend.setVisibility(View.VISIBLE);
|
||||
viewBinding.imgStop.setVisibility(View.GONE);
|
||||
mIsStreamStop = true;
|
||||
|
||||
// 可以在这里处理会话ID等
|
||||
if (mCurrentStreamEntity != null && !TextUtils.isEmpty(mCurrentStreamEntity.getSessionId())) {
|
||||
mSessionId = mCurrentStreamEntity.getSessionId();
|
||||
}
|
||||
|
||||
// 清理当前流式实体
|
||||
mCurrentStreamEntity = null;
|
||||
mStreamContentBuilder.setLength(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logOut(BaseBean bean) {
|
||||
|
||||
}
|
||||
|
||||
// 实现流式消息接收回调
|
||||
@Override
|
||||
public void onStreamMessageReceived(String messageChunk) {
|
||||
mIsStreamStop = false;
|
||||
if (mCurrentStreamEntity != null) {
|
||||
// 更新当前AI消息的内容
|
||||
mCurrentStreamEntity.setContent(messageChunk);
|
||||
|
||||
// 取消之前的更新任务
|
||||
if (mUpdateRunnable != null) {
|
||||
mUpdateHandler.removeCallbacks(mUpdateRunnable);
|
||||
}
|
||||
|
||||
mUpdateRunnable = () -> {
|
||||
// 只更新最后一个item
|
||||
int lastPosition = mChatMsgList.size() - 1;
|
||||
if (lastPosition >= 0) {
|
||||
// 使用更轻量的更新方式,避免重新布局
|
||||
mChatAdapter.notifyItemChanged(lastPosition, "content_only");
|
||||
|
||||
// 流式输出时,如果用户没有手动滑动,则自动滚动NestedScrollView
|
||||
if (!mIsUserScrolling) {
|
||||
smoothScrollNestedScrollView();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 增加延迟时间,减少更新频率
|
||||
mUpdateHandler.postDelayed(mUpdateRunnable, 100);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 实现流式完成回调
|
||||
@Override
|
||||
public void onStreamComplete(String complateMsg) {
|
||||
// 流式传输完成,恢复UI状态
|
||||
viewBinding.imgSend.setVisibility(View.VISIBLE);
|
||||
viewBinding.imgStop.setVisibility(View.GONE);
|
||||
mIsStreamStop = true;
|
||||
|
||||
// 清除当前流式输出位置
|
||||
mChatAdapter.setCurrentStreamingPosition(-1);
|
||||
|
||||
// 注意:这里不标记为停止状态,因为这是正常完成
|
||||
|
||||
// 可以在这里处理会话ID等
|
||||
if (mCurrentStreamEntity != null && !TextUtils.isEmpty(mCurrentStreamEntity.getSessionId())) {
|
||||
mSessionId = mCurrentStreamEntity.getSessionId();
|
||||
}
|
||||
|
||||
// 清理当前流式实体
|
||||
mCurrentStreamEntity = null;
|
||||
mStreamContentBuilder.setLength(0);
|
||||
// 假设你最后一个消息是流式的 placeholder,现在替换它
|
||||
ChatMultiItem lastMessage = mChatMsgList.get(mChatMsgList.size() - 1);
|
||||
lastMessage.getMessage().setContent(complateMsg); // 你可以解析 Markdown 变 PlainText,或保留 Markdown 渲染
|
||||
// mChatAdapter.notifyItemChanged(mChatMsgList.size() - 1); // 更新 UI
|
||||
int lastPos = mChatAdapter.getItemCount() - 1;
|
||||
mChatAdapter.updateTipsVisibility(lastPos);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据会话 id 查询对话详情
|
||||
*
|
||||
* @param list
|
||||
*/
|
||||
@Override
|
||||
public void getChatDetailSuccess(List<ChatAiMsgEntity> list) {
|
||||
mChatMsgList.clear();
|
||||
if (list != null && list.size() != 0) {
|
||||
mSessionId = list.get(0).getSessionId();
|
||||
}
|
||||
for (ChatAiMsgEntity entity : list) {
|
||||
ChatMultiItem item;
|
||||
if (entity.getRole().equals("user")) {
|
||||
item = new ChatMultiItem(ChatMultiItem.TYPE_TEXT_RIGHT, entity);
|
||||
} else {
|
||||
item = new ChatMultiItem(ChatMultiItem.TYPE_TEXT_LEFT, entity);
|
||||
}
|
||||
mChatMsgList.add(item);
|
||||
}
|
||||
mChatAdapter.setNewData(mChatMsgList);
|
||||
viewBinding.linearOptionHint.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loginLost() {
|
||||
if (isFragmentVisible()) {
|
||||
handleLoginLost();
|
||||
}
|
||||
stopSteamOutput();
|
||||
if (mChatAdapter != null) {
|
||||
mChatAdapter.remove(mChatMsgList.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取咨询模板成功
|
||||
*
|
||||
* @param list
|
||||
*/
|
||||
@Override
|
||||
public void getChatZixunSuccess(List<ChatQuestionEntity> list) {
|
||||
this.mQuesTypeList = list;
|
||||
if (list != null) {
|
||||
mZixunQuestAdapter.setNewData(list);
|
||||
mQuesDetailAdapter.setNewData(list.get(0).getSubheadings());
|
||||
setAdapterClick();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 举报成功
|
||||
* @param bean
|
||||
*/
|
||||
@Override
|
||||
public void commitReportSuccess(BaseBean bean) {
|
||||
ToastUtil.showShort(mContext, "星语明灯感谢您的反馈");
|
||||
hideDialogLoading();
|
||||
}
|
||||
|
||||
// 实现sessionId接收回调
|
||||
@Override
|
||||
public void onSessionReceived(String sessionId) {
|
||||
// 保存sessionId
|
||||
mSessionId = sessionId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getHistoryDataSuccess(CharHistoryEntity entity) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteHistorySuccess(BaseBean bean, int delPos) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 平滑滚动NestedScrollView到底部
|
||||
*/
|
||||
private void smoothScrollNestedScrollView() {
|
||||
if (mChatAdapter != null && mChatAdapter.getItemCount() > 0) {
|
||||
// 直接滚动NestedScrollView到底部
|
||||
viewBinding.nestedScrollChat.post(() -> {
|
||||
viewBinding.nestedScrollChat.fullScroll(View.FOCUS_DOWN);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送消息后滚动到底部
|
||||
*/
|
||||
private void scrollToBottomAfterSend() {
|
||||
new Handler().postDelayed(() -> {
|
||||
if (isFragmentVisible()) {
|
||||
viewBinding.nestedScrollChat.fullScroll(View.FOCUS_DOWN);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
package com.ckkj.griddle.chat;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.view.View;
|
||||
|
||||
import com.chad.library.adapter.base.BaseQuickAdapter;
|
||||
import com.gyf.immersionbar.ImmersionBar;
|
||||
import com.ckkj.griddle.chat.entity.ChatQuestionEntity;
|
||||
import com.scwang.smart.refresh.footer.ClassicsFooter;
|
||||
import com.scwang.smart.refresh.layout.api.RefreshHeader;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.base.BaseActivity;
|
||||
import com.ckkj.griddle.custom.view.CustomRefreshHeader;
|
||||
import com.ckkj.griddle.databinding.IndexHistoryLayoutBinding;
|
||||
import com.ckkj.griddle.chat.adapter.ChatHistoryAdapter;
|
||||
import com.ckkj.griddle.chat.entity.CharHistoryEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatAiMsgEntity;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
import com.ckkj.griddle.chat.mvp.IndexContract;
|
||||
import com.ckkj.griddle.chat.mvp.IndexImpl;
|
||||
import com.ckkj.griddle.chat.mvp.IndexPresenter;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/11
|
||||
* @description 历史记录
|
||||
*/
|
||||
|
||||
public class ChatHistoryActivity extends BaseActivity<IndexHistoryLayoutBinding, IndexPresenter>
|
||||
implements IndexContract.IndexView {
|
||||
private int mCurrentPage = 1;
|
||||
private ChatHistoryAdapter mAdapter;
|
||||
//历史记录
|
||||
private List<CharHistoryEntity.Sessions> mChatList = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public IndexPresenter createPresenter() {
|
||||
return new IndexPresenter(new IndexImpl());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLayoutResId(Bundle savedInstanceState) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initData(Bundle savedInstanceState) {
|
||||
super.initData(savedInstanceState);
|
||||
ImmersionBar.with(this)
|
||||
.statusBarColor(R.color.white)
|
||||
.statusBarDarkFont(true)
|
||||
.titleBar(viewBinding.rlTitle) // 替换为你的标题栏View
|
||||
.keyboardEnable(true)
|
||||
.navigationBarDarkIcon(true)
|
||||
.init();
|
||||
viewBinding.includedTitle.tvTitle.setText("历史记录");
|
||||
viewBinding.includedTitle.imgBack.setOnClickListener(c ->finish());
|
||||
mAdapter = new ChatHistoryAdapter(mContext, R.layout.history_item_layout, mChatList);
|
||||
viewBinding.rvData.setAdapter(mAdapter);
|
||||
setAdapterClick();
|
||||
// 设置自定义刷新头
|
||||
RefreshHeader header = new CustomRefreshHeader(mContext);
|
||||
viewBinding.refresh.setRefreshHeader(header);
|
||||
viewBinding.refresh.setRefreshFooter(new ClassicsFooter(mContext));
|
||||
viewBinding.refresh.setOnRefreshListener(layout -> {
|
||||
mCurrentPage = 1;
|
||||
getHistoryDatas();
|
||||
});
|
||||
viewBinding.refresh.setOnLoadMoreListener(layout -> {
|
||||
mCurrentPage++;
|
||||
getHistoryDatas();
|
||||
});
|
||||
showLoadingDialog();
|
||||
getHistoryDatas();
|
||||
}
|
||||
|
||||
private void setAdapterClick() {
|
||||
mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
|
||||
@Override
|
||||
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
|
||||
switch (view.getId()){
|
||||
case R.id.img_delete:
|
||||
showLoadingDialog();
|
||||
mPresenter.deleteHistoryBySessionID(mChatList.get(position).getSessionId(),position);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
|
||||
Intent intent = new Intent();
|
||||
intent.putExtra("session_id",mChatList.get(position).getSessionId());
|
||||
intent.putExtra("numerology_type",mChatList.get(position).getNumerologyType());
|
||||
setResult(RESULT_OK,intent);
|
||||
finish();
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void getHistoryDatas() {
|
||||
mPresenter.getHistoryDatas(mCurrentPage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询历史数据成功 g
|
||||
*
|
||||
* @param entity
|
||||
*/
|
||||
@Override
|
||||
public void getHistoryDataSuccess(CharHistoryEntity entity) {
|
||||
hideDialogLoading();
|
||||
int totalPage = entity.getPages();
|
||||
viewBinding.refresh.finishRefresh(300);
|
||||
viewBinding.refresh.finishLoadMore(300);
|
||||
List<CharHistoryEntity.Sessions> list = entity.getSessions();
|
||||
if (mCurrentPage == 1) {
|
||||
mChatList.clear(); // 只在刷新时清除
|
||||
mChatList = list;
|
||||
} else {
|
||||
mChatList.addAll(list);
|
||||
}
|
||||
mAdapter.setNewData(mChatList);
|
||||
// 4. 判断是否还有更多数据
|
||||
if (totalPage == mCurrentPage || list == null || list.size() == 0) {
|
||||
// ✅ 告诉 SmartRefreshLayout 没有更多数据了
|
||||
viewBinding.refresh.setNoMoreData(true);
|
||||
viewBinding.relNoMore.setVisibility(View.VISIBLE); // 自定义底部提示“暂无更多数据”
|
||||
} else {
|
||||
viewBinding.refresh.setNoMoreData(false); // 重置状态
|
||||
viewBinding.relNoMore.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
// 5. 控制空布局和内容显示
|
||||
if (mAdapter.getItemCount() != 0) {
|
||||
viewBinding.refresh.setVisibility(View.VISIBLE);
|
||||
viewBinding.relNoresult.setVisibility(View.GONE);
|
||||
} else {
|
||||
viewBinding.refresh.setVisibility(View.GONE);
|
||||
viewBinding.relNoresult.setVisibility(View.VISIBLE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除历史会话记录成功
|
||||
* @param bean
|
||||
*/
|
||||
@Override
|
||||
public void deleteHistorySuccess(BaseBean bean, int delPos) {
|
||||
hideDialogLoading();
|
||||
mAdapter.remove(delPos);
|
||||
if(mAdapter.getItemCount() == 0){
|
||||
viewBinding.refresh.setVisibility(View.GONE);
|
||||
viewBinding.relNoresult.setVisibility(View.VISIBLE);
|
||||
viewBinding.relNoMore.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getChatDetailSuccess(List<ChatAiMsgEntity> list) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loginLost() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getChatZixunSuccess(List<ChatQuestionEntity> list) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commitReportSuccess(BaseBean bean) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getTalkResultSuccess(ChatAiMsgEntity bean) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getIndexTemplateSuccess(List<IndexTemplateEntity> list) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStreamMessageReceived(String messageChunk) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStreamComplete(String complateMsg) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSessionReceived(String sessionId) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void showError(String message) {
|
||||
viewBinding.refresh.finishRefresh(500);
|
||||
viewBinding.refresh.finishLoadMore(200);
|
||||
ToastUtil.showShort(mContext, message);
|
||||
hideDialogLoading();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logOut(BaseBean bean) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.ckkj.griddle.chat.adapter;
|
||||
|
||||
import android.content.Context;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.chad.library.adapter.base.BaseQuickAdapter;
|
||||
import com.chad.library.adapter.base.BaseViewHolder;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.chat.entity.CharHistoryEntity;
|
||||
import com.ckkj.griddle.utils.time.ZYTimeUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/11
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class ChatHistoryAdapter extends BaseQuickAdapter<CharHistoryEntity.Sessions, BaseViewHolder> {
|
||||
private Context mContext;
|
||||
|
||||
public ChatHistoryAdapter(Context context,int layoutResId, @Nullable List<CharHistoryEntity.Sessions> data) {
|
||||
super(layoutResId, data);
|
||||
this.mContext = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void convert(BaseViewHolder helper, CharHistoryEntity.Sessions item) {
|
||||
ImageView imgType = helper.getView(R.id.img_logo);
|
||||
switch (item.getNumerologyType()){
|
||||
case "1"://八字命理
|
||||
imgType.setImageDrawable(ContextCompat.getDrawable(mContext,R.mipmap.icon_index_bzml));
|
||||
helper.setBackgroundRes(R.id.tv_type_name,R.drawable.shape_history_type_bzml_bg);
|
||||
helper.setTextColor(R.id.tv_type_name,ContextCompat.getColor(mContext,R.color.color_319EF4));
|
||||
break;
|
||||
case "2"://紫微斗数
|
||||
imgType.setImageDrawable(ContextCompat.getDrawable(mContext,R.mipmap. icon_index_zwds));
|
||||
helper.setBackgroundRes(R.id.tv_type_name,R.drawable.shape_history_type_zwds_bg);
|
||||
helper.setTextColor(R.id.tv_type_name,ContextCompat.getColor(mContext,R.color.color_B85CE6));
|
||||
break;
|
||||
case "3"://风水堪舆
|
||||
imgType.setImageDrawable(ContextCompat.getDrawable(mContext,R.mipmap.icon_index_fsky));
|
||||
helper.setBackgroundRes(R.id.tv_type_name,R.drawable.shape_history_type_fsky_bg);
|
||||
helper.setTextColor(R.id.tv_type_name,ContextCompat.getColor(mContext,R.color.color_24B326));
|
||||
break;
|
||||
case "6"://奇门遁甲
|
||||
imgType.setImageDrawable(ContextCompat.getDrawable(mContext,R.mipmap.icon_index_qmdj));
|
||||
helper.setBackgroundRes(R.id.tv_type_name,R.drawable.shape_history_type_qmdj_bg);
|
||||
helper.setTextColor(R.id.tv_type_name,ContextCompat.getColor(mContext,R.color.color_2A5CAA));
|
||||
break;
|
||||
case "10"://五行起名
|
||||
imgType.setImageDrawable(ContextCompat.getDrawable(mContext,R.mipmap. icon_index_wxqm));
|
||||
helper.setBackgroundRes(R.id.tv_type_name,R.drawable.shape_history_type_wxqm_bg);
|
||||
helper.setTextColor(R.id.tv_type_name,ContextCompat.getColor(mContext,R.color.color_E69900));
|
||||
break;
|
||||
default:
|
||||
imgType.setImageDrawable(ContextCompat.getDrawable(mContext,R.mipmap.icon_index_bzml));
|
||||
helper.setBackgroundRes(R.id.tv_type_name,R.drawable.shape_history_type_bzml_bg);
|
||||
helper.setTextColor(R.id.tv_type_name,ContextCompat.getColor(mContext,R.color.color_319EF4));
|
||||
break;
|
||||
}
|
||||
helper.setText(R.id.tv_type_content,item.getFirstUserMessage());
|
||||
helper.setText(R.id.tv_type_name,item.getSessionName());
|
||||
String chatTime = ZYTimeUtils.formatDateOrOneYearAgo(item.getCreateTime());
|
||||
helper.setText(R.id.tv_time,chatTime);
|
||||
helper.addOnClickListener(R.id.img_delete);
|
||||
// helper.addOnClickListener(R.id.rl_title);
|
||||
// helper.addOnClickListener(R.id.tv_type_content);
|
||||
// helper.addOnClickListener(R.id.img_logo);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.ckkj.griddle.chat.adapter;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.chad.library.adapter.base.BaseQuickAdapter;
|
||||
import com.chad.library.adapter.base.BaseViewHolder;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.chat.entity.ChatQuestionEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/8/19
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class ChatQuestionDetailAdapter extends BaseQuickAdapter<ChatQuestionEntity.SubheadingsDTO, BaseViewHolder> {
|
||||
|
||||
public ChatQuestionDetailAdapter(int layoutResId, @Nullable List<ChatQuestionEntity.SubheadingsDTO> data) {
|
||||
super(layoutResId, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void convert(BaseViewHolder helper, ChatQuestionEntity.SubheadingsDTO item) {
|
||||
helper.setText(R.id.tv_title,item.getTitle());
|
||||
helper.setText(R.id.tv_content,item.getContent());
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.ckkj.griddle.chat.adapter;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.chad.library.adapter.base.BaseQuickAdapter;
|
||||
import com.chad.library.adapter.base.BaseViewHolder;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.chat.entity.ChatQuestionEntity;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class ChatZixunAdapter extends BaseQuickAdapter<ChatQuestionEntity, BaseViewHolder> {
|
||||
private Context mContext;
|
||||
private int mSelPos = 0;
|
||||
|
||||
public ChatZixunAdapter(Context context, int layoutResId, @Nullable List<ChatQuestionEntity> data) {
|
||||
super(layoutResId, data);
|
||||
this.mContext = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void convert(BaseViewHolder helper, ChatQuestionEntity item) {
|
||||
helper.setText(R.id.tv_content,item.getTeb());
|
||||
if(helper.getLayoutPosition() == mSelPos){
|
||||
helper.setTextColor(R.id.tv_content,mContext.getColor(R.color.color_zhu));
|
||||
helper.setBackgroundRes(R.id.tv_content, R.drawable.shape_chat_zixun_type);
|
||||
}else{
|
||||
helper.setTextColor(R.id.tv_content,mContext.getColor(R.color.color_7A8699));
|
||||
helper.setBackgroundRes(R.id.tv_content, R.drawable.shape_trans_touming);
|
||||
}
|
||||
}
|
||||
|
||||
public void setSelectPos(int position) {
|
||||
this.mSelPos = position;
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
public int getmSelPos() {
|
||||
return mSelPos;
|
||||
}
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
package com.ckkj.griddle.chat.adapter;
|
||||
|
||||
import android.content.ClipData;
|
||||
import android.content.ClipboardManager;
|
||||
import android.content.Context;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
|
||||
import com.chad.library.adapter.base.BaseViewHolder;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.chat.entity.ChatAiMsgEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatMultiItem;
|
||||
import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
import com.ckkj.griddle.utils.stream.MarkdownStreamer;
|
||||
import com.lxj.xpopup.XPopup;
|
||||
import com.lxj.xpopup.interfaces.OnSelectListener;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class IndexChatAdapter extends BaseMultiItemQuickAdapter<ChatMultiItem, BaseViewHolder> {
|
||||
private Context mContext;
|
||||
private RecyclerView recyclerView;
|
||||
private OnStreamCompleteListener streamCompleteListener;
|
||||
//convert() 中每次绑定 item 时缓存 MarkdownStreamer 实例
|
||||
private final Map<Integer, MarkdownStreamer> streamerMap = new HashMap<>();
|
||||
|
||||
// Markwon 依赖已移除
|
||||
// private Markwon markwon;
|
||||
|
||||
// 新增:当前正在流式输出的位置
|
||||
private int mCurrentStreamingPosition = -1;
|
||||
// 用于标记哪个 position 需要显示 llTips
|
||||
// 在 IndexChatAdapter 类中新增字段
|
||||
private Integer pendingTipsCheckPos = null;
|
||||
// 新增:记录被停止的位置
|
||||
private final Map<Integer, Boolean> stoppedPositions = new HashMap<>();
|
||||
|
||||
public IndexChatAdapter(Context context, List<ChatMultiItem> data, RecyclerView recyclerView) {
|
||||
super(data);
|
||||
this.mContext = context;
|
||||
this.recyclerView = recyclerView;
|
||||
// this.markwon = Markwon.create(context);
|
||||
addItemType(ChatMultiItem.TYPE_TEXT_LEFT, R.layout.item_text_left);
|
||||
addItemType(ChatMultiItem.TYPE_TEXT_RIGHT, R.layout.item_text_right);
|
||||
}
|
||||
|
||||
public void setStreamerStop(int position) {
|
||||
MarkdownStreamer streamer = streamerMap.get(position);
|
||||
if (streamer != null) {
|
||||
streamer.stopStreaming();
|
||||
streamerMap.remove(position);
|
||||
}
|
||||
if (mCurrentStreamingPosition == position) {
|
||||
mCurrentStreamingPosition = -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 标记某个位置为被停止的状态
|
||||
*/
|
||||
public void markAsStopped(int position) {
|
||||
stoppedPositions.put(position, true);
|
||||
// 通知该位置更新显示
|
||||
notifyItemChanged(position);
|
||||
}
|
||||
|
||||
public interface OnStreamCompleteListener {
|
||||
void onStreamComplete(int position);
|
||||
void onStreamStop();
|
||||
}
|
||||
|
||||
public void setOnStreamCompleteListener(OnStreamCompleteListener listener) {
|
||||
this.streamCompleteListener = listener;
|
||||
}
|
||||
|
||||
// 新增:长按菜单项点击回调接口
|
||||
public interface OnItemLongClickMenuListener {
|
||||
void onCopyClick(ChatMultiItem item, int position);
|
||||
void onReportClick(ChatMultiItem item, int position);
|
||||
}
|
||||
|
||||
private OnItemLongClickMenuListener mLongClickMenuListener;
|
||||
|
||||
public void setOnItemLongClickMenuListener(OnItemLongClickMenuListener listener) {
|
||||
this.mLongClickMenuListener = listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前正在流式输出的位置
|
||||
*/
|
||||
public void setCurrentStreamingPosition(int position) {
|
||||
mCurrentStreamingPosition = position;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 对外暴露的方法:检查某个 position 是否为最后一条,并据此显示/隐藏 llTips。
|
||||
* 仅记录“待检查的位置”并触发该 position 的刷新;实际显示逻辑在 convert() 末尾统一处理。
|
||||
*/
|
||||
public void updateTipsVisibility(int position) {
|
||||
if (position < 0 || position >= getItemCount()) return;
|
||||
pendingTipsCheckPos = position;
|
||||
// notifyItemChanged(position);
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
public void setPendingTipsCheckPos(Integer pendingTipsCheckPos) {
|
||||
this.pendingTipsCheckPos = pendingTipsCheckPos;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void convert(BaseViewHolder helper, ChatMultiItem item) {
|
||||
ChatAiMsgEntity msgEntity = item.getMessage();
|
||||
TextView tvContent = helper.getView(R.id.tv_text);
|
||||
LinearLayout llThinking = helper.getView(R.id.linear_thinking);
|
||||
LinearLayout llStop = helper.getView(R.id.linear_stop);
|
||||
LinearLayout llTips = helper.getView(R.id.linear_tips);
|
||||
int position = helper.getBindingAdapterPosition();
|
||||
helper.addOnClickListener(R.id.img_jb);
|
||||
// helper.addOnLongClickListener(R.id.tv_text);
|
||||
|
||||
if (item.getItemType() == ChatMultiItem.TYPE_TEXT_LEFT) {
|
||||
String content = msgEntity.getContent();
|
||||
if(TextUtils.isEmpty(content)){
|
||||
llThinking.setVisibility(View.VISIBLE);
|
||||
tvContent.setText("");
|
||||
llStop.setVisibility(View.GONE);
|
||||
} else {
|
||||
llThinking.setVisibility(View.GONE);
|
||||
|
||||
// 优化流式输出更新逻辑
|
||||
if (position == mCurrentStreamingPosition) {
|
||||
// 当前正在流式输出的位置
|
||||
// Markwon 依赖已移除,直接显示原始内容
|
||||
tvContent.setText(content);
|
||||
|
||||
// 显示停止标识(如果被停止)
|
||||
if (stoppedPositions.containsKey(position) && stoppedPositions.get(position)) {
|
||||
llStop.setVisibility(View.VISIBLE);
|
||||
llTips.setVisibility(View.VISIBLE);
|
||||
} else {
|
||||
llStop.setVisibility(View.GONE);
|
||||
}
|
||||
} else {
|
||||
// 历史消息,直接显示完整内容
|
||||
// Markwon 依赖已移除,直接显示原始内容
|
||||
tvContent.setText(content);
|
||||
|
||||
// 历史消息也检查是否被停止
|
||||
if (stoppedPositions.containsKey(position) && stoppedPositions.get(position)) {
|
||||
llStop.setVisibility(View.VISIBLE);
|
||||
llTips.setVisibility(View.VISIBLE);
|
||||
} else {
|
||||
llStop.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
Log.i("mingdenglog","XXXXX---position======" + pendingTipsCheckPos);
|
||||
if (pendingTipsCheckPos != null && position == pendingTipsCheckPos) {
|
||||
Log.i("mingdenglog","position======" + position);
|
||||
Log.i("mingdenglog","getItemCount() - 1 ------" + (getItemCount() - 1) );
|
||||
// 仅当是最后一条才显示 llTips,否则隐藏
|
||||
llTips.setVisibility(position == getItemCount() - 1 ? View.VISIBLE : View.GONE);
|
||||
// 用一次即清
|
||||
// pendingTipsCheckPos = null;
|
||||
}else{
|
||||
llTips.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
|
||||
switch (item.getItemType()) {
|
||||
case ChatMultiItem.TYPE_TEXT_RIGHT:
|
||||
tvContent.setText(msgEntity.getContent());
|
||||
break;
|
||||
}
|
||||
|
||||
// //必须要在事件发生之前就watch
|
||||
final XPopup.Builder builder = new XPopup.Builder(mContext)
|
||||
.hasShadowBg(false).watchView(tvContent);
|
||||
tvContent.setOnLongClickListener(new View.OnLongClickListener() {
|
||||
@Override
|
||||
public boolean onLongClick(View v) {
|
||||
// 如果正在流式输出,则拦截长按事件,不执行任何操作
|
||||
if (mCurrentStreamingPosition != -1) {
|
||||
// 可以选择性地提示用户
|
||||
ToastUtil.showShort(mContext, "Ai解答中,请稍后操作");
|
||||
return true; // 拦截事件
|
||||
}
|
||||
|
||||
builder.asAttachList(new String[]{"复制", "举报"}, null, new OnSelectListener() {
|
||||
@Override
|
||||
public void onSelect(int menuPosition, String text) {
|
||||
// 通过接口回调处理菜单项点击事件
|
||||
if (mLongClickMenuListener != null) {
|
||||
switch (menuPosition){
|
||||
case 0: // 复制
|
||||
mLongClickMenuListener.onCopyClick(item, position);
|
||||
break;
|
||||
case 1: // 举报
|
||||
mLongClickMenuListener.onReportClick(item, position);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}).show();
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理缓存
|
||||
*/
|
||||
public void clearCache() {
|
||||
streamerMap.clear();
|
||||
stoppedPositions.clear();
|
||||
mCurrentStreamingPosition = -1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.ckkj.griddle.chat.adapter;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.chad.library.adapter.base.BaseQuickAdapter;
|
||||
import com.chad.library.adapter.base.BaseViewHolder;
|
||||
import com.ckkj.griddle.R;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class IndexEnterHintAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
|
||||
private Context mContext;
|
||||
private int mSelPos = 0;
|
||||
private String textColor;
|
||||
private String bgColor;
|
||||
|
||||
public void setColor(String textColor,String bgColor){
|
||||
this.textColor = textColor;
|
||||
this.bgColor = bgColor;
|
||||
}
|
||||
public IndexEnterHintAdapter(Context context, int layoutResId, @Nullable List<String> data) {
|
||||
super(layoutResId, data);
|
||||
this.mContext = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void convert(BaseViewHolder helper, String item) {
|
||||
helper.setText(R.id.tv_quick_ask_name,item);
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.ckkj.griddle.chat.adapter;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.chad.library.adapter.base.BaseQuickAdapter;
|
||||
import com.chad.library.adapter.base.BaseViewHolder;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class IndexOptionAdapter extends BaseQuickAdapter<IndexTemplateEntity, BaseViewHolder> {
|
||||
private Context mContext;
|
||||
private int mSelPos = 0;
|
||||
|
||||
public IndexOptionAdapter(Context context,int layoutResId, @Nullable List<IndexTemplateEntity> data) {
|
||||
super(layoutResId, data);
|
||||
this.mContext = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void convert(BaseViewHolder helper, IndexTemplateEntity item) {
|
||||
helper.setText(R.id.tv_option_name,item.getTitle());
|
||||
if(helper.getLayoutPosition() == mSelPos){
|
||||
helper.setTextColor(R.id.tv_option_name,mContext.getColor(R.color.white));
|
||||
helper.setBackgroundRes(R.id.tv_option_name, R.drawable.shape_index_option_selected);
|
||||
}else{
|
||||
helper.setTextColor(R.id.tv_option_name,mContext.getColor(R.color.color_zhu));
|
||||
helper.setBackgroundRes(R.id.tv_option_name, R.drawable.shape_index_option_un_selected);
|
||||
}
|
||||
}
|
||||
|
||||
public void setSelectPos(int position) {
|
||||
this.mSelPos = position;
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.ckkj.griddle.chat.adapter;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.util.TypedValue;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.chad.library.adapter.base.BaseQuickAdapter;
|
||||
import com.chad.library.adapter.base.BaseViewHolder;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
import com.ckkj.griddle.utils.manager.ColorManage;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/8
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class IndexQuickAskAdapter extends BaseQuickAdapter<IndexTemplateEntity, BaseViewHolder> {
|
||||
private Context context;
|
||||
public IndexQuickAskAdapter(Context context,int layoutResId, @Nullable List<IndexTemplateEntity> data) {
|
||||
super(layoutResId, data);
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void convert(BaseViewHolder helper, IndexTemplateEntity item) {
|
||||
helper.setText(R.id.tv_quick_ask_name,item.getSpliteItemContent());
|
||||
if(ColorManage.getInstance().isParsableColor(item.getColor())){
|
||||
helper.setTextColor(R.id.tv_quick_ask_name, Color.parseColor(item.getColor()));
|
||||
}else{
|
||||
helper.setTextColor(R.id.tv_quick_ask_name, ContextCompat.getColor(mContext,R.color.color_zhu));
|
||||
}
|
||||
if(ColorManage.getInstance().isParsableColor(item.getBlackcolor())){
|
||||
setRoundedBackground(helper.getView(R.id.tv_quick_ask_name),Color.parseColor(item.getBlackcolor()),30);
|
||||
}else{
|
||||
setRoundedBackground(helper.getView(R.id.tv_quick_ask_name),ContextCompat.getColor(mContext,R.color.color_E5F2FB),30);
|
||||
}
|
||||
}
|
||||
|
||||
private void setRoundedBackground(View view, int fillColor, float cornerRadiusDp) {
|
||||
GradientDrawable drawable = new GradientDrawable();
|
||||
drawable.setShape(GradientDrawable.RECTANGLE);
|
||||
drawable.setColor(fillColor); // 设置填充色
|
||||
float radiusPx = TypedValue.applyDimension(
|
||||
TypedValue.COMPLEX_UNIT_DIP, cornerRadiusDp, view.getResources().getDisplayMetrics()
|
||||
);
|
||||
drawable.setCornerRadius(radiusPx); // 设置圆角半径(单位:px)
|
||||
view.setBackground(drawable); // 应用背景
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package com.ckkj.griddle.chat.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/11
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class CharHistoryEntity implements Serializable {
|
||||
private int total;
|
||||
private List<Sessions> sessions;
|
||||
private int pages;
|
||||
private int pageSize;
|
||||
private long userId;
|
||||
private int pageNum;
|
||||
public void setTotal(int total) {
|
||||
this.total = total;
|
||||
}
|
||||
public int getTotal() {
|
||||
return total;
|
||||
}
|
||||
|
||||
public void setSessions(List<Sessions> sessions) {
|
||||
this.sessions = sessions;
|
||||
}
|
||||
public List<Sessions> getSessions() {
|
||||
return sessions;
|
||||
}
|
||||
|
||||
public void setPages(int pages) {
|
||||
this.pages = pages;
|
||||
}
|
||||
public int getPages() {
|
||||
return pages;
|
||||
}
|
||||
|
||||
public void setPageSize(int pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
public int getPageSize() {
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
public void setUserId(long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
public long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setPageNum(int pageNum) {
|
||||
this.pageNum = pageNum;
|
||||
}
|
||||
public int getPageNum() {
|
||||
return pageNum;
|
||||
}
|
||||
|
||||
|
||||
public static class Sessions implements Serializable{
|
||||
|
||||
private String sessionId;
|
||||
private long userId;
|
||||
private String sessionName;
|
||||
private String numerologyType;
|
||||
private String firstUserMessage;
|
||||
private Date createTime;
|
||||
private Date updateTime;
|
||||
public void setSessionId(String sessionId) {
|
||||
this.sessionId = sessionId;
|
||||
}
|
||||
public String getSessionId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public void setUserId(long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
public long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setSessionName(String sessionName) {
|
||||
this.sessionName = sessionName;
|
||||
}
|
||||
public String getSessionName() {
|
||||
return sessionName;
|
||||
}
|
||||
|
||||
public void setNumerologyType(String numerologyType) {
|
||||
this.numerologyType = numerologyType;
|
||||
}
|
||||
public String getNumerologyType() {
|
||||
return numerologyType;
|
||||
}
|
||||
|
||||
public void setFirstUserMessage(String firstUserMessage) {
|
||||
this.firstUserMessage = firstUserMessage;
|
||||
}
|
||||
public String getFirstUserMessage() {
|
||||
return firstUserMessage;
|
||||
}
|
||||
|
||||
public void setCreateTime(Date createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
public Date getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setUpdateTime(Date updateTime) {
|
||||
this.updateTime = updateTime;
|
||||
}
|
||||
public Date getUpdateTime() {
|
||||
return updateTime;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.ckkj.griddle.chat.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class ChatAiMsgEntity implements Serializable {
|
||||
private int id;
|
||||
private String sessionId;
|
||||
private String type;
|
||||
private String content;
|
||||
private String role;
|
||||
private String messageOrder;
|
||||
private String createTime;
|
||||
|
||||
public String getSessionId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public void setSessionId(String sessionId) {
|
||||
this.sessionId = sessionId;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getMessageOrder() {
|
||||
return messageOrder;
|
||||
}
|
||||
|
||||
public void setMessageOrder(String messageOrder) {
|
||||
this.messageOrder = messageOrder;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.ckkj.griddle.chat.entity;
|
||||
|
||||
import com.chad.library.adapter.base.entity.MultiItemEntity;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class ChatMultiItem implements MultiItemEntity {
|
||||
public static final int TYPE_TEXT_LEFT = 1;
|
||||
public static final int TYPE_TEXT_RIGHT = 2;
|
||||
public static final int TYPE_IMAGE_LEFT = 3;
|
||||
public static final int TYPE_IMAGE_RIGHT = 4;
|
||||
public static final int TYPE_VOICE_LEFT = 5;
|
||||
public static final int TYPE_VOICE_RIGHT = 6;
|
||||
public static final int TYPE_TIME = 7; // 新增时间类型
|
||||
|
||||
private int itemType;
|
||||
private ChatAiMsgEntity message;
|
||||
|
||||
public ChatMultiItem(int itemType, ChatAiMsgEntity message) {
|
||||
this.itemType = itemType;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemType() {
|
||||
return itemType;
|
||||
}
|
||||
|
||||
public void setItemType(int itemType) {
|
||||
this.itemType = itemType;
|
||||
}
|
||||
|
||||
public ChatAiMsgEntity getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(ChatAiMsgEntity message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.ckkj.griddle.chat.entity;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/8/19
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
@NoArgsConstructor
|
||||
@Data
|
||||
public class ChatQuestionEntity implements Serializable {
|
||||
|
||||
@SerializedName("teb")
|
||||
private String teb;
|
||||
@SerializedName("subheadings")
|
||||
private List<SubheadingsDTO> subheadings;
|
||||
@SerializedName("id")
|
||||
private String id;
|
||||
|
||||
@NoArgsConstructor
|
||||
@Data
|
||||
public static class SubheadingsDTO {
|
||||
@SerializedName("title")
|
||||
private String title;
|
||||
@SerializedName("content")
|
||||
private String content;
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package com.ckkj.griddle.chat.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/8
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class IndexTemplateEntity implements Serializable {
|
||||
private String id;
|
||||
private String title;
|
||||
private String titletp;
|
||||
private String color;
|
||||
private String blackcolor;
|
||||
private String subheading;
|
||||
private String intermediateContent;
|
||||
private String quickQuestions;
|
||||
private String hide;
|
||||
private String type;
|
||||
private String spliteItemContent;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getTitletp() {
|
||||
return titletp;
|
||||
}
|
||||
|
||||
public void setTitletp(String titletp) {
|
||||
this.titletp = titletp;
|
||||
}
|
||||
|
||||
public String getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(String color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public String getBlackcolor() {
|
||||
return blackcolor;
|
||||
}
|
||||
|
||||
public void setBlackcolor(String blackcolor) {
|
||||
this.blackcolor = blackcolor;
|
||||
}
|
||||
|
||||
public String getSubheading() {
|
||||
return subheading;
|
||||
}
|
||||
|
||||
public void setSubheading(String subheading) {
|
||||
this.subheading = subheading;
|
||||
}
|
||||
|
||||
public String getIntermediateContent() {
|
||||
return intermediateContent;
|
||||
}
|
||||
|
||||
public void setIntermediateContent(String intermediateContent) {
|
||||
this.intermediateContent = intermediateContent;
|
||||
}
|
||||
|
||||
public String getQuickQuestions() {
|
||||
return quickQuestions;
|
||||
}
|
||||
|
||||
public void setQuickQuestions(String quickQuestions) {
|
||||
this.quickQuestions = quickQuestions;
|
||||
}
|
||||
|
||||
public String getHide() {
|
||||
return hide;
|
||||
}
|
||||
|
||||
public void setHide(String hide) {
|
||||
this.hide = hide;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getSpliteItemContent() {
|
||||
return spliteItemContent;
|
||||
}
|
||||
|
||||
public void setSpliteItemContent(String spliteItemContent) {
|
||||
this.spliteItemContent = spliteItemContent;
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package com.ckkj.griddle.chat.mvp;
|
||||
|
||||
import com.ckkj.griddle.base.IView;
|
||||
import com.ckkj.griddle.chat.entity.CharHistoryEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatAiMsgEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatQuestionEntity;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class IndexContract {
|
||||
public interface DataModel{
|
||||
//发送消息给 AI
|
||||
void sendMsgToAi(Map<String,Object> map, CallBack callBack);
|
||||
//发送消息给 AI
|
||||
void sendMsgToAi(Map<String,Object> map, AiStreamCallback callBack);
|
||||
//停止当前请求
|
||||
void stopCurrentRequest();
|
||||
//获取首页数据
|
||||
void getIndexTemplateDatas(CallBack callBack);
|
||||
//获取会话历史
|
||||
void getHistoryChatDatas(Map<String,Object> map, CallBack callBack);
|
||||
//删除会话
|
||||
void deleteHistoryBySessionID(Map<String,Object> map, CallBack callBack);
|
||||
//根据会话 id,查询记录详情
|
||||
void getChatDetailById(Map<String,Object> map, CallBack callBack);
|
||||
//首页咨询模板
|
||||
void getChatemplateDatas(CallBack callBack);
|
||||
//举报好友
|
||||
void commitReport(Map<String,Object> map,CallBack callBack);
|
||||
}
|
||||
|
||||
public interface CallBack<T> {
|
||||
void success(T msg);
|
||||
void fail(String msg);
|
||||
}
|
||||
|
||||
public interface AiStreamCallback {
|
||||
void onMessage(String messageChunk); // 每次返回一段内容
|
||||
void onError(String error);
|
||||
void onComplete(String complateContent); // 结束
|
||||
void onSessionReceived(String sessionId); // 新增:接收sessionId
|
||||
void loginLost();
|
||||
}
|
||||
|
||||
public interface IndexView extends IView {
|
||||
//发送消息给 AI,获取结果
|
||||
void getTalkResultSuccess(ChatAiMsgEntity bean);
|
||||
//获取首页数据成功
|
||||
void getIndexTemplateSuccess(List<IndexTemplateEntity> list);
|
||||
// 新增流式回调方法
|
||||
void onStreamMessageReceived(String messageChunk);
|
||||
//完成
|
||||
void onStreamComplete(String complateMsg);
|
||||
//接收sessionId
|
||||
void onSessionReceived(String sessionId);
|
||||
//查询历史记录成功 g
|
||||
void getHistoryDataSuccess(CharHistoryEntity entity);
|
||||
//删除会话成功
|
||||
void deleteHistorySuccess(BaseBean bean,int delPos);
|
||||
//根据 id 查询会话详情
|
||||
void getChatDetailSuccess(List<ChatAiMsgEntity> list);
|
||||
//登录失效
|
||||
void loginLost();
|
||||
//获取首页聊天模板
|
||||
void getChatZixunSuccess(List<ChatQuestionEntity> list);
|
||||
//提交举报反馈成功
|
||||
void commitReportSuccess(BaseBean bean);
|
||||
}
|
||||
}
|
||||
@@ -1,575 +0,0 @@
|
||||
package com.ckkj.griddle.chat.mvp;
|
||||
|
||||
import static android.content.ContentValues.TAG;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.ckkj.griddle.AppConfig;
|
||||
import com.ckkj.griddle.chat.entity.CharHistoryEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatAiMsgEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatQuestionEntity;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.network.NetWorkManager;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.net.SocketTimeoutException;
|
||||
|
||||
import io.reactivex.Observer;
|
||||
import io.reactivex.android.schedulers.AndroidSchedulers;
|
||||
import io.reactivex.annotations.NonNull;
|
||||
import io.reactivex.disposables.Disposable;
|
||||
import io.reactivex.schedulers.Schedulers;
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Callback;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class IndexImpl implements IndexContract.DataModel{
|
||||
|
||||
@Override
|
||||
public void sendMsgToAi(Map<String, Object> map, IndexContract.CallBack callBack) {
|
||||
try {
|
||||
NetWorkManager.getRequest().indexTalkToAi(NetWorkManager.getToken(),map)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean<ChatAiMsgEntity>>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean<ChatAiMsgEntity> bean) {
|
||||
if(bean.getCode() == 200){
|
||||
callBack.success(bean.getData());
|
||||
}else{
|
||||
callBack.fail(bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callBack.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息给 AI - 流式版本
|
||||
* @param map
|
||||
* @param callBack
|
||||
*/
|
||||
private final OkHttpClient client = new OkHttpClient.Builder()
|
||||
.connectTimeout(60, TimeUnit.SECONDS) // 连接超时60秒
|
||||
.readTimeout(60, TimeUnit.SECONDS) // 读取超时60秒
|
||||
.writeTimeout(60, TimeUnit.SECONDS) // 写入超时60秒
|
||||
.callTimeout(60, TimeUnit.SECONDS) // 整个调用超时60秒
|
||||
.build();
|
||||
|
||||
private Call currentCall = null; // 新增:保存当前请求的Call对象
|
||||
private volatile boolean isRequestStopped = false; // 新增:标记是否已停止请求
|
||||
|
||||
@Override
|
||||
public void sendMsgToAi(Map<String, Object> map, IndexContract.AiStreamCallback callBack) {
|
||||
try {
|
||||
String finalUrl = AppConfig.BASE_URL + "mobile/context?" + buildQueryParams(map);
|
||||
Log.d(TAG, "Request URL: " + finalUrl);
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.addHeader("Authorization", "Bearer " + AppConfig.USER_TOKEN)
|
||||
.url(finalUrl)
|
||||
.get()
|
||||
.build();
|
||||
currentCall = client.newCall(request);
|
||||
isRequestStopped = false;
|
||||
|
||||
currentCall.enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
if (isRequestStopped) return; // 如果已停止,不处理失败回调
|
||||
|
||||
// 检查是否是超时异常
|
||||
String errorMessage = e.getMessage();
|
||||
if (e instanceof SocketTimeoutException ||
|
||||
(errorMessage != null && errorMessage.contains("timeout"))) {
|
||||
errorMessage = "请求超时,请稍后重试";
|
||||
}
|
||||
|
||||
String finalErrorMessage = errorMessage;
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (callBack != null) callBack.onError(finalErrorMessage);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(Call call, Response response) {
|
||||
if (isRequestStopped) return;
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (callBack != null) callBack.onError("请求失败: " + response.code());
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
InputStream inputStream = response.body().byteStream();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
|
||||
|
||||
try {
|
||||
reader.mark(1024); // 标记流的当前位置
|
||||
String peekLine = reader.readLine();
|
||||
reader.reset(); // 回到标记位置
|
||||
|
||||
// 判断是否是标准 JSON(非流式错误返回)
|
||||
if (peekLine != null && peekLine.trim().startsWith("{")) {
|
||||
StringBuilder jsonBuilder = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
jsonBuilder.append(line);
|
||||
}
|
||||
String responseJson = jsonBuilder.toString();
|
||||
|
||||
JSONObject json = new JSONObject(responseJson);
|
||||
int code = json.optInt("code", 0);
|
||||
String msg = json.optString("msg", "");
|
||||
if (code == 401) {
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (callBack != null) callBack.loginLost();
|
||||
});
|
||||
} else {
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (callBack != null) callBack.onError("未知错误: " + msg);
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 否则处理为 SSE 流式数据
|
||||
handleSSEStream(reader, callBack);
|
||||
|
||||
} catch (Exception e) {
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
// if (callBack != null) callBack.onError("响应异常: " + e.getMessage());
|
||||
});
|
||||
} finally {
|
||||
try {
|
||||
reader.close();
|
||||
response.close();
|
||||
} catch (IOException ignored) {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
} catch (Exception e) {
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (callBack != null) callBack.onError("请求异常: " + e.getMessage());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void handleSSEStream(BufferedReader reader, IndexContract.AiStreamCallback callBack) throws IOException {
|
||||
String line;
|
||||
StringBuilder accumulatedContent = new StringBuilder();
|
||||
StringBuilder lastLineBuffer = new StringBuilder();
|
||||
String currentEvent = null;
|
||||
String currentData = null;
|
||||
String sessionId = "";
|
||||
|
||||
while ((line = reader.readLine()) != null) {
|
||||
if (isRequestStopped) break;
|
||||
|
||||
if (line.startsWith("event:")) {
|
||||
currentEvent = line.substring(6).trim();
|
||||
} else if (line.startsWith("data:")) {
|
||||
currentData = line.substring(5).trim();
|
||||
|
||||
if ("session".equals(currentEvent)) {
|
||||
try {
|
||||
JsonObject sessionData = JsonParser.parseString(currentData).getAsJsonObject();
|
||||
sessionId = sessionData.get("sessionId").getAsString();
|
||||
if (callBack != null && !isRequestStopped) {
|
||||
callBack.onSessionReceived(sessionId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "解析session数据失败", e);
|
||||
}
|
||||
} else if ("chunk".equals(currentEvent)) {
|
||||
try {
|
||||
JsonObject chunkData = JsonParser.parseString(currentData).getAsJsonObject();
|
||||
String content = chunkData.get("content").getAsString();
|
||||
boolean hasNewline = chunkData.get("hasNewline").getAsBoolean();
|
||||
|
||||
if (isTableLineFragment(lastLineBuffer.toString(), content)) {
|
||||
lastLineBuffer.append(content);
|
||||
if (hasNewline) {
|
||||
accumulatedContent.append(lastLineBuffer).append("\n");
|
||||
lastLineBuffer.setLength(0);
|
||||
}
|
||||
} else {
|
||||
if (lastLineBuffer.length() > 0) {
|
||||
accumulatedContent.append(lastLineBuffer);
|
||||
lastLineBuffer.setLength(0);
|
||||
}
|
||||
lastLineBuffer.append(content);
|
||||
if (hasNewline) {
|
||||
accumulatedContent.append(lastLineBuffer).append("\n");
|
||||
lastLineBuffer.setLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
final String currentContent = accumulatedContent.toString();
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (callBack != null && !isRequestStopped) {
|
||||
callBack.onMessage(currentContent);
|
||||
}
|
||||
});
|
||||
|
||||
} catch (Exception e) {
|
||||
accumulatedContent.append(currentData);
|
||||
final String currentContent = accumulatedContent.toString();
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (callBack != null && !isRequestStopped) {
|
||||
callBack.onMessage(currentContent);
|
||||
}
|
||||
});
|
||||
}
|
||||
} else if ("complete".equals(currentEvent)) {
|
||||
// 先处理剩余的 lastLineBuffer 内容,但不通过 onMessage 回调
|
||||
if (lastLineBuffer.length() > 0) {
|
||||
accumulatedContent.append(lastLineBuffer);
|
||||
// 注意:这里不调用 callBack.onMessage(),避免触发 onStreamMessageReceived
|
||||
}
|
||||
|
||||
String complateContent = "";
|
||||
try {
|
||||
JsonObject completeData = JsonParser.parseString(currentData).getAsJsonObject();
|
||||
complateContent = completeData.get("fullResponse").getAsString();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "解析complete数据失败", e);
|
||||
}
|
||||
|
||||
final String finalComplateContent = complateContent;
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (callBack != null && !isRequestStopped) {
|
||||
callBack.onComplete(finalComplateContent); // 只调用 onComplete
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理结束前残留内容
|
||||
// if (lastLineBuffer.length() > 0 && !isRequestStopped) {
|
||||
// accumulatedContent.append(lastLineBuffer);
|
||||
// final String finalContent = accumulatedContent.toString();
|
||||
// new Handler(Looper.getMainLooper()).post(() -> {
|
||||
// if (callBack != null && !isRequestStopped) {
|
||||
// callBack.onMessage(finalContent);
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止当前请求
|
||||
*/
|
||||
public void stopCurrentRequest() {
|
||||
isRequestStopped = true;
|
||||
if (currentCall != null && !currentCall.isCanceled()) {
|
||||
currentCall.cancel();
|
||||
currentCall = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是表格分隔线片段
|
||||
*/
|
||||
private boolean isTableLineFragment(String last, String curr) {
|
||||
return (last.contains("|") && last.contains("-")) || (curr.contains("|") && curr.contains("-"));
|
||||
}
|
||||
|
||||
// 构造 GET 参数
|
||||
private String buildQueryParams(Map<String, Object> map) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
try {
|
||||
if (sb.length() > 0) sb.append("&");
|
||||
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
|
||||
sb.append("=");
|
||||
sb.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Encoding error", e);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取首页数据
|
||||
*/
|
||||
@Override
|
||||
public void getIndexTemplateDatas(IndexContract.CallBack callBack) {
|
||||
try {
|
||||
NetWorkManager.getRequest().getIndexTemplateDatas()
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean<List<IndexTemplateEntity>>>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean<List<IndexTemplateEntity>> bean) {
|
||||
if(bean.getCode() == 200){
|
||||
callBack.success(bean.getData());
|
||||
}else{
|
||||
callBack.fail(bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callBack.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取会话历史记录
|
||||
* @param map
|
||||
* @param callBack
|
||||
*/
|
||||
@Override
|
||||
public void getHistoryChatDatas(Map<String, Object> map, IndexContract.CallBack callBack) {
|
||||
try {
|
||||
NetWorkManager.getRequest().getHistoryList(NetWorkManager.getToken(),map)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean<CharHistoryEntity>>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean<CharHistoryEntity> bean) {
|
||||
if(bean.getCode() == 200){
|
||||
callBack.success(bean.getData());
|
||||
}else{
|
||||
callBack.fail(bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callBack.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除历史会话
|
||||
* @param map
|
||||
* @param callBack
|
||||
*/
|
||||
@Override
|
||||
public void deleteHistoryBySessionID(Map<String, Object> map, IndexContract.CallBack callBack) {
|
||||
try {
|
||||
NetWorkManager.getRequest().deleteHistoryBySessionID(NetWorkManager.getToken(),map)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean bean) {
|
||||
if(bean.getCode() == 200){
|
||||
callBack.success(bean);
|
||||
}else{
|
||||
callBack.fail(bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callBack.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 根据会话 id 查询详情
|
||||
* @param map
|
||||
* @param callBack
|
||||
*/
|
||||
@Override
|
||||
public void getChatDetailById(Map<String, Object> map, IndexContract.CallBack callBack) {
|
||||
try {
|
||||
NetWorkManager.getRequest().getChatDetailById(NetWorkManager.getToken(),map)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean<List<ChatAiMsgEntity>>>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean<List<ChatAiMsgEntity>> bean) {
|
||||
if(bean.getCode() == 200){
|
||||
callBack.success(bean.getData());
|
||||
}else{
|
||||
callBack.fail(bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callBack.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对话页,咨询模板获取
|
||||
* @param callBack
|
||||
*/
|
||||
@Override
|
||||
public void getChatemplateDatas(IndexContract.CallBack callBack) {
|
||||
try {
|
||||
NetWorkManager.getRequest().aitebcontent()
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean<List<ChatQuestionEntity>>>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean<List<ChatQuestionEntity>> bean) {
|
||||
if(bean.getCode() == 200){
|
||||
callBack.success(bean.getData());
|
||||
}else{
|
||||
callBack.fail(bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callBack.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 举报反馈
|
||||
* @param map
|
||||
* @param callBack
|
||||
*/
|
||||
@Override
|
||||
public void commitReport(Map<String, Object> map, IndexContract.CallBack callBack) {
|
||||
try {
|
||||
NetWorkManager.getRequest().commitReporting(NetWorkManager.getToken(),map)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean bean) {
|
||||
if(bean.getCode() == 200){
|
||||
callBack.success(bean.getData());
|
||||
}else{
|
||||
callBack.fail(bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callBack.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
package com.ckkj.griddle.chat.mvp;
|
||||
|
||||
import com.ckkj.griddle.EventMessage;
|
||||
import com.ckkj.griddle.base.BasePresenter;
|
||||
import com.ckkj.griddle.chat.entity.CharHistoryEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatAiMsgEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatQuestionEntity;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import de.greenrobot.event.EventBus;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/7
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class IndexPresenter extends BasePresenter<IndexContract.IndexView> {
|
||||
private IndexImpl impl;
|
||||
|
||||
public IndexPresenter(IndexImpl impl) {
|
||||
this.impl = impl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息给 AI
|
||||
*
|
||||
* @param content
|
||||
*/
|
||||
// public void talkToAi(String content,String type) {
|
||||
// Map<String,Object> map = new HashMap<>();
|
||||
// map.put("content",content);
|
||||
// map.put("type",type);
|
||||
// map.put("sessionId","");
|
||||
// impl.sendMsgToAi(map, new IndexContract.CallBack<ChatAiMsgEntity>() {
|
||||
// @Override
|
||||
// public void success(ChatAiMsgEntity bean) {
|
||||
// if( IndexPresenter.this.getView() != null){
|
||||
// IndexPresenter.this.getView().getTalkResultSuccess(bean);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void fail(String msg) {
|
||||
// if( IndexPresenter.this.getView() != null){
|
||||
// IndexPresenter.this.getView().showError(msg);
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
public void talkToAi(String content, String type, String sessionID) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("content", content);
|
||||
map.put("type", type);
|
||||
map.put("sessionId", sessionID);
|
||||
|
||||
impl.sendMsgToAi(map, new IndexContract.AiStreamCallback() {
|
||||
@Override
|
||||
public void onMessage(String messageChunk) {
|
||||
// 流式数据到达时,通知View更新UI
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().onStreamMessageReceived(messageChunk);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(String msg) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().showError(msg);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete(String complateMsg) {
|
||||
// 流式传输完成
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().onStreamComplete(complateMsg);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSessionReceived(String sessionId) {
|
||||
// 接收到sessionId时,通知View
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().onSessionReceived(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loginLost() {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().loginLost();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止当前流式请求
|
||||
*/
|
||||
public void stopCurrentRequest() {
|
||||
impl.stopCurrentRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
* 首页模板消息数据获取
|
||||
*/
|
||||
public void getIndexTemplateDatas() {
|
||||
impl.getIndexTemplateDatas(new IndexContract.CallBack<List<IndexTemplateEntity>>() {
|
||||
@Override
|
||||
public void success(List<IndexTemplateEntity> list) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().getIndexTemplateSuccess(list);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String msg) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().showError(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取历史记录
|
||||
* @param mCurrentPage
|
||||
*/
|
||||
public void getHistoryDatas(int mCurrentPage) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("pageNum", mCurrentPage);
|
||||
map.put("pageSize", 10);
|
||||
impl.getHistoryChatDatas(map, new IndexContract.CallBack<CharHistoryEntity>() {
|
||||
@Override
|
||||
public void success(CharHistoryEntity entity) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().getHistoryDataSuccess(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String msg) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().showError(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 删除历史记录
|
||||
* @param sessionID
|
||||
*/
|
||||
public void deleteHistoryBySessionID(String sessionID,int delPos) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("sessionId", sessionID);
|
||||
impl.deleteHistoryBySessionID(map, new IndexContract.CallBack<BaseBean>() {
|
||||
@Override
|
||||
public void success(BaseBean entity) {
|
||||
EventBus.getDefault().post(new EventMessage(EventMessage.HISTORY_SESSIONID_DELETE_SUCCESS,sessionID));
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().deleteHistorySuccess(entity,delPos);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String msg) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().showError(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 根据sessionID 查询消息记录
|
||||
* @param sessionId
|
||||
*/
|
||||
public void getChatDetailByID(String sessionId) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("sessionId", sessionId);
|
||||
impl.getChatDetailById(map, new IndexContract.CallBack<List<ChatAiMsgEntity>>() {
|
||||
@Override
|
||||
public void success(List<ChatAiMsgEntity> list) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().getChatDetailSuccess(list);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String msg) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().showError(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取首页咨询会话模板
|
||||
*/
|
||||
public void getChatTemplateDatas() {
|
||||
impl.getChatemplateDatas(new IndexContract.CallBack<List<ChatQuestionEntity>>() {
|
||||
@Override
|
||||
public void success(List<ChatQuestionEntity> list) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().getChatZixunSuccess(list);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String msg) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().showError(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 举报
|
||||
* @param reason
|
||||
*/
|
||||
public void commitReport(String reason) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("content", reason);
|
||||
impl.commitReport(map, new IndexContract.CallBack<BaseBean>() {
|
||||
@Override
|
||||
public void success(BaseBean bean) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().commitReportSuccess(bean);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String msg) {
|
||||
if (IndexPresenter.this.getView() != null) {
|
||||
IndexPresenter.this.getView().showError(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.ckkj.griddle.custom.view;
|
||||
|
||||
import android.animation.ValueAnimator;
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.RectF;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.view.animation.DecelerateInterpolator;
|
||||
|
||||
/** 配网进度环:浅橙色完整底环,叠加两端为半圆的橙色进度弧。 */
|
||||
public class ProvisionProgressView extends View {
|
||||
private static final int PROGRESS_COLOR = 0xFFFF6900;
|
||||
private static final int TRACK_COLOR = 0xFFFFE3CC;
|
||||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final RectF arcBounds = new RectF();
|
||||
private final float strokeWidth;
|
||||
private final float inset;
|
||||
private float displayedProgress;
|
||||
private int progress;
|
||||
private ValueAnimator progressAnimator;
|
||||
|
||||
public ProvisionProgressView(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
public ProvisionProgressView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
float density = getResources().getDisplayMetrics().density;
|
||||
strokeWidth = 12f * density;
|
||||
inset = 3f * density;
|
||||
paint.setStyle(Paint.Style.STROKE);
|
||||
paint.setStrokeWidth(strokeWidth);
|
||||
paint.setStrokeCap(Paint.Cap.ROUND);
|
||||
// 只在布局预览中显示示例进度,运行时仍从真实设备阶段开始。
|
||||
if (isInEditMode()) {
|
||||
progress = 70;
|
||||
displayedProgress = progress;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
super.onDraw(canvas);
|
||||
float centerX = getPaddingLeft()
|
||||
+ (getWidth() - getPaddingLeft() - getPaddingRight()) / 2f;
|
||||
float centerY = getPaddingTop()
|
||||
+ (getHeight() - getPaddingTop() - getPaddingBottom()) / 2f;
|
||||
float radius = (Math.min(getWidth() - getPaddingLeft() - getPaddingRight(),
|
||||
getHeight() - getPaddingTop() - getPaddingBottom()) - strokeWidth) / 2f - inset;
|
||||
if (radius <= 0f) return;
|
||||
arcBounds.set(centerX - radius, centerY - radius, centerX + radius, centerY + radius);
|
||||
|
||||
// 先绘制整圈浅橙色轨道,尚未完成的部分始终可见。
|
||||
paint.setColor(TRACK_COLOR);
|
||||
canvas.drawCircle(centerX, centerY, radius, paint);
|
||||
paint.setColor(PROGRESS_COLOR);
|
||||
if (displayedProgress >= 100f) {
|
||||
// 完成时直接画整圈,避免圆弧闭合处出现接缝。
|
||||
canvas.drawCircle(centerX, centerY, radius, paint);
|
||||
} else if (displayedProgress > 0f) {
|
||||
// -90 度从正上方起步,正角度顺时针增长,ROUND 保留两端圆弧。
|
||||
canvas.drawArc(arcBounds, -90f, 360f * displayedProgress / 100f, false, paint);
|
||||
}
|
||||
}
|
||||
|
||||
/** 更新真实进度;连续回调从当前显示位置平滑过渡。 */
|
||||
public void setProgressCompat(int value, boolean animated) {
|
||||
if (progressAnimator != null) {
|
||||
progressAnimator.cancel();
|
||||
progressAnimator = null;
|
||||
}
|
||||
progress = Math.max(0, Math.min(100, value));
|
||||
if (!animated || !isAttachedToWindow()) {
|
||||
displayedProgress = progress;
|
||||
invalidate();
|
||||
return;
|
||||
}
|
||||
progressAnimator = ValueAnimator.ofFloat(displayedProgress, progress);
|
||||
progressAnimator.setDuration(300L);
|
||||
progressAnimator.setInterpolator(new DecelerateInterpolator());
|
||||
progressAnimator.addUpdateListener(animation -> {
|
||||
displayedProgress = (float) animation.getAnimatedValue();
|
||||
invalidate();
|
||||
});
|
||||
progressAnimator.start();
|
||||
}
|
||||
|
||||
public int getProgress() {
|
||||
return progress;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDetachedFromWindow() {
|
||||
if (progressAnimator != null) {
|
||||
progressAnimator.cancel();
|
||||
progressAnimator = null;
|
||||
}
|
||||
displayedProgress = progress;
|
||||
super.onDetachedFromWindow();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ckkj.griddle.device;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
/** 首页授权和扫描页面使用同一组权限,避免入口检查与扫描条件不一致。 */
|
||||
public final class BleScanPermissions {
|
||||
private BleScanPermissions() { }
|
||||
|
||||
/** 按系统版本返回扫描所需的动态权限,不在此工具类中弹窗或发起申请。 */
|
||||
public static String[] requiredPermissions() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
// Android 12 起使用附近设备权限:SCAN 用于扫描,CONNECT 用于读取设备信息和请求开启蓝牙。
|
||||
return new String[]{Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT};
|
||||
}
|
||||
// Android 8~11 的 BLE 扫描需要位置权限,旧版蓝牙权限已在清单中声明。
|
||||
return new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
|
||||
}
|
||||
|
||||
/** 必须全部授权才返回 true,避免只获得部分权限时进入扫描流程。 */
|
||||
public static boolean hasPermissions(Context context) {
|
||||
for (String permission : requiredPermissions()) {
|
||||
if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,32 @@
|
||||
package com.ckkj.griddle.device;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.location.LocationManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.provider.Settings;
|
||||
import android.text.TextUtils;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.activity.result.ActivityResultLauncher;
|
||||
import androidx.activity.result.contract.ActivityResultContracts;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
|
||||
import com.gyf.immersionbar.ImmersionBar;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.base.BaseActivity;
|
||||
import com.ckkj.griddle.databinding.BlDeviceListBinding;
|
||||
import com.ckkj.griddle.device.adapter.BltDeviceListAdapter;
|
||||
import com.ckkj.griddle.device.entity.BleScanDevice;
|
||||
import com.ckkj.griddle.device.mvp.BltDeviceListContract;
|
||||
import com.ckkj.griddle.device.mvp.BltDeviceListImpl;
|
||||
import com.ckkj.griddle.device.mvp.BltDeviceListPresenter;
|
||||
@@ -14,12 +34,72 @@ import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
|
||||
/**
|
||||
* 蓝牙设备列表
|
||||
* 电饼铛蓝牙扫描列表:负责扫描前置条件、页面状态和扫描结果展示。
|
||||
* 动态权限由设备首页申请;先建立 BLE 连接,再进入下一页展示连接状态及设备能力。
|
||||
*/
|
||||
public class BltDeviceListActivity
|
||||
extends BaseActivity<BlDeviceListBinding, BltDeviceListPresenter>
|
||||
implements BltDeviceListContract.BltDeviceListView {
|
||||
|
||||
private final BltDeviceListAdapter deviceAdapter = new BltDeviceListAdapter();
|
||||
// 系统弹窗返回时页面可能尚未恢复,使用这两个标记延迟到前台再启动扫描。
|
||||
private boolean resumed;
|
||||
private boolean pendingScan = true;
|
||||
private GriddleProvisioningSession provisioning;
|
||||
private String connectionToken;
|
||||
private boolean openingWifi;
|
||||
private final GriddleProvisioningSession.Listener connectionListener = this::renderConnection;
|
||||
|
||||
// 请求用户开启蓝牙后,仅在用户同意时继续扫描;这不是动态权限申请。
|
||||
private final ActivityResultLauncher<Intent> bluetoothLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.StartActivityForResult(), result -> {
|
||||
if (result.getResultCode() == Activity.RESULT_OK) {
|
||||
scanWhenResumed();
|
||||
} else {
|
||||
onScanError(R.string.bl_device_bluetooth_off);
|
||||
}
|
||||
});
|
||||
|
||||
// 从定位设置返回后重新检查条件,用户没有开启开关时不反复弹出设置页面。
|
||||
private final ActivityResultLauncher<Intent> settingsLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.StartActivityForResult(), result -> {
|
||||
if (!hasScanPermissions()) {
|
||||
onScanError(R.string.bl_device_permission_home_required);
|
||||
} else if (!isLegacyLocationEnabled()) {
|
||||
onScanError(R.string.bl_device_location_required);
|
||||
} else {
|
||||
scanWhenResumed();
|
||||
}
|
||||
});
|
||||
|
||||
// Wi-Fi 页面退出后释放旧会话并重新搜索,返回时可直接选择其他设备。
|
||||
private final ActivityResultLauncher<Intent> wifiLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.StartActivityForResult(), result -> {
|
||||
provisioning.close(connectionToken);
|
||||
connectionToken = null;
|
||||
openingWifi = false;
|
||||
scanWhenResumed();
|
||||
});
|
||||
|
||||
// 扫描过程中蓝牙或旧版系统定位被关闭时,立即停止扫描并更新提示。
|
||||
private final BroadcastReceiver scanEnvironmentReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (!resumed) return;
|
||||
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
|
||||
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
|
||||
if (state == BluetoothAdapter.STATE_TURNING_OFF || state == BluetoothAdapter.STATE_OFF) {
|
||||
mPresenter.stopScan();
|
||||
onScanError(R.string.bl_device_bluetooth_off);
|
||||
}
|
||||
} else if (LocationManager.MODE_CHANGED_ACTION.equals(intent.getAction())
|
||||
&& !isLegacyLocationEnabled()) {
|
||||
mPresenter.stopScan();
|
||||
onScanError(R.string.bl_device_location_required);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public BltDeviceListPresenter createPresenter() {
|
||||
return new BltDeviceListPresenter(new BltDeviceListImpl());
|
||||
@@ -32,7 +112,225 @@ public class BltDeviceListActivity
|
||||
.statusBarColor(R.color.device_home_background)
|
||||
.statusBarDarkFont(true)
|
||||
.init();
|
||||
// 列表布局已配置 LinearLayoutManager,后续接入扫描适配器与重新搜索事件。
|
||||
viewBinding.rvDevices.setAdapter(deviceAdapter);
|
||||
// RSSI 持续变化时避免列表项反复闪烁。
|
||||
viewBinding.rvDevices.setItemAnimator(null);
|
||||
viewBinding.llSearchAgain.setOnClickListener(v -> requestScan());
|
||||
provisioning = GriddleProvisioningSession.get(this);
|
||||
if (savedInstanceState != null) {
|
||||
connectionToken = savedInstanceState.getString("connection_token");
|
||||
openingWifi = savedInstanceState.getBoolean("opening_wifi");
|
||||
}
|
||||
deviceAdapter.setOnDeviceClickListener(this::connectDevice);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
// 接收器只在页面启动期间注册,并在 onStop 中成对注销。
|
||||
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
|
||||
filter.addAction(LocationManager.MODE_CHANGED_ACTION);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
registerReceiver(scanEnvironmentReceiver, filter, Context.RECEIVER_EXPORTED);
|
||||
} else {
|
||||
registerReceiver(scanEnvironmentReceiver, filter);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
resumed = true;
|
||||
if (connectionToken != null && !provisioning.matches(connectionToken)) connectionToken = null;
|
||||
provisioning.attach(connectionListener);
|
||||
// 首次进入、蓝牙开启成功或扫描被页面暂停打断时,执行待处理的扫描。
|
||||
if (pendingScan && connectionToken == null && !openingWifi) {
|
||||
pendingScan = false;
|
||||
requestScan();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
resumed = false;
|
||||
provisioning.detach(connectionListener);
|
||||
hideDialogLoading();
|
||||
if (mPresenter != null) {
|
||||
// 只记录尚未完成的扫描,正常超时结束的扫描不会因返回前台而自动重启。
|
||||
pendingScan = pendingScan || mPresenter.isScanning();
|
||||
mPresenter.stopScan();
|
||||
}
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
unregisterReceiver(scanEnvironmentReceiver);
|
||||
super.onStop();
|
||||
}
|
||||
|
||||
/** 前台可立即扫描;若仍处于系统弹窗切换过程,则交给 onResume 执行。 */
|
||||
private void scanWhenResumed() {
|
||||
pendingScan = true;
|
||||
if (resumed) {
|
||||
pendingScan = false;
|
||||
requestScan();
|
||||
}
|
||||
}
|
||||
|
||||
/** 与首页共用权限定义,防止两个页面的判断条件不一致。 */
|
||||
private boolean hasScanPermissions() {
|
||||
return BleScanPermissions.hasPermissions(this);
|
||||
}
|
||||
|
||||
/** Android 11 及以下额外检查系统定位开关;本功能在 Android 12 起不依赖定位。 */
|
||||
private boolean isLegacyLocationEnabled() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) return true;
|
||||
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
|
||||
if (manager == null) return false;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) return manager.isLocationEnabled();
|
||||
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|
||||
|| manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
|
||||
}
|
||||
|
||||
/** 依次检查页面状态、硬件、权限、蓝牙开关和定位条件,全部满足后才交给数据层扫描。 */
|
||||
@SuppressLint("MissingPermission")
|
||||
private void requestScan() {
|
||||
if (!resumed || mPresenter.isScanning() || connectionToken != null || openingWifi) return;
|
||||
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
|
||||
onScanError(R.string.bl_device_not_supported);
|
||||
return;
|
||||
}
|
||||
if (!hasScanPermissions()) {
|
||||
// 授权说明和系统申请统一由设备首页的添加入口触发。
|
||||
onScanError(R.string.bl_device_permission_home_required);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
BluetoothAdapter adapter = manager == null ? null : manager.getAdapter();
|
||||
if (adapter == null) {
|
||||
onScanError(R.string.bl_device_not_supported);
|
||||
return;
|
||||
}
|
||||
if (!adapter.isEnabled()) {
|
||||
bluetoothLauncher.launch(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
|
||||
return;
|
||||
}
|
||||
if (!isLegacyLocationEnabled()) {
|
||||
onScanError(R.string.bl_device_location_required);
|
||||
showSettingsDialog(R.string.bl_device_location_required,
|
||||
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
|
||||
return;
|
||||
}
|
||||
mPresenter.startScan(getApplicationContext());
|
||||
} catch (SecurityException e) {
|
||||
onScanError(R.string.bl_device_permission_home_required);
|
||||
} catch (ActivityNotFoundException | IllegalStateException e) {
|
||||
onScanError(R.string.bl_device_scan_failed);
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户确认后才打开系统设置,避免定位未开启时直接跳转。 */
|
||||
private void showSettingsDialog(int messageResId, Intent settingsIntent) {
|
||||
if (isFinishing() || isDestroyed()) return;
|
||||
new AlertDialog.Builder(this)
|
||||
.setMessage(messageResId)
|
||||
.setNegativeButton(android.R.string.cancel, null)
|
||||
.setPositiveButton(R.string.bl_device_open_settings, (dialog, which) -> {
|
||||
try {
|
||||
settingsLauncher.launch(settingsIntent);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
onScanError(messageResId);
|
||||
}
|
||||
})
|
||||
.show();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeviceFound(BleScanDevice device) {
|
||||
// 数据层已按协议过滤,适配器继续按地址去重,因此数量只统计符合条件的不同设备。
|
||||
deviceAdapter.updateDevice(device);
|
||||
updateScanStatus(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanStateChanged(boolean scanning) {
|
||||
// 每轮扫描重新收集结果;扫描期间禁用重复搜索,避免频繁触发系统扫描限制。
|
||||
if (scanning) deviceAdapter.clear();
|
||||
viewBinding.scanProgress.setVisibility(scanning ? View.VISIBLE : View.GONE);
|
||||
viewBinding.llSearchAgain.setEnabled(!scanning);
|
||||
viewBinding.llSearchAgain.setAlpha(scanning ? 0.5f : 1f);
|
||||
viewBinding.tvSearchAgain.setText(scanning
|
||||
? R.string.bl_device_searching : R.string.bl_device_search_again);
|
||||
updateScanStatus(scanning);
|
||||
}
|
||||
|
||||
/** 根据扫描状态与去重后的数量,展示搜索中、搜索结束或空列表文案。 */
|
||||
private void updateScanStatus(boolean scanning) {
|
||||
int count = deviceAdapter.getItemCount();
|
||||
if (scanning) {
|
||||
viewBinding.tvScanStatus.setText(getString(R.string.bl_device_scanning_count, count));
|
||||
} else if (count == 0) {
|
||||
viewBinding.tvScanStatus.setText(R.string.bl_device_scan_empty);
|
||||
} else {
|
||||
viewBinding.tvScanStatus.setText(getString(R.string.bl_device_scan_finished, count));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanError(int messageResId) {
|
||||
viewBinding.tvScanStatus.setText(messageResId);
|
||||
}
|
||||
|
||||
/** 扫描和连接互斥;连接期间忽略重复点击,loading 返回键可取消本次连接。 */
|
||||
private void connectDevice(BleScanDevice device) {
|
||||
if (!resumed || connectionToken != null || openingWifi) return;
|
||||
if (!hasScanPermissions()) { onScanError(R.string.bl_device_permission_home_required); return; }
|
||||
mPresenter.stopScan();
|
||||
pendingScan = false;
|
||||
connectionToken = provisioning.connect(device);
|
||||
renderConnection();
|
||||
}
|
||||
|
||||
private void renderConnection() {
|
||||
if (!resumed || connectionToken == null || !provisioning.matches(connectionToken)) return;
|
||||
if (provisioning.getState() == GriddleProvisioningSession.State.CONNECTING) {
|
||||
viewBinding.llSearchAgain.setEnabled(false);
|
||||
viewBinding.tvScanStatus.setText(R.string.wifi_setup_connecting);
|
||||
if (mLoadingDialog == null || !mLoadingDialog.isShowing()) showLoadingDialog();
|
||||
} else if (provisioning.isConnected() && !openingWifi) {
|
||||
hideDialogLoading();
|
||||
openingWifi = true;
|
||||
Intent intent = new Intent(this, WifiListActivity.class);
|
||||
intent.putExtra(WifiListActivity.EXTRA_SESSION_TOKEN, connectionToken);
|
||||
// 会话所有权交给 Wi-Fi 页面;当前页留在返回栈,离开前台时只停止扫描。
|
||||
wifiLauncher.launch(intent);
|
||||
} else if (provisioning.getState() == GriddleProvisioningSession.State.FAILED) {
|
||||
hideDialogLoading();
|
||||
int error = provisioning.getErrorRes();
|
||||
provisioning.close(connectionToken);
|
||||
connectionToken = null;
|
||||
viewBinding.llSearchAgain.setEnabled(true);
|
||||
viewBinding.tvScanStatus.setText(error);
|
||||
ToastUtil.showShort(this, getString(error));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSaveInstanceState(Bundle outState) {
|
||||
outState.putString("connection_token", connectionToken);
|
||||
outState.putBoolean("opening_wifi", openingWifi);
|
||||
super.onSaveInstanceState(outState);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
if (provisioning != null) {
|
||||
provisioning.detach(connectionListener);
|
||||
if (!isChangingConfigurations() && !openingWifi) provisioning.close(connectionToken);
|
||||
}
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.ckkj.griddle.device;
|
||||
|
||||
import android.content.res.ColorStateList;
|
||||
import android.graphics.Paint;
|
||||
import android.os.Bundle;
|
||||
import android.text.TextUtils;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.activity.OnBackPressedCallback;
|
||||
import androidx.appcompat.content.res.AppCompatResources;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.base.BaseActivity;
|
||||
import com.ckkj.griddle.databinding.DeviceWifiConnectBinding;
|
||||
import com.ckkj.griddle.device.entity.BleScanDevice;
|
||||
import com.ckkj.griddle.device.entity.WifiProvisioningProgress;
|
||||
import com.ckkj.griddle.device.mvp.BltDeviceListContract;
|
||||
import com.ckkj.griddle.device.mvp.BltDeviceListPresenter;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
import com.gyf.immersionbar.ImmersionBar;
|
||||
|
||||
/** 配网过渡页面:复用已提交的会话,通过 SDK 回调更新现有进度环和步骤。 */
|
||||
public class DeviceConnectingActivity extends BaseActivity<DeviceWifiConnectBinding, BltDeviceListPresenter>
|
||||
implements BltDeviceListContract.BltDeviceListView {
|
||||
private GriddleProvisioningSession provisioning;
|
||||
private String connectionToken;
|
||||
private final GriddleProvisioningSession.Listener sessionListener = this::renderSession;
|
||||
|
||||
@Override
|
||||
public void initData(Bundle savedInstanceState) {
|
||||
super.initData(savedInstanceState);
|
||||
ImmersionBar.with(this).statusBarColor(android.R.color.white).statusBarDarkFont(true)
|
||||
.navigationBarColor(android.R.color.white).init();
|
||||
provisioning = GriddleProvisioningSession.get(this);
|
||||
connectionToken = getIntent().getStringExtra(WifiListActivity.EXTRA_SESSION_TOKEN);
|
||||
viewBinding.tvCancelSetup.setPaintFlags(viewBinding.tvCancelSetup.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
|
||||
viewBinding.tvCancelSetup.setOnClickListener(v -> cancelProvisioning());
|
||||
// 同时兼容按键与手势返回,不能仅关闭页面而留下正在执行的配网任务。
|
||||
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
|
||||
@Override public void handleOnBackPressed() {
|
||||
if (provisioning.getState() == GriddleProvisioningSession.State.PROVISIONING) {
|
||||
cancelProvisioning();
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
// 进入页面只订阅现有进度,不重新连接蓝牙、不重复提交 SSID/密码。
|
||||
provisioning.attach(sessionListener);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
provisioning.detach(sessionListener);
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
private void renderSession() {
|
||||
if (isFinishing() || isDestroyed()) return;
|
||||
if (!provisioning.matches(connectionToken)) {
|
||||
showError(getString(R.string.wifi_setup_reconnect_required));
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
WifiProvisioningProgress progress = provisioning.getProgress();
|
||||
GriddleProvisioningSession.State state = provisioning.getState();
|
||||
if (state != GriddleProvisioningSession.State.PROVISIONING
|
||||
&& state != GriddleProvisioningSession.State.PROVISIONED
|
||||
&& state != GriddleProvisioningSession.State.FAILED) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
renderProgress(progress);
|
||||
int notice = provisioning.consumeProvisioningNotice();
|
||||
if (notice != 0) ToastUtil.showShort(this, getString(notice));
|
||||
if (state == GriddleProvisioningSession.State.FAILED) {
|
||||
viewBinding.tvProvisionStage.setText(provisioning.getErrorRes());
|
||||
}
|
||||
if (state == GriddleProvisioningSession.State.PROVISIONED || state == GriddleProvisioningSession.State.FAILED) {
|
||||
// 配网结束后保留当前页面及结果,暂不自动返回 Wi-Fi 列表。
|
||||
viewBinding.tvCancelSetup.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
}
|
||||
|
||||
private void renderProgress(WifiProvisioningProgress progress) {
|
||||
// 圆环仅反映 SDK 已确认的阶段,100% 必须由设备联网成功回调驱动。
|
||||
viewBinding.provisionProgress.setProgressCompat(progress.getPercent(), true);
|
||||
viewBinding.provisionProgress.setContentDescription(
|
||||
getString(R.string.wifi_setup_provision_percent, progress.getPercent()));
|
||||
int stageText = R.string.wifi_setup_provision_sending;
|
||||
switch (progress.getStage()) {
|
||||
case CONFIG_SENT: stageText = R.string.wifi_setup_provision_sent; break;
|
||||
case CONNECTING_WIFI: stageText = R.string.wifi_setup_provision_connecting; break;
|
||||
case SUCCEEDED: stageText = R.string.wifi_setup_provision_success; break;
|
||||
default: break;
|
||||
}
|
||||
viewBinding.tvProvisionStage.setText(stageText);
|
||||
boolean transferred = progress.getStage() == WifiProvisioningProgress.Stage.CONFIG_SENT
|
||||
|| progress.getStage() == WifiProvisioningProgress.Stage.CONNECTING_WIFI
|
||||
|| progress.getStage() == WifiProvisioningProgress.Stage.SUCCEEDED;
|
||||
boolean connecting = progress.getStage() == WifiProvisioningProgress.Stage.CONNECTING_WIFI;
|
||||
boolean succeeded = progress.getStage() == WifiProvisioningProgress.Stage.SUCCEEDED;
|
||||
renderProvisioningStep(viewBinding.tvTransferStep, transferred, true);
|
||||
renderProvisioningStep(viewBinding.tvNetworkStep, succeeded, connecting || succeeded);
|
||||
viewBinding.tvTransferDescription.setText(transferred
|
||||
? R.string.wifi_setup_provision_sent : R.string.wifi_connect_transfer_description);
|
||||
viewBinding.tvNetworkTitle.setTextColor(getColor(connecting || succeeded
|
||||
? R.color.wifi_setup_text : R.color.wifi_setup_secondary_text));
|
||||
viewBinding.tvNetworkDescription.setText(succeeded
|
||||
? R.string.wifi_setup_provision_success : R.string.wifi_connect_network_description);
|
||||
viewBinding.tvCancelSetup.setVisibility(succeeded ? View.INVISIBLE : View.VISIBLE);
|
||||
}
|
||||
|
||||
/** 已完成步骤复用现有白色勾选图标,当前步骤橙色,待开始步骤浅灰色。 */
|
||||
private void renderProvisioningStep(android.widget.TextView step, boolean completed, boolean active) {
|
||||
step.setText(completed ? "" : step == viewBinding.tvTransferStep ? "2" : "3");
|
||||
step.setBackgroundTintList(ColorStateList.valueOf(completed ? 0xFF22A45D
|
||||
: active ? getColor(R.color.wifi_setup_accent) : 0xFFF5F6F8));
|
||||
step.setTextColor(active ? getColor(android.R.color.white) : getColor(R.color.wifi_setup_secondary_text));
|
||||
android.graphics.drawable.Drawable check = completed
|
||||
? AppCompatResources.getDrawable(this, R.drawable.ef_ic_done_white) : null;
|
||||
if (check != null) {
|
||||
int size = Math.round(14 * getResources().getDisplayMetrics().density);
|
||||
check.setBounds(0, 0, size, size);
|
||||
}
|
||||
int padding = completed ? Math.round(9 * getResources().getDisplayMetrics().density) : 0;
|
||||
step.setPadding(padding, 0, padding, 0);
|
||||
step.setCompoundDrawables(check, null, null, null);
|
||||
}
|
||||
|
||||
private void cancelProvisioning() {
|
||||
// 取消按钮和系统返回键行为一致:释放连接,使旧回调失效。
|
||||
provisioning.close(connectionToken);
|
||||
finish();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
if (provisioning != null) {
|
||||
provisioning.detach(sessionListener);
|
||||
// 配置变化和进入后台继续配网;真正退出仍在配网的页面才取消。
|
||||
if (isFinishing() && !isChangingConfigurations()
|
||||
&& provisioning.getState() == GriddleProvisioningSession.State.PROVISIONING) {
|
||||
provisioning.close(connectionToken);
|
||||
}
|
||||
}
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override public BltDeviceListPresenter createPresenter() { return null; }
|
||||
@Override public int getLayoutResId(Bundle savedInstanceState) { return 0; }
|
||||
@Override public void onDeviceFound(BleScanDevice device) { }
|
||||
@Override public void onScanStateChanged(boolean scanning) { }
|
||||
@Override public void onScanError(int messageResId) { showError(getString(messageResId)); }
|
||||
@Override public void showError(String message) {
|
||||
if (!TextUtils.isEmpty(message)) ToastUtil.showShort(this, message);
|
||||
}
|
||||
@Override public void logOut(BaseBean bean) { }
|
||||
}
|
||||
@@ -1,13 +1,18 @@
|
||||
package com.ckkj.griddle.device;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.provider.Settings;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.base.BaseFragment;
|
||||
import com.ckkj.griddle.databinding.DeviceIndexFragmentBinding;
|
||||
import com.ckkj.griddle.device.mvp.DeviceContract;
|
||||
@@ -18,6 +23,8 @@ import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import pub.devrel.easypermissions.EasyPermissions;
|
||||
|
||||
/**
|
||||
* 设备首页。
|
||||
*/
|
||||
@@ -26,6 +33,8 @@ public class DeviceFragment extends BaseFragment<DeviceIndexFragmentBinding, Dev
|
||||
|
||||
private RecyclerView.Adapter<?> mDeviceAdapter;
|
||||
private RecyclerView.Adapter<?> mObservedAdapter;
|
||||
// 从系统权限请求发起到结果回调之间保持为 true,防止连续点击重复申请。
|
||||
private boolean bluetoothPermissionRequestInFlight;
|
||||
private final RecyclerView.AdapterDataObserver mDeviceDataObserver =
|
||||
new RecyclerView.AdapterDataObserver() {
|
||||
@Override
|
||||
@@ -52,14 +61,59 @@ public class DeviceFragment extends BaseFragment<DeviceIndexFragmentBinding, Dev
|
||||
@Override
|
||||
public void initData(Bundle state) {
|
||||
bindDeviceAdapter();
|
||||
// 首页标题、右上角添加图标和空状态入口共用授权检查,避免某个入口绕过授权。
|
||||
View.OnClickListener openDeviceList = v -> openBluetoothDeviceList();
|
||||
viewBinding.tvHomeTitle.setOnClickListener(openDeviceList);
|
||||
viewBinding.cvAddDevice.setOnClickListener(openDeviceList);
|
||||
viewBinding.ivEmptyDevices.setOnClickListener(openDeviceList);
|
||||
viewBinding.ivAddDevice.setOnClickListener(openDeviceList);
|
||||
viewBinding.btnEmptyAddDevice.setOnClickListener(openDeviceList);
|
||||
}
|
||||
|
||||
/** 添加入口:已有权限直接跳转;缺少权限时先通过基类弹窗说明用途。 */
|
||||
private void openBluetoothDeviceList() {
|
||||
if (!isAdded() || getView() == null || bluetoothPermissionRequestInFlight
|
||||
|| (dialog != null && dialog.isShowing())) {
|
||||
return;
|
||||
}
|
||||
if (BleScanPermissions.hasPermissions(requireContext())) {
|
||||
navigateToBluetoothDeviceList();
|
||||
return;
|
||||
}
|
||||
// 说明文案对应实际申请的权限,旧版系统需明确说明位置权限与蓝牙扫描的关系。
|
||||
String title = getString(R.string.bl_device_permission_title);
|
||||
String description = getString(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
|
||||
? R.string.bl_device_permission_description
|
||||
: R.string.bl_device_location_permission_description);
|
||||
showDialogtext(null, false, false, title, description,
|
||||
getString(R.string.bl_device_permission_deny),
|
||||
getString(R.string.bl_device_permission_allow), new OnDialogClick() {
|
||||
@Override
|
||||
public void onCancelClick() {
|
||||
// 留在设备首页,不触发系统权限申请。
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfirmClick() {
|
||||
if (!isAdded() || getView() == null) return;
|
||||
// 说明弹窗显示期间权限可能已变化,真正申请前再检查一次。
|
||||
if (BleScanPermissions.hasPermissions(requireContext())) {
|
||||
navigateToBluetoothDeviceList();
|
||||
return;
|
||||
}
|
||||
bluetoothPermissionRequestInFlight = true;
|
||||
// 顶部说明框在系统权限申请期间保留,收到结果后统一关闭。
|
||||
showPermissionDialog(ContextCompat.getDrawable(requireContext(),
|
||||
R.mipmap.img_permission_file), true, title, description);
|
||||
dialog.setCanceledOnTouchOutside(false);
|
||||
dialog.setCancelable(false);
|
||||
requestPermissions(BleScanPermissions.requiredPermissions(), REQUEST_EVENT_CODE_10003);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 只由已有完整权限或完整授权成功的分支调用,不在此方法中再申请权限。 */
|
||||
private void navigateToBluetoothDeviceList() {
|
||||
if (!isAdded() || getView() == null) return;
|
||||
startActivity(new Intent(requireContext(), BltDeviceListActivity.class));
|
||||
}
|
||||
|
||||
@@ -101,6 +155,9 @@ public class DeviceFragment extends BaseFragment<DeviceIndexFragmentBinding, Dev
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
// 避免首页视图销毁后遗留顶部说明框或授权等待状态。
|
||||
bluetoothPermissionRequestInFlight = false;
|
||||
hidePermissionDialog();
|
||||
unregisterDeviceObserver();
|
||||
if (viewBinding != null) {
|
||||
viewBinding.rvDevices.setAdapter(null);
|
||||
@@ -124,11 +181,56 @@ public class DeviceFragment extends BaseFragment<DeviceIndexFragmentBinding, Dev
|
||||
public void logOut(BaseBean bean) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
|
||||
@NonNull int[] grantResults) {
|
||||
// 先关闭顶部说明框,再分发结果;通过、拒绝和取消都需要结束说明展示。
|
||||
if (requestCode == REQUEST_EVENT_CODE_10003) {
|
||||
hidePermissionDialog();
|
||||
}
|
||||
// BaseFragment 将结果分发给 EasyPermissions,包含部分授权和拒绝的回调。
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
|
||||
if (requestCode == REQUEST_EVENT_CODE_10003) {
|
||||
// 系统取消请求时可能返回空结果,同样需要清理等待状态。
|
||||
bluetoothPermissionRequestInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
|
||||
// EasyPermissions 在部分授权时也可能回调此方法,必须复查整组权限才能跳转。
|
||||
if (requestCode == REQUEST_EVENT_CODE_10003 && bluetoothPermissionRequestInFlight
|
||||
&& isAdded() && getView() != null
|
||||
&& BleScanPermissions.hasPermissions(requireContext())) {
|
||||
bluetoothPermissionRequestInFlight = false;
|
||||
navigateToBluetoothDeviceList();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
|
||||
if (requestCode != REQUEST_EVENT_CODE_10003 || !isAdded() || getView() == null) return;
|
||||
bluetoothPermissionRequestInFlight = false;
|
||||
// 永久拒绝后无法再次弹出系统授权框,使用基类弹窗引导用户自行前往应用设置。
|
||||
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
|
||||
showDialogtext(null, false, false,
|
||||
getString(R.string.bl_device_permission_title),
|
||||
getString(R.string.bl_device_permission_settings_description),
|
||||
getString(R.string.bl_device_permission_deny),
|
||||
getString(R.string.bl_device_open_settings), new OnDialogClick() {
|
||||
@Override
|
||||
public void onCancelClick() { }
|
||||
|
||||
@Override
|
||||
public void onConfirmClick() {
|
||||
if (isAdded()) {
|
||||
startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.parse("package:" + requireContext().getPackageName())));
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
ToastUtil.showShort(requireContext(), getString(R.string.bl_device_permission_required));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,606 @@
|
||||
package com.ckkj.griddle.device;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothGatt;
|
||||
import android.bluetooth.BluetoothGattCallback;
|
||||
import android.bluetooth.BluetoothGattCharacteristic;
|
||||
import android.bluetooth.BluetoothGattDescriptor;
|
||||
import android.bluetooth.BluetoothGattService;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.BluetoothProfile;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.device.entity.BleScanDevice;
|
||||
import com.ckkj.griddle.device.entity.WifiNetwork;
|
||||
import com.ckkj.griddle.device.entity.WifiProvisioningInput;
|
||||
import com.ckkj.griddle.device.entity.WifiProvisioningProgress;
|
||||
import com.espressif.provisioning.DeviceConnectionEvent;
|
||||
import com.espressif.provisioning.ESPConstants;
|
||||
import com.espressif.provisioning.ESPDevice;
|
||||
import com.espressif.provisioning.WiFiAccessPoint;
|
||||
import com.espressif.provisioning.listeners.WiFiScanListener;
|
||||
import com.espressif.provisioning.listeners.ProvisionListener;
|
||||
|
||||
import org.greenrobot.eventbus.EventBus;
|
||||
import org.greenrobot.eventbus.Subscribe;
|
||||
import org.greenrobot.eventbus.ThreadMode;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/** 蓝牙连接跨页面复用;先保持 BLE 连接,再按实际服务决定能否进行后续 Wi-Fi 扫描。 */
|
||||
@SuppressLint("MissingPermission")
|
||||
public final class GriddleProvisioningSession {
|
||||
private static final String TAG = "GriddleProvisioning";
|
||||
public enum State { IDLE, CONNECTING, CONNECTED, SCANNING, READY, PROVISIONING, PROVISIONED, FAILED }
|
||||
public enum ConnectionMode { UNKNOWN, BUSINESS, PROVISIONING }
|
||||
public interface Listener { void onSessionChanged(); }
|
||||
|
||||
private static final UUID DESCRIPTION_UUID = UUID.fromString("00002901-0000-1000-8000-00805f9b34fb");
|
||||
private static final UUID BUSINESS_UUID = UUID.fromString("44424301-0001-4dbc-8000-00805f9b34fb");
|
||||
private static final UUID INFO_UUID = UUID.fromString("44424302-0001-4dbc-8000-00805f9b34fb");
|
||||
private static GriddleProvisioningSession instance;
|
||||
private final Context context;
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
private final ArrayDeque<BluetoothGattDescriptor> descriptions = new ArrayDeque<>();
|
||||
private final Map<UUID, Set<String>> endpoints = new HashMap<>();
|
||||
private final List<WifiNetwork> networks = new ArrayList<>();
|
||||
// 原生 GATT 在第一步连接后持续保留,仅退出页面或显式进入 SDK 扫描时释放。
|
||||
private BluetoothGatt probe;
|
||||
private BluetoothGattCharacteristic pendingInfo;
|
||||
private ESPDevice espDevice;
|
||||
private ConnectionMode connectionMode = ConnectionMode.UNKNOWN;
|
||||
private String provisioningServiceUuid;
|
||||
private String deviceId;
|
||||
private String sku;
|
||||
private String firmwareVersion;
|
||||
private int infoWarningRes;
|
||||
private boolean awaitingSdkConnection;
|
||||
private Runnable infoTimeout;
|
||||
private Listener listener;
|
||||
private State state = State.IDLE;
|
||||
private String token;
|
||||
private String deviceName;
|
||||
private String address;
|
||||
private int errorRes;
|
||||
private int generation;
|
||||
private int scanGeneration;
|
||||
private Runnable timeout;
|
||||
private Runnable disconnectGrace;
|
||||
private final WifiProvisioningProgress progress = new WifiProvisioningProgress();
|
||||
private int provisioningNotice;
|
||||
|
||||
private GriddleProvisioningSession(Context context) { this.context = context.getApplicationContext(); }
|
||||
|
||||
public static GriddleProvisioningSession get(Context context) {
|
||||
if (instance == null) instance = new GriddleProvisioningSession(context);
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void attach(Listener listener) { this.listener = listener; listener.onSessionChanged(); }
|
||||
public void detach(Listener listener) { if (this.listener == listener) this.listener = null; }
|
||||
public State getState() { return state; }
|
||||
public String getToken() { return token; }
|
||||
public String getDeviceName() { return deviceName; }
|
||||
public String getAddress() { return address; }
|
||||
public int getErrorRes() { return errorRes; }
|
||||
public WifiProvisioningProgress getProgress() { return progress; }
|
||||
/** 结果提示只消费一次,避免页面恢复或重复回调时反复 Toast。 */
|
||||
public int consumeProvisioningNotice() {
|
||||
int notice = provisioningNotice;
|
||||
provisioningNotice = 0;
|
||||
return notice;
|
||||
}
|
||||
public ConnectionMode getConnectionMode() { return connectionMode; }
|
||||
public String getDeviceId() { return deviceId; }
|
||||
public String getSku() { return sku; }
|
||||
public String getFirmwareVersion() { return firmwareVersion; }
|
||||
public int getInfoWarningRes() { return infoWarningRes; }
|
||||
public boolean supportsWifiScan() {
|
||||
return connectionMode == ConnectionMode.PROVISIONING && provisioningServiceUuid != null;
|
||||
}
|
||||
public List<WifiNetwork> getNetworks() { return Collections.unmodifiableList(networks); }
|
||||
public boolean matches(String token) { return token != null && token.equals(this.token); }
|
||||
public boolean isConnected() {
|
||||
return disconnectGrace == null && (state == State.CONNECTED || state == State.SCANNING
|
||||
|| state == State.READY || state == State.PROVISIONING);
|
||||
}
|
||||
|
||||
/** 第一步只建立 BLE 连接;业务服务和配网服务都可以连接,缺少配网服务不是连接失败。 */
|
||||
public String connect(BleScanDevice device) {
|
||||
releaseTransport();
|
||||
token = UUID.randomUUID().toString();
|
||||
deviceName = device.getName();
|
||||
address = device.getAddress();
|
||||
networks.clear();
|
||||
progress.reset();
|
||||
provisioningNotice = 0;
|
||||
connectionMode = ConnectionMode.UNKNOWN;
|
||||
provisioningServiceUuid = null;
|
||||
deviceId = null;
|
||||
sku = null;
|
||||
firmwareVersion = null;
|
||||
infoWarningRes = 0;
|
||||
errorRes = 0;
|
||||
state = State.CONNECTING;
|
||||
final int attempt = generation;
|
||||
armTimeout(30_000L, () -> fail(R.string.wifi_setup_connection_timeout));
|
||||
try {
|
||||
if (!BleScanPermissions.hasPermissions(context)) {
|
||||
fail(R.string.bl_device_permission_home_required);
|
||||
} else {
|
||||
BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (manager == null || manager.getAdapter() == null || !manager.getAdapter().isEnabled()) {
|
||||
fail(R.string.bl_device_bluetooth_off);
|
||||
} else {
|
||||
BluetoothDevice target = manager.getAdapter().getRemoteDevice(address);
|
||||
startProbe(attempt, target, 0);
|
||||
}
|
||||
}
|
||||
} catch (SecurityException e) {
|
||||
fail(R.string.bl_device_permission_home_required);
|
||||
} catch (RuntimeException e) {
|
||||
fail(R.string.wifi_setup_connection_failed);
|
||||
}
|
||||
publish();
|
||||
return token;
|
||||
}
|
||||
|
||||
private void startProbe(int attempt, BluetoothDevice target, int retryCount) {
|
||||
if (attempt != generation || state != State.CONNECTING) return;
|
||||
try {
|
||||
probe = target.connectGatt(context, false, createProbeCallback(attempt, target, retryCount), BluetoothDevice.TRANSPORT_LE);
|
||||
if (probe == null) fail(R.string.wifi_setup_connection_failed);
|
||||
} catch (SecurityException e) { fail(R.string.bl_device_permission_home_required);
|
||||
} catch (RuntimeException e) { fail(R.string.wifi_setup_connection_failed); }
|
||||
}
|
||||
|
||||
private BluetoothGattCallback createProbeCallback(int attempt, BluetoothDevice target, int retryCount) {
|
||||
return new BluetoothGattCallback() {
|
||||
@Override
|
||||
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
|
||||
handler.post(() -> {
|
||||
if (!isCurrentGatt(attempt, gatt)) return;
|
||||
// Android 偶发的 GATT 133 先释放旧连接后重试一次,保留原来的总超时时间。
|
||||
if (state == State.CONNECTING && status == 133 && retryCount == 0) {
|
||||
Log.i(TAG, "Retrying transient GATT 133 once");
|
||||
closeProbe();
|
||||
descriptions.clear();
|
||||
endpoints.clear();
|
||||
handler.postDelayed(() -> startProbe(attempt, target, 1), 800L);
|
||||
return;
|
||||
}
|
||||
if (status != BluetoothGatt.GATT_SUCCESS || newState == BluetoothProfile.STATE_DISCONNECTED) {
|
||||
fail(state == State.CONNECTING ? R.string.wifi_setup_connection_failed : R.string.wifi_setup_disconnected);
|
||||
} else if (newState == BluetoothProfile.STATE_CONNECTED && state == State.CONNECTING) {
|
||||
try {
|
||||
if (!gatt.discoverServices()) fail(R.string.wifi_setup_connection_failed);
|
||||
} catch (SecurityException e) { fail(R.string.bl_device_permission_home_required); }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
|
||||
handler.post(() -> {
|
||||
if (!isCurrentGatt(attempt, gatt) || state != State.CONNECTING) return;
|
||||
if (status != BluetoothGatt.GATT_SUCCESS) { fail(R.string.wifi_setup_connection_failed); return; }
|
||||
clearTimeout();
|
||||
// 按 0x2901 描述符识别 proto-ver/prov-session/prov-scan,兼容固件自定义 Service UUID。
|
||||
for (BluetoothGattService service : gatt.getServices()) {
|
||||
Log.i(TAG, "Discovered GATT service: " + service.getUuid());
|
||||
if (BUSINESS_UUID.equals(service.getUuid())) continue;
|
||||
for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
|
||||
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(DESCRIPTION_UUID);
|
||||
if (descriptor != null) descriptions.add(descriptor);
|
||||
}
|
||||
}
|
||||
BluetoothGattService businessService = gatt.getService(BUSINESS_UUID);
|
||||
if (businessService != null) {
|
||||
descriptions.clear();
|
||||
connectionMode = ConnectionMode.BUSINESS;
|
||||
// Info 是只读 JSON,不发送控制命令,也不要求设备切换到配网模式。
|
||||
readBusinessInfo(attempt, gatt, businessService.getCharacteristic(INFO_UUID));
|
||||
return;
|
||||
}
|
||||
// 描述符只用于识别后续能力,读不到也保留已经建立的 BLE 连接。
|
||||
armTimeout(5_000L, GriddleProvisioningSession.this::completeBleConnection);
|
||||
readNextDescription();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
byte[] value = descriptor.getValue();
|
||||
handleDescription(gatt, descriptor, status, value == null ? null : value.clone());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status, byte[] value) {
|
||||
handleDescription(gatt, descriptor, status, value == null ? null : value.clone());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
|
||||
byte[] value = characteristic.getValue();
|
||||
handleBusinessInfo(attempt, gatt, characteristic, status, value == null ? null : value.clone());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value, int status) {
|
||||
handleBusinessInfo(attempt, gatt, characteristic, status, value == null ? null : value.clone());
|
||||
}
|
||||
|
||||
private void handleDescription(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status, byte[] value) {
|
||||
handler.post(() -> {
|
||||
if (!isCurrentGatt(attempt, gatt) || state != State.CONNECTING) return;
|
||||
// API 33 起使用回调携带的值;旧系统使用旧回调,所有 GATT 操作串行执行。
|
||||
if (status == BluetoothGatt.GATT_SUCCESS && value != null) {
|
||||
UUID service = descriptor.getCharacteristic().getService().getUuid();
|
||||
endpoints.computeIfAbsent(service, key -> new HashSet<>())
|
||||
.add(new String(value, StandardCharsets.UTF_8).replace("\u0000", ""));
|
||||
}
|
||||
readNextDescription();
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private boolean isCurrentGatt(int attempt, BluetoothGatt gatt) {
|
||||
return attempt == generation && probe == gatt;
|
||||
}
|
||||
|
||||
private void readBusinessInfo(int attempt, BluetoothGatt gatt, BluetoothGattCharacteristic info) {
|
||||
if (info == null || (info.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) == 0) {
|
||||
infoWarningRes = R.string.ble_device_info_read_failed;
|
||||
completeBleConnection();
|
||||
return;
|
||||
}
|
||||
pendingInfo = info;
|
||||
// 读取失败或超时只影响设备信息展示,不能把已建立的蓝牙连接当成失败并断开。
|
||||
infoTimeout = () -> {
|
||||
if (!isCurrentGatt(attempt, gatt) || pendingInfo == null) return;
|
||||
clearInfoRead();
|
||||
infoWarningRes = R.string.ble_device_info_read_failed;
|
||||
completeBleConnection();
|
||||
};
|
||||
handler.postDelayed(infoTimeout, 5_000L);
|
||||
try {
|
||||
if (!gatt.readCharacteristic(info)) {
|
||||
clearInfoRead();
|
||||
infoWarningRes = R.string.ble_device_info_read_failed;
|
||||
completeBleConnection();
|
||||
}
|
||||
} catch (SecurityException e) {
|
||||
fail(R.string.bl_device_permission_home_required);
|
||||
} catch (RuntimeException e) {
|
||||
clearInfoRead();
|
||||
infoWarningRes = R.string.ble_device_info_read_failed;
|
||||
completeBleConnection();
|
||||
}
|
||||
}
|
||||
|
||||
private void handleBusinessInfo(int attempt, BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
|
||||
int status, byte[] value) {
|
||||
handler.post(() -> {
|
||||
if (!isCurrentGatt(attempt, gatt) || pendingInfo != characteristic) return;
|
||||
clearInfoRead();
|
||||
try {
|
||||
if (status != BluetoothGatt.GATT_SUCCESS || value == null) throw new IllegalStateException("Info read failed");
|
||||
JSONObject info = new JSONObject(new String(value, StandardCharsets.UTF_8));
|
||||
deviceId = info.optString("deviceId", "");
|
||||
sku = info.optString("sku", "");
|
||||
firmwareVersion = info.optString("firmwareVersion", "");
|
||||
Log.i(TAG, "Business Info: sku=" + sku + ", firmware=" + firmwareVersion + ", deviceId=" + deviceId);
|
||||
} catch (Exception e) {
|
||||
infoWarningRes = R.string.ble_device_info_read_failed;
|
||||
}
|
||||
completeBleConnection();
|
||||
});
|
||||
}
|
||||
|
||||
private void clearInfoRead() {
|
||||
if (infoTimeout != null) handler.removeCallbacks(infoTimeout);
|
||||
infoTimeout = null;
|
||||
pendingInfo = null;
|
||||
}
|
||||
|
||||
private void completeBleConnection() {
|
||||
clearTimeout();
|
||||
state = State.CONNECTED;
|
||||
errorRes = 0;
|
||||
Log.i(TAG, "BLE connected and retained, mode=" + connectionMode);
|
||||
publish();
|
||||
}
|
||||
|
||||
private void readNextDescription() {
|
||||
BluetoothGattDescriptor descriptor;
|
||||
try {
|
||||
while ((descriptor = descriptions.poll()) != null) {
|
||||
if (probe.readDescriptor(descriptor)) return;
|
||||
}
|
||||
String serviceUuid = null;
|
||||
for (Map.Entry<UUID, Set<String>> entry : endpoints.entrySet()) {
|
||||
Set<String> names = entry.getValue();
|
||||
if (names.contains("proto-ver") && names.contains("prov-session") && names.contains("prov-scan")) {
|
||||
serviceUuid = entry.getKey().toString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
provisioningServiceUuid = serviceUuid;
|
||||
connectionMode = serviceUuid == null ? ConnectionMode.UNKNOWN : ConnectionMode.PROVISIONING;
|
||||
// 连接成功后保持当前 GATT,不因缺少配网服务而断开,也不自动启动 SDK 或配网。
|
||||
completeBleConnection();
|
||||
} catch (SecurityException e) { fail(R.string.bl_device_permission_home_required); }
|
||||
}
|
||||
|
||||
/** SDK 使用 org.greenrobot EventBus,与项目旧版 de.greenrobot EventBus 分开处理。 */
|
||||
@Subscribe(threadMode = ThreadMode.MAIN)
|
||||
public void onDeviceConnectionEvent(DeviceConnectionEvent event) {
|
||||
if (espDevice == null) return;
|
||||
if (state == State.PROVISIONED) return;
|
||||
if (event.getEventType() == ESPConstants.EVENT_DEVICE_CONNECTED && state == State.SCANNING && awaitingSdkConnection) {
|
||||
try {
|
||||
// 固定使用协议要求的 Security 2,拒绝 SDK 自动退回低版本安全协议。
|
||||
JSONObject prov = new JSONObject(espDevice.getVersionInfo()).getJSONObject("prov");
|
||||
if (prov.optInt("sec_ver", -1) != 2) { fail(R.string.wifi_setup_security_mismatch); return; }
|
||||
awaitingSdkConnection = false;
|
||||
requestWifiScan(generation, scanGeneration);
|
||||
} catch (Exception e) { fail(R.string.wifi_setup_security_mismatch); }
|
||||
} else if (event.getEventType() == ESPConstants.EVENT_DEVICE_CONNECTION_FAILED) {
|
||||
if (state == State.PROVISIONING) awaitProvisioningResult();
|
||||
else fail(R.string.wifi_setup_connection_failed);
|
||||
} else if (event.getEventType() == ESPConstants.EVENT_DEVICE_DISCONNECTED) {
|
||||
if (state == State.PROVISIONING) awaitProvisioningResult();
|
||||
else fail(R.string.wifi_setup_disconnected);
|
||||
}
|
||||
}
|
||||
|
||||
/** 请求的是设备周围的网络,不调用手机 WifiManager 扫描,也不额外申请手机 Wi-Fi 扫描权限。 */
|
||||
public void scanNetworks(String token) {
|
||||
if (!matches(token) || !supportsWifiScan() || !isConnected()
|
||||
|| (state != State.CONNECTED && state != State.READY)) return;
|
||||
errorRes = 0;
|
||||
state = State.SCANNING;
|
||||
final int attempt = generation;
|
||||
final int request = ++scanGeneration;
|
||||
armTimeout(35_000L, () -> fail(R.string.wifi_setup_scan_timeout));
|
||||
publish();
|
||||
if (espDevice == null) {
|
||||
BluetoothDevice target = probe.getDevice();
|
||||
// 仅当用户明确点击搜索 Wi-Fi 时才将 GATT 交给官方 SDK;第一步连接不依赖 SDK。
|
||||
closeProbe();
|
||||
awaitingSdkConnection = true;
|
||||
handler.postDelayed(() -> {
|
||||
if (attempt != generation || state != State.SCANNING) return;
|
||||
try {
|
||||
espDevice = new ESPDevice(context, ESPConstants.TransportType.TRANSPORT_BLE,
|
||||
ESPConstants.SecurityType.SECURITY_2);
|
||||
espDevice.setUserName("wifiprov");
|
||||
espDevice.setProofOfPossession("abcd1234");
|
||||
EventBus.getDefault().register(this);
|
||||
espDevice.connectBLEDevice(target, provisioningServiceUuid);
|
||||
} catch (SecurityException e) { fail(R.string.bl_device_permission_home_required);
|
||||
} catch (RuntimeException e) { fail(R.string.wifi_setup_scan_failed); }
|
||||
}, 500L);
|
||||
} else {
|
||||
requestWifiScan(attempt, request);
|
||||
}
|
||||
}
|
||||
|
||||
private void requestWifiScan(int attempt, int request) {
|
||||
try {
|
||||
espDevice.scanNetworks(new WiFiScanListener() {
|
||||
@Override
|
||||
public void onWifiListReceived(ArrayList<WiFiAccessPoint> wifiList) {
|
||||
List<WifiNetwork> result = new ArrayList<>();
|
||||
if (wifiList != null) for (WiFiAccessPoint ap : wifiList) {
|
||||
if (ap != null) result.add(new WifiNetwork(ap.getWifiName(), ap.getSecurity(), ap.getRssi()));
|
||||
}
|
||||
handler.post(() -> finishScan(attempt, request, result, 0));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWiFiScanFailed(Exception e) {
|
||||
handler.post(() -> finishScan(attempt, request, null, R.string.wifi_setup_scan_failed));
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
finishScan(attempt, request, null, R.string.wifi_setup_scan_failed);
|
||||
}
|
||||
}
|
||||
|
||||
private void finishScan(int attempt, int request, List<WifiNetwork> result, int error) {
|
||||
if (attempt != generation || request != scanGeneration || state != State.SCANNING) return;
|
||||
clearTimeout();
|
||||
if (error != 0) { fail(error); return; }
|
||||
networks.clear();
|
||||
networks.addAll(result);
|
||||
// 只记录数量,便于联调确认设备是否返回扫描结果,不输出 Wi-Fi 密码等凭据。
|
||||
Log.i(TAG, "Device Wi-Fi scan returned " + networks.size() + " access points");
|
||||
state = State.READY;
|
||||
publish();
|
||||
}
|
||||
|
||||
/** 提交选中的设备扫描结果,凭据仅交给 SDK,不缓存、不输出日志。返回 0 表示已开始。 */
|
||||
public int provision(String token, WifiNetwork network, String password) {
|
||||
if (!matches(token) || state != State.READY || espDevice == null) {
|
||||
return R.string.wifi_setup_reconnect_required;
|
||||
}
|
||||
int validation = validateCredentials(network, password);
|
||||
if (validation != 0) return validation;
|
||||
boolean found = false;
|
||||
for (WifiNetwork item : networks) {
|
||||
if (item.getKey().equals(network.getKey())) { found = true; break; }
|
||||
}
|
||||
if (!found) return R.string.wifi_setup_network_required;
|
||||
state = State.PROVISIONING;
|
||||
errorRes = 0;
|
||||
provisioningNotice = 0;
|
||||
progress.start();
|
||||
final int attempt = generation;
|
||||
armTimeout(90_000L, () -> fail(R.string.wifi_setup_provision_timeout));
|
||||
publish();
|
||||
try {
|
||||
espDevice.provision(network.getSsid(), network.isSecured() ? password : "", new ProvisionListener() {
|
||||
private void error(int resource) {
|
||||
handler.post(() -> {
|
||||
if (isProvisioningAttempt(attempt) && disconnectGrace == null) fail(resource);
|
||||
});
|
||||
}
|
||||
@Override public void createSessionFailed(Exception e) { error(R.string.wifi_setup_provision_session_failed); }
|
||||
@Override public void wifiConfigFailed(Exception e) { error(R.string.wifi_setup_provision_send_failed); }
|
||||
@Override public void wifiConfigApplyFailed(Exception e) { error(R.string.wifi_setup_provision_apply_failed); }
|
||||
@Override public void onProvisioningFailed(Exception e) { error(R.string.wifi_setup_provision_failed); }
|
||||
@Override public void wifiConfigSent() {
|
||||
handler.post(() -> {
|
||||
if (!isProvisioningAttempt(attempt)) return;
|
||||
progress.configurationSent();
|
||||
publish();
|
||||
});
|
||||
}
|
||||
@Override public void wifiConfigApplied() {
|
||||
handler.post(() -> {
|
||||
if (!isProvisioningAttempt(attempt)) return;
|
||||
progress.configurationApplied();
|
||||
publish();
|
||||
});
|
||||
}
|
||||
@Override public void provisioningFailedFromDevice(ESPConstants.ProvisionFailureReason reason) {
|
||||
handler.post(() -> {
|
||||
if (!isProvisioningAttempt(attempt)) return;
|
||||
if (reason == ESPConstants.ProvisionFailureReason.DEVICE_DISCONNECTED) {
|
||||
awaitProvisioningResult();
|
||||
} else if (reason == ESPConstants.ProvisionFailureReason.AUTH_FAILED) {
|
||||
fail(R.string.wifi_setup_provision_auth_failed);
|
||||
} else if (reason == ESPConstants.ProvisionFailureReason.NETWORK_NOT_FOUND) {
|
||||
fail(R.string.wifi_setup_provision_network_missing);
|
||||
} else {
|
||||
fail(R.string.wifi_setup_provision_failed);
|
||||
}
|
||||
});
|
||||
}
|
||||
@Override public void deviceProvisioningSuccess() {
|
||||
handler.post(() -> {
|
||||
if (!isProvisioningAttempt(attempt)) return;
|
||||
// 只有设备明确返回已联网才算成功;随后退出配网服务的断连不再作为失败。
|
||||
progress.succeed();
|
||||
state = State.PROVISIONED;
|
||||
provisioningNotice = R.string.wifi_setup_provision_success;
|
||||
releaseTransport();
|
||||
Log.i(TAG, "Device confirmed Wi-Fi provisioning success");
|
||||
publish();
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
if (isProvisioningAttempt(attempt)) fail(R.string.wifi_setup_provision_failed);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int validateCredentials(WifiNetwork network, String password) {
|
||||
switch (WifiProvisioningInput.validate(network, password)) {
|
||||
case NETWORK_REQUIRED: return R.string.wifi_setup_network_required;
|
||||
case SSID_INVALID: return R.string.wifi_setup_ssid_invalid;
|
||||
case PASSWORD_REQUIRED: return R.string.wifi_setup_password_required;
|
||||
case PASSWORD_INVALID: return R.string.wifi_setup_password_invalid;
|
||||
case SECURITY_UNSUPPORTED: return R.string.wifi_setup_security_unsupported;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isProvisioningAttempt(int attempt) {
|
||||
return attempt == generation && state == State.PROVISIONING;
|
||||
}
|
||||
|
||||
private void awaitProvisioningResult() {
|
||||
if (disconnectGrace != null) return;
|
||||
// 为已在途的成功回调保留短暂窗口;单独断连不能证明设备已联网。
|
||||
final int attempt = generation;
|
||||
disconnectGrace = () -> {
|
||||
if (isProvisioningAttempt(attempt)) fail(R.string.wifi_setup_provision_unconfirmed);
|
||||
};
|
||||
handler.postDelayed(disconnectGrace, 2_000L);
|
||||
publish();
|
||||
}
|
||||
|
||||
public void close(String token) {
|
||||
if (!matches(token)) return;
|
||||
releaseTransport();
|
||||
this.token = null;
|
||||
networks.clear();
|
||||
errorRes = 0;
|
||||
state = State.IDLE;
|
||||
progress.reset();
|
||||
provisioningNotice = 0;
|
||||
}
|
||||
|
||||
private void fail(int errorRes) {
|
||||
if (state == State.PROVISIONED) return;
|
||||
if (state == State.PROVISIONING) {
|
||||
progress.fail();
|
||||
provisioningNotice = errorRes;
|
||||
}
|
||||
Log.w(TAG, "BLE session stopped: " + context.getString(errorRes));
|
||||
releaseTransport();
|
||||
this.errorRes = errorRes;
|
||||
state = State.FAILED;
|
||||
publish();
|
||||
}
|
||||
|
||||
private void armTimeout(long duration, Runnable action) {
|
||||
clearTimeout();
|
||||
timeout = action;
|
||||
handler.postDelayed(action, duration);
|
||||
}
|
||||
|
||||
private void clearTimeout() {
|
||||
if (timeout != null) handler.removeCallbacks(timeout);
|
||||
timeout = null;
|
||||
}
|
||||
|
||||
private void closeProbe() {
|
||||
BluetoothGatt previous = probe;
|
||||
probe = null;
|
||||
if (previous != null) {
|
||||
try { previous.disconnect(); } catch (SecurityException ignored) { }
|
||||
try { previous.close(); } catch (SecurityException ignored) { }
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseTransport() {
|
||||
// 让旧连接的异步回调失效;超时和退出都需要关闭 GATT,不能仅隐藏 loading。
|
||||
generation++;
|
||||
if (disconnectGrace != null) handler.removeCallbacks(disconnectGrace);
|
||||
disconnectGrace = null;
|
||||
clearTimeout();
|
||||
clearInfoRead();
|
||||
awaitingSdkConnection = false;
|
||||
descriptions.clear();
|
||||
endpoints.clear();
|
||||
if (EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this);
|
||||
closeProbe();
|
||||
ESPDevice previous = espDevice;
|
||||
espDevice = null;
|
||||
if (previous != null) {
|
||||
try { previous.disconnectDevice(); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
}
|
||||
|
||||
private void publish() { if (listener != null) listener.onSessionChanged(); }
|
||||
}
|
||||
250
app/src/main/java/com/ckkj/griddle/device/WifiListActivity.java
Normal file
250
app/src/main/java/com/ckkj/griddle/device/WifiListActivity.java
Normal file
@@ -0,0 +1,250 @@
|
||||
package com.ckkj.griddle.device;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.text.Editable;
|
||||
import android.text.TextUtils;
|
||||
import android.text.TextWatcher;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
|
||||
import androidx.activity.result.ActivityResultLauncher;
|
||||
import androidx.activity.result.contract.ActivityResultContracts;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.base.BaseActivity;
|
||||
import com.ckkj.griddle.databinding.WifiListLayoutBinding;
|
||||
import com.ckkj.griddle.device.adapter.WifiNetworkAdapter;
|
||||
import com.ckkj.griddle.device.entity.WifiNetwork;
|
||||
import com.ckkj.griddle.device.mvp.DeviceContract;
|
||||
import com.ckkj.griddle.device.mvp.DeviceImpl;
|
||||
import com.ckkj.griddle.device.mvp.DevicePresenter;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
import com.gyf.immersionbar.ImmersionBar;
|
||||
|
||||
/** 先展示上一页已建立的 BLE 连接;配网能力独立判断,Wi-Fi 扫描仅由用户手动触发。 */
|
||||
public class WifiListActivity extends BaseActivity<WifiListLayoutBinding, DevicePresenter>
|
||||
implements DeviceContract.DeviceView {
|
||||
public static final String EXTRA_SESSION_TOKEN = "provisioning_session_token";
|
||||
private GriddleProvisioningSession provisioning;
|
||||
private String connectionToken;
|
||||
private WifiNetworkAdapter networkAdapter;
|
||||
private boolean openingConnecting;
|
||||
private final ActivityResultLauncher<Intent> connectingLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.StartActivityForResult(), result -> {
|
||||
openingConnecting = false;
|
||||
// 主动取消后直接返回设备列表,不再重复提示“连接失效”。
|
||||
if (!provisioning.matches(connectionToken)) finish();
|
||||
else renderSession();
|
||||
});
|
||||
private final GriddleProvisioningSession.Listener sessionListener = this::renderSession;
|
||||
|
||||
@Override
|
||||
public DevicePresenter createPresenter() { return new DevicePresenter(new DeviceImpl()); }
|
||||
|
||||
@Override
|
||||
public void initData(Bundle savedInstanceState) {
|
||||
super.initData(savedInstanceState);
|
||||
ImmersionBar.with(this).statusBarColor(android.R.color.white).statusBarDarkFont(true).init();
|
||||
provisioning = GriddleProvisioningSession.get(this);
|
||||
connectionToken = getIntent().getStringExtra(EXTRA_SESSION_TOKEN);
|
||||
openingConnecting = savedInstanceState != null && savedInstanceState.getBoolean("opening_connecting");
|
||||
networkAdapter = new WifiNetworkAdapter(this::onNetworkSelected);
|
||||
if (savedInstanceState != null) {
|
||||
networkAdapter.restoreSelection(savedInstanceState.getString("selected_network"));
|
||||
}
|
||||
viewBinding.rvWifiNetworks.setAdapter(networkAdapter);
|
||||
viewBinding.rvWifiNetworks.setItemAnimator(null);
|
||||
// 网络较多时列表内部滚动,不再只显示设计稿中的三个示例网络。
|
||||
viewBinding.rvWifiNetworks.setNestedScrollingEnabled(true);
|
||||
viewBinding.tvOtherNetworks.setText(R.string.wifi_setup_refresh_networks);
|
||||
viewBinding.tvOtherNetworks.setOnClickListener(v -> {
|
||||
if (!provisioning.matches(connectionToken) || !provisioning.isConnected()) {
|
||||
showMessage(getString(R.string.wifi_setup_reconnect_required));
|
||||
finish();
|
||||
} else {
|
||||
provisioning.scanNetworks(connectionToken);
|
||||
}
|
||||
});
|
||||
viewBinding.btnStartSetup.setEnabled(false);
|
||||
viewBinding.btnStartSetup.setAlpha(0.5f);
|
||||
viewBinding.btnStartSetup.setOnClickListener(v -> startProvisioning());
|
||||
viewBinding.etWifiPassword.setEnabled(false);
|
||||
// 禁止系统跨页面重建保存 Wi-Fi 密码;切换 SSID 时也会主动清空输入。
|
||||
viewBinding.etWifiPassword.setSaveEnabled(false);
|
||||
viewBinding.etWifiPassword.addTextChangedListener(new TextWatcher() {
|
||||
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
|
||||
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateStartButton(); }
|
||||
@Override public void afterTextChanged(Editable s) { }
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
provisioning.attach(sessionListener);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
provisioning.detach(sessionListener);
|
||||
hideDialogLoading();
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
private void renderSession() {
|
||||
if (isFinishing() || isDestroyed()) return;
|
||||
if (!provisioning.matches(connectionToken)) {
|
||||
showMessage(getString(R.string.wifi_setup_reconnect_required));
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
viewBinding.tvDeviceName.setText(TextUtils.isEmpty(provisioning.getDeviceName())
|
||||
? getString(R.string.bl_device_unknown_name) : provisioning.getDeviceName());
|
||||
// 优先显示 Info 中真实的固件版本;没有读取到版本时显示 MAC,不伪造序列号。
|
||||
viewBinding.tvDeviceSn.setText(TextUtils.isEmpty(provisioning.getFirmwareVersion())
|
||||
? getString(R.string.bl_device_address, provisioning.getAddress())
|
||||
: getString(R.string.ble_device_firmware, provisioning.getFirmwareVersion()));
|
||||
boolean connected = provisioning.isConnected();
|
||||
viewBinding.tvBluetoothStatus.setText(connected
|
||||
? R.string.wifi_setup_bluetooth_connected : R.string.wifi_setup_bluetooth_disconnected);
|
||||
viewBinding.tvBluetoothStatus.setBackgroundResource(connected
|
||||
? R.drawable.bl_device_signal_strong_bg : R.drawable.bl_device_signal_weak_bg);
|
||||
viewBinding.tvBluetoothStatus.setTextColor(getColor(connected
|
||||
? R.color.bl_device_signal_strong : R.color.bl_device_signal_weak));
|
||||
|
||||
GriddleProvisioningSession.State state = provisioning.getState();
|
||||
boolean scanning = state == GriddleProvisioningSession.State.SCANNING;
|
||||
boolean provisioningNow = state == GriddleProvisioningSession.State.PROVISIONING;
|
||||
boolean provisioned = state == GriddleProvisioningSession.State.PROVISIONED;
|
||||
boolean wifiSupported = provisioning.supportsWifiScan();
|
||||
boolean canSearch = connected && wifiSupported && !scanning && !provisioningNow && !provisioned;
|
||||
viewBinding.tvOtherNetworks.setEnabled(canSearch || state == GriddleProvisioningSession.State.FAILED);
|
||||
viewBinding.tvOtherNetworks.setAlpha(viewBinding.tvOtherNetworks.isEnabled() ? 1f : 0.5f);
|
||||
viewBinding.tvOtherNetworks.setText(provisioned ? R.string.wifi_setup_provision_success
|
||||
: !connected ? R.string.wifi_setup_return_to_devices
|
||||
: wifiSupported ? R.string.wifi_setup_refresh_networks : R.string.ble_device_wifi_not_ready);
|
||||
networkAdapter.setSelectionEnabled(canSearch);
|
||||
if (scanning) {
|
||||
viewBinding.etWifiPassword.setEnabled(false);
|
||||
viewBinding.tvWifiStatus.setText(R.string.wifi_setup_scanning);
|
||||
viewBinding.tvWifiStatus.setVisibility(View.VISIBLE);
|
||||
if (mLoadingDialog == null || !mLoadingDialog.isShowing()) showLoadingDialog();
|
||||
} else {
|
||||
hideDialogLoading();
|
||||
String previousKey = networkAdapter.getSelectedKey();
|
||||
networkAdapter.submit(provisioning.getNetworks());
|
||||
if (!TextUtils.equals(previousKey, networkAdapter.getSelectedKey())) viewBinding.etWifiPassword.setText("");
|
||||
WifiNetwork selected = networkAdapter.getSelected();
|
||||
viewBinding.etWifiPassword.setEnabled(canSearch && selected != null && selected.isSecured());
|
||||
viewBinding.etWifiPassword.setHint(selected != null && !selected.isSecured()
|
||||
? R.string.wifi_setup_password_not_required : R.string.wifi_setup_password_hint);
|
||||
resizeNetworkList();
|
||||
int error = provisioning.getErrorRes();
|
||||
if (error != 0) {
|
||||
viewBinding.tvWifiStatus.setText(error);
|
||||
viewBinding.tvWifiStatus.setVisibility(View.VISIBLE);
|
||||
} else if (provisioned) {
|
||||
viewBinding.tvWifiStatus.setText(R.string.wifi_setup_provision_success);
|
||||
viewBinding.tvWifiStatus.setVisibility(View.VISIBLE);
|
||||
} else if (state == GriddleProvisioningSession.State.READY && networkAdapter.getItemCount() == 0) {
|
||||
viewBinding.tvWifiStatus.setText(R.string.wifi_setup_scan_empty);
|
||||
viewBinding.tvWifiStatus.setVisibility(View.VISIBLE);
|
||||
} else if (state == GriddleProvisioningSession.State.CONNECTED) {
|
||||
// 连接成功与配网能力分开显示:业务模式保持绿色“蓝牙已连接”,不触发失败或断开。
|
||||
int statusText;
|
||||
if ("ble_only".equals(provisioning.getSku())) {
|
||||
statusText = R.string.ble_device_connected_ble_only;
|
||||
} else if (provisioning.getConnectionMode() == GriddleProvisioningSession.ConnectionMode.BUSINESS) {
|
||||
statusText = R.string.ble_device_connected_business;
|
||||
} else if (wifiSupported) {
|
||||
statusText = R.string.ble_device_connected_provisioning;
|
||||
} else {
|
||||
statusText = R.string.ble_device_connected_unknown;
|
||||
}
|
||||
String statusMessage = getString(statusText);
|
||||
if (provisioning.getInfoWarningRes() != 0) {
|
||||
statusMessage += "\n" + getString(provisioning.getInfoWarningRes());
|
||||
}
|
||||
viewBinding.tvWifiStatus.setText(statusMessage);
|
||||
viewBinding.tvWifiStatus.setVisibility(View.VISIBLE);
|
||||
} else {
|
||||
viewBinding.tvWifiStatus.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
updateStartButton();
|
||||
}
|
||||
|
||||
private void onNetworkSelected(WifiNetwork network) {
|
||||
if (!provisioning.isConnected()) return;
|
||||
// 防止把上一个网络的密码误用于新 SSID;开放网络无需输入密码。
|
||||
viewBinding.etWifiPassword.setText("");
|
||||
viewBinding.etWifiPassword.setEnabled(network.isSecured());
|
||||
viewBinding.etWifiPassword.setHint(network.isSecured()
|
||||
? R.string.wifi_setup_password_hint : R.string.wifi_setup_password_not_required);
|
||||
updateStartButton();
|
||||
}
|
||||
|
||||
private void updateStartButton() {
|
||||
WifiNetwork selected = networkAdapter.getSelected();
|
||||
boolean enabled = provisioning.matches(connectionToken)
|
||||
&& provisioning.getState() == GriddleProvisioningSession.State.READY && selected != null
|
||||
&& (!selected.isSecured() || viewBinding.etWifiPassword.length() > 0);
|
||||
viewBinding.btnStartSetup.setEnabled(enabled);
|
||||
viewBinding.btnStartSetup.setAlpha(enabled ? 1f : 0.5f);
|
||||
viewBinding.btnStartSetup.setText(provisioning.getState() == GriddleProvisioningSession.State.PROVISIONED
|
||||
? R.string.wifi_setup_provision_success : R.string.wifi_setup_start);
|
||||
}
|
||||
|
||||
private void startProvisioning() {
|
||||
// 不 trim:网络名与密码中的首尾空格也可能是有效凭据的一部分。
|
||||
String password = viewBinding.etWifiPassword.getText().toString();
|
||||
int error = provisioning.provision(connectionToken, networkAdapter.getSelected(), password);
|
||||
if (error != 0) {
|
||||
ToastUtil.showShort(this, getString(error));
|
||||
return;
|
||||
}
|
||||
viewBinding.etWifiPassword.setText("");
|
||||
viewBinding.etWifiPassword.clearFocus();
|
||||
InputMethodManager keyboard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
|
||||
if (keyboard != null) keyboard.hideSoftInputFromWindow(viewBinding.etWifiPassword.getWindowToken(), 0);
|
||||
// 只传会话标识,不通过 Intent 传递密码,也不重复发起配网。
|
||||
openingConnecting = true;
|
||||
Intent intent = new Intent(this, DeviceConnectingActivity.class);
|
||||
intent.putExtra(EXTRA_SESSION_TOKEN, connectionToken);
|
||||
connectingLauncher.launch(intent);
|
||||
}
|
||||
|
||||
private void resizeNetworkList() {
|
||||
int rows = Math.min(6, networkAdapter.getItemCount());
|
||||
ViewGroup.LayoutParams params = viewBinding.rvWifiNetworks.getLayoutParams();
|
||||
params.height = Math.round(rows * 43 * getResources().getDisplayMetrics().density);
|
||||
viewBinding.rvWifiNetworks.setLayoutParams(params);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSaveInstanceState(Bundle outState) {
|
||||
outState.putString("selected_network", networkAdapter.getSelectedKey());
|
||||
outState.putBoolean("opening_connecting", openingConnecting);
|
||||
super.onSaveInstanceState(outState);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
if (provisioning != null) {
|
||||
provisioning.detach(sessionListener);
|
||||
// 连接页展示期间保留会话;返回列表或真正退出时再交还/释放。
|
||||
if (!isChangingConfigurations() && !openingConnecting) provisioning.close(connectionToken);
|
||||
}
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override public int getLayoutResId(Bundle savedInstanceState) { return 0; }
|
||||
@Override public void showError(String message) {
|
||||
hideDialogLoading();
|
||||
if (!TextUtils.isEmpty(message)) ToastUtil.showShort(this, message);
|
||||
}
|
||||
@Override public void logOut(BaseBean bean) { }
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.ckkj.griddle.device.adapter;
|
||||
|
||||
import android.text.TextUtils;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.databinding.BlDeviceListItemBinding;
|
||||
import com.ckkj.griddle.device.entity.BleScanDevice;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 按扫描地址去重,保留发现顺序并实时刷新广播名称与 RSSI。 */
|
||||
public class BltDeviceListAdapter extends RecyclerView.Adapter<BltDeviceListAdapter.Holder> {
|
||||
private final List<BleScanDevice> devices = new ArrayList<>();
|
||||
// 保存扫描地址对应的位置,同一设备重复广播时更新原条目,不追加新行。
|
||||
private final Map<String, Integer> positions = new HashMap<>();
|
||||
private OnDeviceClickListener clickListener;
|
||||
|
||||
public interface OnDeviceClickListener { void onDeviceClick(BleScanDevice device); }
|
||||
|
||||
public void setOnDeviceClickListener(OnDeviceClickListener listener) { clickListener = listener; }
|
||||
|
||||
/** 新一轮扫描开始时同时清空数据和地址索引,避免残留上一轮已离线设备。 */
|
||||
public void clear() {
|
||||
int count = devices.size();
|
||||
devices.clear();
|
||||
positions.clear();
|
||||
if (count > 0) notifyItemRangeRemoved(0, count);
|
||||
}
|
||||
|
||||
/** 新设备按发现顺序追加;已存在的设备只更新名称和信号,不改变列表顺序。 */
|
||||
public void updateDevice(BleScanDevice device) {
|
||||
Integer position = positions.get(device.getAddress());
|
||||
if (position == null) {
|
||||
positions.put(device.getAddress(), devices.size());
|
||||
devices.add(device);
|
||||
notifyItemInserted(devices.size() - 1);
|
||||
} else {
|
||||
BleScanDevice previous = devices.get(position);
|
||||
// 部分广播包没有携带名称,保留之前已识别的名称,防止显示反复变成未命名设备。
|
||||
String name = TextUtils.isEmpty(device.getName()) ? previous.getName() : device.getName();
|
||||
// 展示内容未变化时不触发列表刷新,减少持续广播造成的无效更新。
|
||||
if (TextUtils.equals(name, previous.getName()) && device.getRssi() == previous.getRssi()) {
|
||||
return;
|
||||
}
|
||||
devices.set(position, new BleScanDevice(name, device.getAddress(), device.getRssi()));
|
||||
notifyItemChanged(position);
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
return new Holder(BlDeviceListItemBinding.inflate(
|
||||
LayoutInflater.from(parent.getContext()), parent, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull Holder holder, int position) {
|
||||
BleScanDevice device = devices.get(position);
|
||||
BlDeviceListItemBinding binding = holder.binding;
|
||||
binding.tvDeviceName.setText(TextUtils.isEmpty(device.getName())
|
||||
? holder.itemView.getContext().getString(R.string.bl_device_unknown_name) : device.getName());
|
||||
// 扫描阶段尚未读取业务设备信息,因此这里显示 MAC,不将其冒充设备序列号。
|
||||
binding.tvDeviceSn.setText(holder.itemView.getContext().getString(
|
||||
R.string.bl_device_address, device.getAddress()));
|
||||
int label;
|
||||
int color;
|
||||
int background;
|
||||
// RSSI 越接近 0 信号越强;这两个阈值仅用于页面分档,不代表实际距离。
|
||||
if (device.getRssi() >= -60) {
|
||||
label = R.string.bl_device_signal_strong;
|
||||
color = R.color.bl_device_signal_strong;
|
||||
background = R.drawable.bl_device_signal_strong_bg;
|
||||
} else if (device.getRssi() >= -80) {
|
||||
label = R.string.bl_device_signal_medium;
|
||||
color = R.color.device_home_orange;
|
||||
background = R.drawable.mine_soft_pill_bg;
|
||||
} else {
|
||||
label = R.string.bl_device_signal_weak;
|
||||
color = R.color.bl_device_signal_weak;
|
||||
background = R.drawable.bl_device_signal_weak_bg;
|
||||
}
|
||||
// 每次绑定均同步设置文字、颜色和背景,避免列表复用时残留上一设备的样式。
|
||||
binding.tvDeviceSignal.setText(label);
|
||||
binding.tvDeviceSignal.setTextColor(ContextCompat.getColor(holder.itemView.getContext(), color));
|
||||
binding.tvDeviceSignal.setBackgroundResource(background);
|
||||
// 无障碍朗读额外提供原始 dBm 数值,页面仍使用信号强弱标签。
|
||||
binding.tvDeviceSignal.setContentDescription(holder.itemView.getContext().getString(
|
||||
R.string.bl_device_signal_description,
|
||||
holder.itemView.getContext().getString(label), device.getRssi()));
|
||||
// 点击时重新读取位置,避免扫描更新或列表复用后连接到旧条目。
|
||||
binding.getRoot().setOnClickListener(v -> {
|
||||
int current = holder.getBindingAdapterPosition();
|
||||
if (current != RecyclerView.NO_POSITION && clickListener != null) {
|
||||
clickListener.onDeviceClick(devices.get(current));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() { return devices.size(); }
|
||||
|
||||
static final class Holder extends RecyclerView.ViewHolder {
|
||||
final BlDeviceListItemBinding binding;
|
||||
|
||||
Holder(BlDeviceListItemBinding binding) {
|
||||
super(binding.getRoot());
|
||||
this.binding = binding;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ckkj.griddle.device.adapter;
|
||||
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.device.entity.WifiNetwork;
|
||||
import com.ckkj.griddle.device.entity.WifiNetworkSelection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 按设计稿切换普通行和浅橙色选中行;始终只允许选中一个网络。 */
|
||||
public final class WifiNetworkAdapter extends RecyclerView.Adapter<WifiNetworkAdapter.Holder> {
|
||||
public interface OnSelectionChanged { void onSelected(WifiNetwork network); }
|
||||
private final WifiNetworkSelection selection = new WifiNetworkSelection();
|
||||
private final OnSelectionChanged listener;
|
||||
private boolean selectionEnabled = true;
|
||||
|
||||
public WifiNetworkAdapter(OnSelectionChanged listener) { this.listener = listener; }
|
||||
|
||||
public void submit(List<WifiNetwork> result) {
|
||||
selection.submit(result);
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
public void setSelectionEnabled(boolean enabled) { selectionEnabled = enabled; }
|
||||
public WifiNetwork getSelected() { return selection.getSelected(); }
|
||||
public String getSelectedKey() { return selection.getSelectedKey(); }
|
||||
public void restoreSelection(String key) { selection.restoreSelection(key); }
|
||||
@Override public int getItemCount() { return selection.size(); }
|
||||
@Override public int getItemViewType(int position) { return selection.isSelected(position) ? 1 : 0; }
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
return new Holder(LayoutInflater.from(parent.getContext()).inflate(viewType == 1
|
||||
? R.layout.wifi_list_selected_item : R.layout.wifi_list_item, parent, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull Holder holder, int position) {
|
||||
WifiNetwork network = selection.get(position);
|
||||
holder.name.setText(network.getSsid());
|
||||
holder.itemView.setSelected(selection.isSelected(position));
|
||||
if (holder.lock != null) holder.lock.setVisibility(network.isSecured() ? View.VISIBLE : View.GONE);
|
||||
holder.signal.setContentDescription(holder.itemView.getContext().getString(
|
||||
R.string.wifi_setup_signal_description, network.getRssi()));
|
||||
holder.itemView.setOnClickListener(v -> {
|
||||
int current = holder.getBindingAdapterPosition();
|
||||
if (!selectionEnabled || current == RecyclerView.NO_POSITION || selection.isSelected(current)) return;
|
||||
int previous = selection.getSelectedPosition();
|
||||
selection.select(current);
|
||||
// 同时刷新旧行和新行,恢复旧行背景、文字及图标,防止复用后出现多个选中项。
|
||||
if (previous >= 0) notifyItemChanged(previous);
|
||||
notifyItemChanged(current);
|
||||
listener.onSelected(selection.getSelected());
|
||||
});
|
||||
}
|
||||
|
||||
static final class Holder extends RecyclerView.ViewHolder {
|
||||
final TextView name;
|
||||
final ImageView signal;
|
||||
final ImageView lock;
|
||||
Holder(View itemView) {
|
||||
super(itemView);
|
||||
name = itemView.findViewById(R.id.tv_wifi_name);
|
||||
signal = itemView.findViewById(R.id.iv_wifi_signal);
|
||||
lock = itemView.findViewById(R.id.iv_wifi_lock);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ckkj.griddle.device.entity;
|
||||
|
||||
/** 扫描广播的快照;address 仅用于本轮 Android 扫描去重,不作为业务设备身份。 */
|
||||
public final class BleScanDevice {
|
||||
/** 广播或系统缓存中的设备名称,可能为空,缺省显示由适配器处理。 */
|
||||
private final String name;
|
||||
/** Android 扫描地址,仅用于当前扫描列表的去重和展示。 */
|
||||
private final String address;
|
||||
/** 接收信号强度,单位 dBm,用于更新列表中的信号等级。 */
|
||||
private final int rssi;
|
||||
|
||||
public BleScanDevice(String name, String address, int rssi) {
|
||||
this.name = name;
|
||||
this.address = address;
|
||||
this.rssi = rssi;
|
||||
}
|
||||
|
||||
public String getName() { return name; }
|
||||
public String getAddress() { return address; }
|
||||
public int getRssi() { return rssi; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.ckkj.griddle.device.entity;
|
||||
|
||||
/** 设备返回的 Wi-Fi 快照;0 表示开放网络,其余值保留固件给出的认证类型。 */
|
||||
public final class WifiNetwork {
|
||||
private final String ssid;
|
||||
private final int security;
|
||||
private final int rssi;
|
||||
|
||||
public WifiNetwork(String ssid, int security, int rssi) {
|
||||
this.ssid = ssid;
|
||||
this.security = security;
|
||||
this.rssi = rssi;
|
||||
}
|
||||
|
||||
public String getSsid() { return ssid; }
|
||||
public int getSecurity() { return security; }
|
||||
public int getRssi() { return rssi; }
|
||||
public boolean isSecured() { return security != 0; }
|
||||
public String getKey() { return ssid + "\u0000" + security; }
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ckkj.griddle.device.entity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 单选状态独立于列表位置,刷新排序、视图复用时不会把选中状态移到其他 SSID。 */
|
||||
public final class WifiNetworkSelection {
|
||||
private final List<WifiNetwork> networks = new ArrayList<>();
|
||||
private String selectedKey;
|
||||
|
||||
public void submit(List<WifiNetwork> result) {
|
||||
Map<String, WifiNetwork> unique = new LinkedHashMap<>();
|
||||
if (result != null) for (WifiNetwork network : result) {
|
||||
// 隐藏 SSID 无法通过当前列表选择,不展示空白行;同名同认证只保留最强信号。
|
||||
if (network == null || network.getSsid() == null || network.getSsid().isEmpty()) continue;
|
||||
WifiNetwork previous = unique.get(network.getKey());
|
||||
if (previous == null || previous.getRssi() < network.getRssi()) unique.put(network.getKey(), network);
|
||||
}
|
||||
networks.clear();
|
||||
networks.addAll(unique.values());
|
||||
networks.sort(Comparator.comparingInt(WifiNetwork::getRssi).reversed()
|
||||
.thenComparing(WifiNetwork::getSsid).thenComparingInt(WifiNetwork::getSecurity));
|
||||
if (getSelected() == null) selectedKey = null;
|
||||
}
|
||||
|
||||
public void select(int position) { selectedKey = networks.get(position).getKey(); }
|
||||
public void restoreSelection(String key) { selectedKey = key; }
|
||||
public String getSelectedKey() { return selectedKey; }
|
||||
public int size() { return networks.size(); }
|
||||
public WifiNetwork get(int position) { return networks.get(position); }
|
||||
public boolean isSelected(int position) { return networks.get(position).getKey().equals(selectedKey); }
|
||||
public WifiNetwork getSelected() {
|
||||
for (WifiNetwork network : networks) if (network.getKey().equals(selectedKey)) return network;
|
||||
return null;
|
||||
}
|
||||
public int getSelectedPosition() {
|
||||
for (int i = 0; i < networks.size(); i++) if (isSelected(i)) return i;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ckkj.griddle.device.entity;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/** 校验待提交的凭据;SSID、密码均保留原始空格,不写入日志或本地存储。 */
|
||||
public final class WifiProvisioningInput {
|
||||
public enum Error { NONE, NETWORK_REQUIRED, SSID_INVALID, PASSWORD_REQUIRED, PASSWORD_INVALID, SECURITY_UNSUPPORTED }
|
||||
private WifiProvisioningInput() { }
|
||||
|
||||
public static Error validate(WifiNetwork network, String password) {
|
||||
if (network == null) return Error.NETWORK_REQUIRED;
|
||||
String ssid = network.getSsid();
|
||||
if (ssid == null || ssid.isEmpty() || ssid.getBytes(StandardCharsets.UTF_8).length > 32) return Error.SSID_INVALID;
|
||||
int security = network.getSecurity();
|
||||
if (security == 0) return Error.NONE;
|
||||
// 当前页面只有密码输入,不支持需要企业账号/证书的网络或未知认证类型。
|
||||
if (security != 1 && security != 2 && security != 3 && security != 4 && security != 6 && security != 7) {
|
||||
return Error.SECURITY_UNSUPPORTED;
|
||||
}
|
||||
if (password == null || password.isEmpty()) return Error.PASSWORD_REQUIRED;
|
||||
int bytes = password.getBytes(StandardCharsets.UTF_8).length;
|
||||
boolean hex = password.matches("[0-9a-fA-F]+");
|
||||
if (security == 1) {
|
||||
boolean ascii = password.chars().allMatch(c -> c >= 32 && c <= 126);
|
||||
return (ascii && (bytes == 5 || bytes == 13)) || (hex && (bytes == 10 || bytes == 26))
|
||||
? Error.NONE : Error.PASSWORD_INVALID;
|
||||
}
|
||||
// WPA3-SAE 允许较短口令;WPA/WPA2 支持 8~63 字节口令或 64 位十六进制 PSK。
|
||||
boolean valid = security == 6 ? bytes >= 1 && bytes <= 63
|
||||
: bytes >= 8 && bytes <= 63 || bytes == 64 && hex;
|
||||
return valid ? Error.NONE : Error.PASSWORD_INVALID;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ckkj.griddle.device.entity;
|
||||
|
||||
/** SDK 只返回阶段回调;百分比表示阶段进度,100% 必须以设备确认联网成功为准。 */
|
||||
public final class WifiProvisioningProgress {
|
||||
public enum Stage { IDLE, SENDING_CONFIG, CONFIG_SENT, CONNECTING_WIFI, SUCCEEDED, FAILED }
|
||||
private Stage stage = Stage.IDLE;
|
||||
private int percent;
|
||||
|
||||
public void reset() { stage = Stage.IDLE; percent = 0; }
|
||||
public void start() { stage = Stage.SENDING_CONFIG; percent = 10; }
|
||||
public Stage getStage() { return stage; }
|
||||
public int getPercent() { return percent; }
|
||||
public boolean isRunning() {
|
||||
return stage == Stage.SENDING_CONFIG || stage == Stage.CONFIG_SENT || stage == Stage.CONNECTING_WIFI;
|
||||
}
|
||||
public void configurationSent() { advance(Stage.CONFIG_SENT, 40); }
|
||||
public void configurationApplied() { advance(Stage.CONNECTING_WIFI, 70); }
|
||||
public void succeed() { if (isRunning()) { stage = Stage.SUCCEEDED; percent = 100; } }
|
||||
public void fail() { if (isRunning()) stage = Stage.FAILED; }
|
||||
|
||||
private void advance(Stage next, int value) {
|
||||
// 忽略重复或乱序回调,也不允许终态被旧回调覆盖。
|
||||
if (isRunning() && value > percent) { stage = next; percent = value; }
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,34 @@
|
||||
package com.ckkj.griddle.device.mvp;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.ckkj.griddle.base.IView;
|
||||
import com.ckkj.griddle.device.entity.BleScanDevice;
|
||||
|
||||
/** 蓝牙设备列表页面与数据层协议。 */
|
||||
public class BltDeviceListContract {
|
||||
|
||||
public interface CallBack<T> {
|
||||
void success(T data);
|
||||
|
||||
void fail(String message);
|
||||
/** 数据层向协调层回传扫描事件;实际实现统一在主线程触发。 */
|
||||
public interface ScanListener {
|
||||
/** 收到符合电饼铛协议的设备;同一设备可随广播多次回调以更新信号。 */
|
||||
void onDeviceFound(BleScanDevice device);
|
||||
/** 扫描开始或结束,用于切换进度、搜索按钮和状态文案。 */
|
||||
void onScanStateChanged(boolean scanning);
|
||||
/** 参数为提示文案资源 ID,由页面负责显示。 */
|
||||
void onScanError(int messageResId);
|
||||
}
|
||||
|
||||
/** 数据层仅负责扫描及资源释放,不负责弹窗、动态授权或页面跳转。 */
|
||||
public interface DataModel {
|
||||
// 后续定义蓝牙扫描、停止扫描等数据操作。
|
||||
void startScan(Context context, ScanListener listener);
|
||||
void stopScan();
|
||||
boolean isScanning();
|
||||
}
|
||||
|
||||
/** 页面接收协调层转发的事件,并将结果交给列表适配器去重展示。 */
|
||||
public interface BltDeviceListView extends IView {
|
||||
// 后续定义扫描状态及设备列表回调。
|
||||
void onDeviceFound(BleScanDevice device);
|
||||
void onScanStateChanged(boolean scanning);
|
||||
void onScanError(int messageResId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,174 @@
|
||||
package com.ckkj.griddle.device.mvp;
|
||||
|
||||
/** 蓝牙设备列表数据层,后续接入实际扫描逻辑。 */
|
||||
import android.annotation.SuppressLint;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.le.BluetoothLeScanner;
|
||||
import android.bluetooth.le.ScanCallback;
|
||||
import android.bluetooth.le.ScanRecord;
|
||||
import android.bluetooth.le.ScanResult;
|
||||
import android.bluetooth.le.ScanSettings;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.ParcelUuid;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.device.entity.BleScanDevice;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** 原生 BLE 扫描,同时覆盖配网模式和业务模式;权限由页面检查。 */
|
||||
public class BltDeviceListImpl implements BltDeviceListContract.DataModel {
|
||||
// 每轮扫描最多持续 15 秒,避免页面停留时长时间占用蓝牙扫描资源。
|
||||
private static final long SCAN_DURATION_MS = 15_000L;
|
||||
// 协议 v1.1:Wi-Fi + BLE 版和纯 BLE 版使用同一广播名称规则。
|
||||
private static final Pattern DEVICE_NAME_PATTERN =
|
||||
Pattern.compile("electricGriddle-[0-9A-F]{12}");
|
||||
// 此 UUID 属于业务 GATT,不代表待配网阶段一定会广播该服务。
|
||||
private static final ParcelUuid BUSINESS_SERVICE_UUID =
|
||||
new ParcelUuid(UUID.fromString("44424301-0001-4dbc-8000-00805f9b34fb"));
|
||||
// 扫描结果、错误和超时处理统一切回主线程,便于安全更新页面和适配器。
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
private BluetoothLeScanner scanner;
|
||||
private ScanCallback scanCallback;
|
||||
private BltDeviceListContract.ScanListener listener;
|
||||
private final Runnable scanTimeout = this::stopScan;
|
||||
|
||||
/** 创建本轮独立的扫描回调;调用方需提前完成动态权限及系统开关检查。 */
|
||||
@SuppressLint("MissingPermission")
|
||||
@Override
|
||||
public void startScan(Context context, BltDeviceListContract.ScanListener listener) {
|
||||
// 开始新一轮前释放上一轮回调和超时任务,避免多轮扫描互相干扰。
|
||||
stopScan();
|
||||
this.listener = listener;
|
||||
BluetoothManager manager = (BluetoothManager) context.getApplicationContext()
|
||||
.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
BluetoothAdapter adapter = manager == null ? null : manager.getAdapter();
|
||||
try {
|
||||
if (adapter == null || !adapter.isEnabled()) {
|
||||
fail(R.string.bl_device_bluetooth_off);
|
||||
return;
|
||||
}
|
||||
scanner = adapter.getBluetoothLeScanner();
|
||||
if (scanner == null) {
|
||||
fail(R.string.bl_device_scan_failed);
|
||||
return;
|
||||
}
|
||||
ScanCallback callback = new ScanCallback() {
|
||||
@Override
|
||||
public void onScanResult(int callbackType, ScanResult result) {
|
||||
handler.post(() -> publish(this, result));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBatchScanResults(List<ScanResult> results) {
|
||||
handler.post(() -> {
|
||||
for (ScanResult result : results) {
|
||||
publish(this, result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanFailed(int errorCode) {
|
||||
handler.post(() -> {
|
||||
// 旧扫描延迟到达的错误不能终止已经开始的新扫描。
|
||||
if (scanCallback == this) {
|
||||
fail(R.string.bl_device_scan_failed);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
scanCallback = callback;
|
||||
listener.onScanStateChanged(true);
|
||||
// Android 的设备名 ScanFilter 只能匹配完整名称,不能匹配 MAC 后缀变化的前缀。
|
||||
// 统一在 publish 中按协议名称或业务 UUID 筛选;仅按业务 UUID 扫描会漏掉配网设备。
|
||||
ScanSettings settings = new ScanSettings.Builder()
|
||||
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
|
||||
.setReportDelay(0)
|
||||
.build();
|
||||
scanner.startScan(Collections.emptyList(), settings, callback);
|
||||
handler.postDelayed(scanTimeout, SCAN_DURATION_MS);
|
||||
} catch (SecurityException e) {
|
||||
fail(R.string.bl_device_permission_required);
|
||||
} catch (IllegalStateException | IllegalArgumentException e) {
|
||||
fail(R.string.bl_device_scan_failed);
|
||||
}
|
||||
}
|
||||
|
||||
/** 提取广播信息并按协议过滤;通过筛选后才通知页面,因此无关设备不会进入列表。 */
|
||||
@SuppressLint("MissingPermission")
|
||||
private void publish(ScanCallback callback, ScanResult result) {
|
||||
// 扫描停止后仍可能收到已排队的结果,仅处理当前这一轮的有效回调。
|
||||
if (scanCallback != callback || listener == null || result == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ScanRecord record = result.getScanRecord();
|
||||
// 优先使用本次广播中的名称,广播未携带名称时再读取系统缓存的设备名称。
|
||||
String name = record == null ? null : record.getDeviceName();
|
||||
if (TextUtils.isEmpty(name)) {
|
||||
name = result.getDevice().getName();
|
||||
}
|
||||
// 完整匹配固定前缀和 12 位大写十六进制 MAC,避免仅前缀相近的其他设备混入。
|
||||
boolean matchesName = name != null && DEVICE_NAME_PATTERN.matcher(name).matches();
|
||||
List<ParcelUuid> advertisedServices = record == null ? null : record.getServiceUuids();
|
||||
// 广播包含业务 UUID 时也可识别,兼容业务设备没有广播名称的情况。
|
||||
boolean matchesService = advertisedServices != null
|
||||
&& advertisedServices.contains(BUSINESS_SERVICE_UUID);
|
||||
// 名称或业务 UUID 任一匹配即可:不能要求同时满足,否则会漏掉待配网设备。
|
||||
if (!matchesName && !matchesService) {
|
||||
return;
|
||||
}
|
||||
listener.onDeviceFound(new BleScanDevice(name,
|
||||
result.getDevice().getAddress(), result.getRssi()));
|
||||
} catch (SecurityException e) {
|
||||
fail(R.string.bl_device_permission_required);
|
||||
}
|
||||
}
|
||||
|
||||
/** 先清理扫描资源,再使用保存的监听器通知错误,防止清理后丢失错误回调。 */
|
||||
private void fail(int messageResId) {
|
||||
BltDeviceListContract.ScanListener currentListener = listener;
|
||||
stopScan();
|
||||
if (currentListener != null) {
|
||||
currentListener.onScanError(messageResId);
|
||||
}
|
||||
}
|
||||
|
||||
/** 页面离开、扫描超时或扫描失败时复用此方法,可重复调用。 */
|
||||
@SuppressLint("MissingPermission")
|
||||
@Override
|
||||
public void stopScan() {
|
||||
ScanCallback previousCallback = scanCallback;
|
||||
BluetoothLeScanner previousScanner = scanner;
|
||||
BltDeviceListContract.ScanListener previousListener = listener;
|
||||
// 先使本轮回调失效,再停止系统扫描;随后到达的旧结果会被 publish 忽略。
|
||||
scanCallback = null;
|
||||
scanner = null;
|
||||
listener = null;
|
||||
// Handler 只属于本扫描器,可一并移除超时任务和已排队的扫描结果。
|
||||
handler.removeCallbacksAndMessages(null);
|
||||
if (previousCallback != null && previousScanner != null) {
|
||||
try {
|
||||
previousScanner.stopScan(previousCallback);
|
||||
} catch (SecurityException | IllegalStateException ignored) {
|
||||
// 蓝牙关闭或权限被撤销时,也必须清理本地扫描状态。
|
||||
}
|
||||
}
|
||||
// 仅在确实存在活动扫描时通知结束,避免重复停止导致页面状态反复变化。
|
||||
if (previousCallback != null && previousListener != null) {
|
||||
previousListener.onScanStateChanged(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isScanning() {
|
||||
return scanCallback != null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.ckkj.griddle.device.mvp;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.ckkj.griddle.base.BasePresenter;
|
||||
import com.ckkj.griddle.device.entity.BleScanDevice;
|
||||
|
||||
/** 蓝牙设备列表业务协调层。 */
|
||||
public class BltDeviceListPresenter
|
||||
@@ -11,4 +14,37 @@ public class BltDeviceListPresenter
|
||||
public BltDeviceListPresenter(BltDeviceListContract.DataModel impl) {
|
||||
this.impl = impl;
|
||||
}
|
||||
|
||||
/** 将扫描事件转发给仍绑定的页面,页面销毁后不再访问视图。 */
|
||||
public void startScan(Context context) {
|
||||
impl.startScan(context, new BltDeviceListContract.ScanListener() {
|
||||
@Override
|
||||
public void onDeviceFound(BleScanDevice device) {
|
||||
if (mRootView != null) mRootView.onDeviceFound(device);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanStateChanged(boolean scanning) {
|
||||
if (mRootView != null) mRootView.onScanStateChanged(scanning);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onScanError(int messageResId) {
|
||||
if (mRootView != null) mRootView.onScanError(messageResId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 页面暂停时主动停止扫描,不等待本轮 15 秒超时。 */
|
||||
public void stopScan() { impl.stopScan(); }
|
||||
|
||||
/** 供页面判断是否已有扫描在运行,避免重复启动。 */
|
||||
public boolean isScanning() { return impl.isScanning(); }
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
// 最终释放扫描回调和定时任务,再解除页面引用。
|
||||
impl.stopScan();
|
||||
super.onDestroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,8 @@ public class FateContract {
|
||||
void getUserTodayFateDatas(Map<String,Object> map, CallBack callBack);
|
||||
//查询历史运势
|
||||
void getUserFateHistory(Map<String,Object> map, CallBack callBack);
|
||||
//提交举报反馈
|
||||
void commitReport(Map<String,Object> map, CallBack callBack);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -229,4 +229,45 @@ public class FateImpl implements FateContract.DataModel{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 举报反馈
|
||||
* @param map
|
||||
* @param callBack
|
||||
*/
|
||||
@Override
|
||||
public void commitReport(Map<String, Object> map, FateContract.CallBack callBack) {
|
||||
try {
|
||||
NetWorkManager.getRequest().commitReporting(NetWorkManager.getToken(), map)
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean bean) {
|
||||
if (bean.getCode() == 200) {
|
||||
callBack.success(bean);
|
||||
} else {
|
||||
callBack.fail(bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callBack.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ package com.ckkj.griddle.fate.mvp;
|
||||
|
||||
import com.ckkj.griddle.base.BasePresenter;
|
||||
import com.ckkj.griddle.base.entity.MineUserInfoBean;
|
||||
import com.ckkj.griddle.chat.mvp.IndexContract;
|
||||
import com.ckkj.griddle.chat.mvp.IndexImpl;
|
||||
import com.ckkj.griddle.fate.entity.CityDataEntity;
|
||||
import com.ckkj.griddle.fate.entity.FateHistoryEntity;
|
||||
import com.ckkj.griddle.fate.entity.TodayFateEntity;
|
||||
@@ -173,7 +171,7 @@ public class FatePresenter extends BasePresenter<FateContract.FateView> {
|
||||
public void commitReport(String reason) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("content", reason);
|
||||
new IndexImpl().commitReport(map, new IndexContract.CallBack<BaseBean>() {
|
||||
impl.commitReport(map, new FateContract.CallBack<BaseBean>() {
|
||||
@Override
|
||||
public void success(BaseBean bean) {
|
||||
if (FatePresenter.this.getView() != null) {
|
||||
|
||||
@@ -158,11 +158,6 @@ public class LaunchActivity extends BaseActivity<GuideLayoutBinding, MainPresent
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getYunshiDataSuccess(BaseBean bean) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getUserInfoSuccess(MineUserInfoBean bean) {
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ public class LoginActivity extends BaseActivity<LoginLayoutBinding, LoginPresent
|
||||
.init();
|
||||
ClickUtil.addClickPart(viewBinding.checkboxRead, 100);
|
||||
initAgreement();
|
||||
updateAgreementCheckState();
|
||||
initCountDownTimer();
|
||||
switchLoginMode(false);
|
||||
}
|
||||
@@ -134,13 +135,19 @@ public class LoginActivity extends BaseActivity<LoginLayoutBinding, LoginPresent
|
||||
tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
|
||||
}
|
||||
|
||||
private void updateAgreementCheckState() {
|
||||
viewBinding.checkboxRead.setChecked(mYinsiConfirm);
|
||||
viewBinding.checkboxRead.setBackgroundResource(mYinsiConfirm
|
||||
? R.mipmap.icon_login_checked : R.mipmap.icon_uncheck);
|
||||
}
|
||||
|
||||
@OnClick({R.id.tv_login_confirm, R.id.tv_get_code, R.id.checkbox_read,
|
||||
R.id.tv_login_mode_switch, R.id.tv_go_register, R.id.btn1, R.id.btn2})
|
||||
public void onClick(View v) {
|
||||
switch (v.getId()) {
|
||||
case R.id.checkbox_read:
|
||||
mYinsiConfirm = !mYinsiConfirm;
|
||||
viewBinding.checkboxRead.setChecked(mYinsiConfirm);
|
||||
updateAgreementCheckState();
|
||||
break;
|
||||
|
||||
case R.id.tv_login_mode_switch:
|
||||
|
||||
@@ -13,8 +13,6 @@ public interface MainContract {
|
||||
interface DataModel{
|
||||
//新版本检测
|
||||
void checkAppVersionCode(JSONObject json, CallBack callBack);
|
||||
//运势
|
||||
void getYunshiData(Map<String,Object> map, CallBack callBack);
|
||||
}
|
||||
|
||||
interface CallBack<T> {
|
||||
@@ -30,7 +28,6 @@ public interface MainContract {
|
||||
void activationVipSuccess(BaseBean bean);
|
||||
//校验版本号
|
||||
void getVersionCheck(CheckVersionEntity bean);
|
||||
void getYunshiDataSuccess(BaseBean bean);
|
||||
//获取个人信息成功
|
||||
void getUserInfoSuccess(MineUserInfoBean bean);
|
||||
}
|
||||
|
||||
@@ -59,40 +59,4 @@ public class MainImpl implements MainContract.DataModel{
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getYunshiData(Map<String, Object> map, MainContract.CallBack callBack) {
|
||||
// try {
|
||||
// NetWorkManager.getRequest().indexTalkToAi(NetWorkManager.getToken(),map)
|
||||
// .subscribeOn(Schedulers.io())
|
||||
// .unsubscribeOn(Schedulers.io())
|
||||
// .observeOn(AndroidSchedulers.mainThread())
|
||||
// .subscribe(new Observer<BaseBean>() {
|
||||
// @Override
|
||||
// public void onSubscribe(@NonNull Disposable d) {
|
||||
//
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void onNext(@NonNull BaseBean bean) {
|
||||
// if(bean.getCode() == 200){
|
||||
// callBack.success(bean);
|
||||
// }else{
|
||||
// callBack.fail(bean.getMessage());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void onError(@NonNull Throwable e) {
|
||||
// callBack.fail(e.getMessage());
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void onComplete() {
|
||||
// }
|
||||
// });
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import com.ckkj.griddle.base.entity.MineUserInfoBean;
|
||||
import com.ckkj.griddle.login.mvp.LoginContract;
|
||||
import com.ckkj.griddle.main.entity.CheckVersionEntity;
|
||||
import com.ckkj.griddle.base.repository.UserInfoRepository;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
@@ -43,29 +42,6 @@ public class MainPresenter extends BasePresenter<MainContract.MainView> {
|
||||
});
|
||||
}
|
||||
|
||||
public void getYunShiData() {
|
||||
Map<String,Object> map = new HashMap<>();
|
||||
map.put("content","生日:2002年4月28日 下午3点, 性别:男;根据八字命理帮我分析一下命理");
|
||||
map.put("type",1);
|
||||
// map.put("content","你如何看待叙利亚局势,做出详细分析");
|
||||
// map.put("content","你如何看待母猪的产后护理,请帮我详细介绍一下");
|
||||
mainImpl.getYunshiData(map, new MainContract.CallBack<BaseBean>() {
|
||||
@Override
|
||||
public void success(BaseBean bean) {
|
||||
if( MainPresenter.this.getView() != null){
|
||||
MainPresenter.this.getView().getYunshiDataSuccess(bean);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String msg) {
|
||||
if( MainPresenter.this.getView() != null){
|
||||
MainPresenter.this.getView().showError(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询个人信息
|
||||
*/
|
||||
|
||||
@@ -3,9 +3,6 @@ package com.ckkj.griddle.main.activity;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.animation.Animation;
|
||||
import android.view.animation.AnimationUtils;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
@@ -21,7 +18,6 @@ import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.adapter.ViewPageAdapter;
|
||||
import com.ckkj.griddle.base.BaseActivity;
|
||||
import com.ckkj.griddle.base.entity.MineUserInfoBean;
|
||||
import com.ckkj.griddle.chat.ChatFragment;
|
||||
import com.ckkj.griddle.databinding.MainActivityLayoutBinding;
|
||||
import com.ckkj.griddle.dialog.DialogAppUpdate;
|
||||
import com.ckkj.griddle.fate.view.FateFragment;
|
||||
@@ -32,6 +28,7 @@ import com.ckkj.griddle.main.entity.CheckVersionEntity;
|
||||
import com.ckkj.griddle.mine.MineFragment;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.device.DeviceFragment;
|
||||
import com.ckkj.griddle.shop.ShopFragment;
|
||||
import com.ckkj.griddle.utils.AppInfoUtil;
|
||||
import com.ckkj.griddle.utils.dataUtil.SharePreUtil;
|
||||
import com.ckkj.griddle.utils.manager.ActivityManager;
|
||||
@@ -108,7 +105,7 @@ public class MainActivity extends BaseActivity<MainActivityLayoutBinding, MainPr
|
||||
// 清空Fragment列表,避免状态恢复问题
|
||||
mFragmentList.clear();
|
||||
mFragmentList.add(new DeviceFragment());
|
||||
mFragmentList.add(new ChatFragment());
|
||||
mFragmentList.add(new ShopFragment());
|
||||
mFragmentList.add(new FateFragment());
|
||||
mFragmentList.add(new Fragment(R.layout.fragment_placeholder)); // 文化页占位
|
||||
mFragmentList.add(new MineFragment());
|
||||
@@ -125,9 +122,9 @@ public class MainActivity extends BaseActivity<MainActivityLayoutBinding, MainPr
|
||||
viewBinding.navViewpage2.setSaveEnabled(false);
|
||||
viewBinding.navViewpage2.setUserInputEnabled(false);
|
||||
|
||||
// 检查是否需要跳转到IndexFragment(仅在首次创建时)
|
||||
// 检查是否需要跳转到商城页(仅在首次创建时)
|
||||
if (isFirstCreate) {
|
||||
checkAndNavigateToIndexFragment();
|
||||
checkAndNavigateToShopFragment();
|
||||
isFirstCreate = false;
|
||||
}
|
||||
|
||||
@@ -143,7 +140,7 @@ public class MainActivity extends BaseActivity<MainActivityLayoutBinding, MainPr
|
||||
break;
|
||||
case 1:
|
||||
viewBinding.navView.getMenu().getItem(position).setChecked(true);
|
||||
viewBinding.navView.setSelectedItemId(R.id.navigation_index);
|
||||
viewBinding.navView.setSelectedItemId(R.id.navigation_shop);
|
||||
break;
|
||||
case 2:
|
||||
viewBinding.navView.getMenu().getItem(position).setChecked(true);
|
||||
@@ -167,7 +164,7 @@ public class MainActivity extends BaseActivity<MainActivityLayoutBinding, MainPr
|
||||
case R.id.navigation_device:
|
||||
viewBinding.navViewpage2.setCurrentItem(0);
|
||||
return true;
|
||||
case R.id.navigation_index:
|
||||
case R.id.navigation_shop:
|
||||
viewBinding.navViewpage2.setCurrentItem(1);
|
||||
return true;
|
||||
case R.id.navigation_fate:
|
||||
@@ -194,59 +191,31 @@ public class MainActivity extends BaseActivity<MainActivityLayoutBinding, MainPr
|
||||
if (extras != null && extras.getBoolean("goto_index_fragment", false)) {
|
||||
// 延迟执行,确保Fragment已经初始化完成
|
||||
viewBinding.navViewpage2.post(() -> {
|
||||
// 跳转到IndexFragment(位置为1)
|
||||
// 跳转到商城页(位置为1)
|
||||
viewBinding.navViewpage2.setCurrentItem(1);
|
||||
// 设置底部导航栏选中状态
|
||||
viewBinding.navView.setSelectedItemId(R.id.navigation_index);
|
||||
|
||||
// 将参数传递给IndexFragment
|
||||
passBundleToIndexFragment(extras);
|
||||
viewBinding.navView.setSelectedItemId(R.id.navigation_shop);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查并跳转到IndexFragment(仅在首次创建时)
|
||||
* 检查并跳转到商城页(仅在首次创建时)
|
||||
*/
|
||||
private void checkAndNavigateToIndexFragment() {
|
||||
private void checkAndNavigateToShopFragment() {
|
||||
Bundle extras = getIntent().getExtras();
|
||||
if (extras != null && extras.getBoolean("goto_index_fragment", false)) {
|
||||
// 延迟执行,确保Fragment已经初始化完成
|
||||
viewBinding.navViewpage2.post(() -> {
|
||||
// 跳转到IndexFragment(位置为1)
|
||||
// 跳转到商城页(位置为1)
|
||||
viewBinding.navViewpage2.setCurrentItem(1);
|
||||
// 设置底部导航栏选中状态
|
||||
viewBinding.navView.setSelectedItemId(R.id.navigation_index);
|
||||
|
||||
// 将参数传递给IndexFragment
|
||||
passBundleToIndexFragment(extras);
|
||||
viewBinding.navView.setSelectedItemId(R.id.navigation_shop);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将Bundle参数传递给IndexFragment
|
||||
*/
|
||||
private void passBundleToIndexFragment(Bundle bundle) {
|
||||
// 获取IndexFragment实例
|
||||
Fragment indexFragment = mFragmentList.get(1);
|
||||
if (indexFragment instanceof ChatFragment) {
|
||||
// 设置参数到Fragment
|
||||
indexFragment.setArguments(bundle);
|
||||
|
||||
// 如果Fragment已经创建,可以调用其方法来处理参数
|
||||
if (indexFragment.isAdded()) {
|
||||
((ChatFragment) indexFragment).handleBirthInfoBundle(bundle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void getYunshiDataSuccess(BaseBean bean) {
|
||||
hideDialogLoading();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取个人信息
|
||||
@@ -295,13 +264,6 @@ public class MainActivity extends BaseActivity<MainActivityLayoutBinding, MainPr
|
||||
}
|
||||
|
||||
|
||||
private void animateIcon(ImageView icon) {
|
||||
Animation explodeAnimation = AnimationUtils.loadAnimation(this, R.anim.index_tab_anim);
|
||||
icon.startAnimation(explodeAnimation);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
package com.ckkj.griddle.main.entity;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2025/7/5
|
||||
* @description TODO: 描述该类的作用
|
||||
*/
|
||||
|
||||
public class DeepEntity {
|
||||
private String daily_horoscope;
|
||||
private String bazi;
|
||||
private String wuxing;
|
||||
private String constellation;
|
||||
private String weather_influence;
|
||||
private String overall_prediction;
|
||||
private String metal;
|
||||
private String wood;
|
||||
private String water;
|
||||
private String fire;
|
||||
private String earth;
|
||||
|
||||
public String getDaily_horoscope() {
|
||||
return daily_horoscope;
|
||||
}
|
||||
|
||||
public void setDaily_horoscope(String daily_horoscope) {
|
||||
this.daily_horoscope = daily_horoscope;
|
||||
}
|
||||
|
||||
public String getBazi() {
|
||||
return bazi;
|
||||
}
|
||||
|
||||
public void setBazi(String bazi) {
|
||||
this.bazi = bazi;
|
||||
}
|
||||
|
||||
public String getWuxing() {
|
||||
return wuxing;
|
||||
}
|
||||
|
||||
public void setWuxing(String wuxing) {
|
||||
this.wuxing = wuxing;
|
||||
}
|
||||
|
||||
public String getConstellation() {
|
||||
return constellation;
|
||||
}
|
||||
|
||||
public void setConstellation(String constellation) {
|
||||
this.constellation = constellation;
|
||||
}
|
||||
|
||||
public String getWeather_influence() {
|
||||
return weather_influence;
|
||||
}
|
||||
|
||||
public void setWeather_influence(String weather_influence) {
|
||||
this.weather_influence = weather_influence;
|
||||
}
|
||||
|
||||
public String getOverall_prediction() {
|
||||
return overall_prediction;
|
||||
}
|
||||
|
||||
public void setOverall_prediction(String overall_prediction) {
|
||||
this.overall_prediction = overall_prediction;
|
||||
}
|
||||
|
||||
public String getMetal() {
|
||||
return metal;
|
||||
}
|
||||
|
||||
public void setMetal(String metal) {
|
||||
this.metal = metal;
|
||||
}
|
||||
|
||||
public String getWood() {
|
||||
return wood;
|
||||
}
|
||||
|
||||
public void setWood(String wood) {
|
||||
this.wood = wood;
|
||||
}
|
||||
|
||||
public String getWater() {
|
||||
return water;
|
||||
}
|
||||
|
||||
public void setWater(String water) {
|
||||
this.water = water;
|
||||
}
|
||||
|
||||
public String getFire() {
|
||||
return fire;
|
||||
}
|
||||
|
||||
public void setFire(String fire) {
|
||||
this.fire = fire;
|
||||
}
|
||||
|
||||
public String getEarth() {
|
||||
return earth;
|
||||
}
|
||||
|
||||
public void setEarth(String earth) {
|
||||
this.earth = earth;
|
||||
}
|
||||
}
|
||||
@@ -337,6 +337,7 @@ public class NetWorkManager {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
try {
|
||||
map.put("Authorization", "Bearer " + AppConfig.USER_TOKEN);
|
||||
map.put("clientId", "app");
|
||||
// map.put("Authorization", "Bearer " + "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxOTI1NzYwMTgxMTMyNzI2MDIyLCJ1c2VyX2tleSI6IjY0YjVmMjRjLTIyM2ItNDRkZC1iMDJlLTI0ZTRiNzNmODgxZCIsInVzZXJuYW1lIjoiMTg2NDU5MDQzMDIifQ.PiIjBZlQ9UtOuotfhd5mZZO2e8SbMpbXU7VDvVeiWZIecsFDUd51Rae09EFxQ_MJmBUEvIdyysnyqYiBC2AEfw");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
|
||||
@@ -3,18 +3,16 @@ package com.ckkj.griddle.network;
|
||||
|
||||
|
||||
import com.ckkj.griddle.base.entity.MineUserInfoBean;
|
||||
import com.ckkj.griddle.chat.entity.ChatQuestionEntity;
|
||||
import com.ckkj.griddle.fate.entity.CityDataEntity;
|
||||
import com.ckkj.griddle.fate.entity.FateHistoryEntity;
|
||||
import com.ckkj.griddle.fate.entity.TodayFateEntity;
|
||||
import com.ckkj.griddle.chat.entity.CharHistoryEntity;
|
||||
import com.ckkj.griddle.chat.entity.ChatAiMsgEntity;
|
||||
import com.ckkj.griddle.chat.entity.IndexTemplateEntity;
|
||||
import com.ckkj.griddle.login.entity.LoginEntity;
|
||||
import com.ckkj.griddle.main.entity.CheckVersionEntity;
|
||||
import com.ckkj.griddle.plate.entity.BaziResultBean;
|
||||
import com.ckkj.griddle.plate.entity.BaziSaveSuccessEntity;
|
||||
import com.ckkj.griddle.plate.entity.PaipanHistoryEntity;
|
||||
import com.ckkj.griddle.shop.entity.ShopBannerEntity;
|
||||
import com.ckkj.griddle.shop.entity.ShopCategoryEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -47,24 +45,6 @@ public interface Request {
|
||||
//版本检测更新
|
||||
@POST("mine/api/versionNum")
|
||||
Observable<BaseBean<CheckVersionEntity>> getVersionCheck(@HeaderMap Map<String, String> headMap, @QueryMap Map<String, Object> map);
|
||||
//版本检测更新
|
||||
@POST("mobile/context")
|
||||
Observable<BaseBean<ChatAiMsgEntity>> indexTalkToAi(@HeaderMap Map<String, String> headMap, @QueryMap Map<String, Object> map);
|
||||
//首页模板消息数据获取
|
||||
@POST("mobile/homeInfo")
|
||||
Observable<BaseBean<List<IndexTemplateEntity>>> getIndexTemplateDatas();
|
||||
//会话底部模板数据获取
|
||||
@POST("mobile/aitebcontent")
|
||||
Observable<BaseBean<List<ChatQuestionEntity>>> aitebcontent();
|
||||
//对话历史记录
|
||||
@POST("mobile/mySessions")
|
||||
Observable<BaseBean<CharHistoryEntity>> getHistoryList(@HeaderMap Map<String, String> headMap, @QueryMap Map<String, Object> map);
|
||||
//删除历史记录
|
||||
@POST("mobile/deleteSession")
|
||||
Observable<BaseBean> deleteHistoryBySessionID(@HeaderMap Map<String, String> headMap, @QueryMap Map<String, Object> map);
|
||||
//根据 id 查询会话详情
|
||||
@POST("mobile/sessionMessages")
|
||||
Observable<BaseBean<List<ChatAiMsgEntity>>> getChatDetailById(@HeaderMap Map<String, String> headMap, @QueryMap Map<String, Object> map);
|
||||
//获取城市列表
|
||||
@GET("mobile/chinaCites")
|
||||
Observable<BaseBean<List<CityDataEntity>>> getCityDatas(@HeaderMap Map<String, String> headMap, @QueryMap Map<String, Object> map);
|
||||
@@ -116,5 +96,15 @@ public interface Request {
|
||||
//问题反馈
|
||||
@POST("mobile/reporting")
|
||||
Observable<BaseBean> commitReporting(@HeaderMap Map<String, String> headMap,@QueryMap Map<String, Object> map);
|
||||
/**
|
||||
* 获取商城顶部轮播商品,接口最多返回三个在售商品。
|
||||
*/
|
||||
@GET("app/elicacy/banners")
|
||||
Observable<BaseBean<List<ShopBannerEntity>>> getShopBanners(@HeaderMap Map<String, String> headMap);
|
||||
/**
|
||||
* 获取商城商品分类列表。
|
||||
*/
|
||||
@GET("app/elicacy/categories")
|
||||
Observable<BaseBean<List<ShopCategoryEntity>>> getShopCategories(@HeaderMap Map<String, String> headMap);
|
||||
/***************************钱包********************************/
|
||||
}
|
||||
|
||||
292
app/src/main/java/com/ckkj/griddle/shop/ShopFragment.java
Normal file
292
app/src/main/java/com/ckkj/griddle/shop/ShopFragment.java
Normal file
@@ -0,0 +1,292 @@
|
||||
package com.ckkj.griddle.shop;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.text.TextUtils;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.GridLayoutManager;
|
||||
import androidx.recyclerview.widget.LinearLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.base.BaseFragment;
|
||||
import com.ckkj.griddle.custom.view.CustomRefreshHeader;
|
||||
import com.ckkj.griddle.databinding.ShopFragmentBinding;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.shop.adapter.ShopBannerAdapter;
|
||||
import com.ckkj.griddle.shop.adapter.ShopCategoryAdapter;
|
||||
import com.ckkj.griddle.shop.adapter.ShopFoodAdapter;
|
||||
import com.ckkj.griddle.shop.entity.ShopBannerEntity;
|
||||
import com.ckkj.griddle.shop.entity.ShopCategoryEntity;
|
||||
import com.ckkj.griddle.shop.mvp.ShopContract;
|
||||
import com.ckkj.griddle.shop.mvp.ShopImpl;
|
||||
import com.ckkj.griddle.shop.mvp.ShopPresenter;
|
||||
import com.ckkj.griddle.utils.show.ToastUtil;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 美食商城首页。
|
||||
*/
|
||||
public class ShopFragment extends BaseFragment<ShopFragmentBinding, ShopPresenter>
|
||||
implements ShopContract.ShopView {
|
||||
|
||||
/**
|
||||
* Banner 自动切换间隔。
|
||||
*/
|
||||
private static final long BANNER_SWITCH_INTERVAL = 3500L;
|
||||
|
||||
/**
|
||||
* 商城首页下拉刷新时等待的网络请求数量。
|
||||
*/
|
||||
private static final int SHOP_NETWORK_REQUEST_COUNT = 2;
|
||||
|
||||
/**
|
||||
* 使用主线程 Handler 控制 Banner 自动轮播。
|
||||
*/
|
||||
private final Handler bannerHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* 循环切换到下一张 Banner,只有存在多条数据时才继续调度。
|
||||
*/
|
||||
private final Runnable bannerSwitchTask = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (viewBinding == null || bannerAdapter == null
|
||||
|| bannerAdapter.getItemCount() <= 1) {
|
||||
return;
|
||||
}
|
||||
int currentItem = viewBinding.vpFoodBanner.getCurrentItem();
|
||||
int nextItem = (currentItem + 1) % bannerAdapter.getItemCount();
|
||||
viewBinding.vpFoodBanner.setCurrentItem(nextItem, true);
|
||||
bannerHandler.postDelayed(this, BANNER_SWITCH_INTERVAL);
|
||||
}
|
||||
};
|
||||
|
||||
private ShopBannerAdapter bannerAdapter;
|
||||
private ShopCategoryAdapter categoryAdapter;
|
||||
private ShopFoodAdapter breakfastAdapter;
|
||||
private ShopFoodAdapter recommendationAdapter;
|
||||
/**
|
||||
* 保存商品分类接口结果,当前暂不用于页面展示。
|
||||
*/
|
||||
private List<ShopCategoryEntity> shopCategories = Collections.emptyList();
|
||||
/**
|
||||
* 标记当前是否由用户下拉触发了数据刷新。
|
||||
*/
|
||||
private boolean shopRefreshing;
|
||||
/**
|
||||
* 当前仍未结束的商城网络请求数量。
|
||||
*/
|
||||
private int pendingShopRequests;
|
||||
|
||||
@Override
|
||||
public ShopPresenter createPresenter() {
|
||||
return new ShopPresenter(new ShopImpl());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initData(Bundle state) {
|
||||
initRecyclerViews();
|
||||
initBanner();
|
||||
initRefresh();
|
||||
loadShopData();
|
||||
}
|
||||
|
||||
private void initRecyclerViews() {
|
||||
if (viewBinding.rvFoodCategories.getLayoutManager() == null) {
|
||||
viewBinding.rvFoodCategories.setLayoutManager(new LinearLayoutManager(
|
||||
mContext, RecyclerView.HORIZONTAL, false));
|
||||
}
|
||||
if (viewBinding.rvFoodBreakfast.getLayoutManager() == null) {
|
||||
viewBinding.rvFoodBreakfast.setLayoutManager(new LinearLayoutManager(
|
||||
mContext, RecyclerView.HORIZONTAL, false));
|
||||
}
|
||||
if (viewBinding.rvFoodRecommend.getLayoutManager() == null) {
|
||||
viewBinding.rvFoodRecommend.setLayoutManager(new GridLayoutManager(mContext, 2));
|
||||
}
|
||||
|
||||
categoryAdapter = new ShopCategoryAdapter(this::showCategory);
|
||||
breakfastAdapter = new ShopFoodAdapter(R.layout.food_breakfast_item);
|
||||
recommendationAdapter = new ShopFoodAdapter(R.layout.food_recommend_item);
|
||||
viewBinding.rvFoodCategories.setAdapter(categoryAdapter);
|
||||
viewBinding.rvFoodBreakfast.setAdapter(breakfastAdapter);
|
||||
viewBinding.rvFoodRecommend.setAdapter(recommendationAdapter);
|
||||
}
|
||||
|
||||
private void initBanner() {
|
||||
// 先绑定适配器,接口返回后再提交真实的轮播商品数据。
|
||||
bannerAdapter = new ShopBannerAdapter();
|
||||
viewBinding.vpFoodBanner.setAdapter(bannerAdapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* 复用项目现有的刷新头,商城页面只开启下拉刷新。
|
||||
*/
|
||||
private void initRefresh() {
|
||||
viewBinding.refreshShop.setRefreshHeader(new CustomRefreshHeader(mContext));
|
||||
viewBinding.refreshShop.setEnableLoadMore(false);
|
||||
viewBinding.refreshShop.setOnRefreshListener(refreshLayout -> refreshShopData());
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载商城 Banner 和页面内容。
|
||||
*/
|
||||
private void loadShopData() {
|
||||
pendingShopRequests = SHOP_NETWORK_REQUEST_COUNT;
|
||||
mPresenter.loadContent();
|
||||
mPresenter.getShopCategories();
|
||||
mPresenter.getShopBanners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户下拉后暂停自动轮播,并重新请求页面数据。
|
||||
*/
|
||||
private void refreshShopData() {
|
||||
shopRefreshing = true;
|
||||
stopBannerAutoPlay();
|
||||
loadShopData();
|
||||
}
|
||||
|
||||
/**
|
||||
* 每完成一个网络请求就更新计数,全部结束后收起下拉刷新头。
|
||||
*/
|
||||
private void completeShopNetworkRequest() {
|
||||
if (!shopRefreshing) {
|
||||
return;
|
||||
}
|
||||
if (pendingShopRequests > 0) {
|
||||
pendingShopRequests--;
|
||||
}
|
||||
if (pendingShopRequests > 0) {
|
||||
return;
|
||||
}
|
||||
shopRefreshing = false;
|
||||
if (viewBinding != null) {
|
||||
viewBinding.refreshShop.finishRefresh(300);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getShopBannersSuccess(List<ShopBannerEntity> banners) {
|
||||
// 接口数据可能为空,统一转换为空列表后再交给适配器。
|
||||
List<ShopBannerEntity> bannerList = banners == null
|
||||
? Collections.emptyList()
|
||||
: banners;
|
||||
bannerAdapter.submitList(bannerList);
|
||||
if (!bannerList.isEmpty()) {
|
||||
// 新数据到达后从第一张开始展示。
|
||||
viewBinding.vpFoodBanner.setCurrentItem(0, false);
|
||||
}
|
||||
startBannerAutoPlay();
|
||||
completeShopNetworkRequest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getShopCategoriesSuccess(List<ShopCategoryEntity> categories) {
|
||||
// 暂不展示商品分类,只保存接口返回结果,后续接入分类 UI 时直接使用。
|
||||
shopCategories = categories == null ? Collections.emptyList() : categories;
|
||||
completeShopNetworkRequest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showShopContent(ShopContract.ShopContent content) {
|
||||
if (content == null) {
|
||||
categoryAdapter.submitList(Collections.emptyList());
|
||||
breakfastAdapter.submitList(Collections.emptyList());
|
||||
recommendationAdapter.submitList(Collections.emptyList());
|
||||
return;
|
||||
}
|
||||
|
||||
categoryAdapter.submitList(content.getCategories());
|
||||
recommendationAdapter.submitList(content.getRecommendations());
|
||||
|
||||
List<ShopContract.Category> categories = content.getCategories();
|
||||
if (categories.isEmpty()) {
|
||||
breakfastAdapter.submitList(Collections.emptyList());
|
||||
} else {
|
||||
showCategory(categories.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
private void showCategory(ShopContract.Category category) {
|
||||
if (category == null) {
|
||||
return;
|
||||
}
|
||||
viewBinding.tvFoodSectionTitle.setText(category.getTitleRes());
|
||||
breakfastAdapter.submitList(category.getFoods());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResumeInitData() {
|
||||
super.onResumeInitData();
|
||||
startBannerAutoPlay();
|
||||
}
|
||||
|
||||
private void startBannerAutoPlay() {
|
||||
// 页面不可见或只有一条数据时停止自动轮播,避免无效切换。
|
||||
bannerHandler.removeCallbacks(bannerSwitchTask);
|
||||
if (!isResumed() || bannerAdapter == null || bannerAdapter.getItemCount() <= 1) {
|
||||
return;
|
||||
}
|
||||
bannerHandler.postDelayed(bannerSwitchTask, BANNER_SWITCH_INTERVAL);
|
||||
}
|
||||
|
||||
private void stopBannerAutoPlay() {
|
||||
bannerHandler.removeCallbacks(bannerSwitchTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
stopBannerAutoPlay();
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
stopBannerAutoPlay();
|
||||
shopRefreshing = false;
|
||||
pendingShopRequests = 0;
|
||||
// 主动解除 RecyclerView 对适配器的引用,避免视图销毁后继续持有页面对象。
|
||||
if (viewBinding != null) {
|
||||
viewBinding.vpFoodBanner.setAdapter(null);
|
||||
viewBinding.rvFoodCategories.setAdapter(null);
|
||||
viewBinding.rvFoodBreakfast.setAdapter(null);
|
||||
viewBinding.rvFoodRecommend.setAdapter(null);
|
||||
}
|
||||
bannerAdapter = null;
|
||||
categoryAdapter = null;
|
||||
breakfastAdapter = null;
|
||||
recommendationAdapter = null;
|
||||
super.onDestroyView();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNetChange(int netModel) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showError(String message) {
|
||||
hideDialogLoading();
|
||||
if (mContext != null && !TextUtils.isEmpty(message)) {
|
||||
ToastUtil.showShort(mContext, message);
|
||||
}
|
||||
completeShopNetworkRequest();
|
||||
startBannerAutoPlay();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void logOut(BaseBean bean) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.ckkj.griddle.shop.adapter;
|
||||
|
||||
import android.text.TextUtils;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.LinearLayout;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.bumptech.glide.Glide;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.databinding.FoodBannerItemBinding;
|
||||
import com.ckkj.griddle.shop.entity.ShopBannerEntity;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商城顶部轮播适配器。
|
||||
*/
|
||||
public class ShopBannerAdapter extends RecyclerView.Adapter<ShopBannerAdapter.BannerViewHolder> {
|
||||
|
||||
private final List<ShopBannerEntity> items = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 提交接口返回的轮播商品列表。
|
||||
*/
|
||||
public void submitList(List<ShopBannerEntity> banners) {
|
||||
items.clear();
|
||||
if (banners != null) {
|
||||
items.addAll(banners);
|
||||
}
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public BannerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
FoodBannerItemBinding binding = FoodBannerItemBinding.inflate(
|
||||
LayoutInflater.from(parent.getContext()), parent, false);
|
||||
return new BannerViewHolder(binding);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull BannerViewHolder holder, int position) {
|
||||
holder.bind(items.get(position), position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return items.size();
|
||||
}
|
||||
|
||||
class BannerViewHolder extends RecyclerView.ViewHolder {
|
||||
private final FoodBannerItemBinding binding;
|
||||
|
||||
BannerViewHolder(FoodBannerItemBinding binding) {
|
||||
super(binding.getRoot());
|
||||
this.binding = binding;
|
||||
}
|
||||
|
||||
void bind(ShopBannerEntity item, int position) {
|
||||
// 接口只返回商品图、名称和价格,标题直接使用商品名称。
|
||||
String goodsName = item.getGoodsName();
|
||||
binding.tvFoodBannerTitle.setText(goodsName);
|
||||
binding.ivFoodBanner.setContentDescription(goodsName);
|
||||
|
||||
// 根据接口返回的积分价和现金价,组合出需要展示的价格文案。
|
||||
String priceText = getPriceText(item);
|
||||
binding.tvFoodBannerSubtitle.setText(priceText);
|
||||
binding.tvFoodBannerSubtitle.setVisibility(
|
||||
TextUtils.isEmpty(priceText) ? View.GONE : View.VISIBLE);
|
||||
|
||||
// 统一交给 Glide 加载,空地址也会替换旧请求,避免复用时显示上一件商品图。
|
||||
String goodsImg = item.getGoodsImg();
|
||||
Glide.with(binding.ivFoodBanner)
|
||||
.load(TextUtils.isEmpty(goodsImg) ? null : goodsImg.trim())
|
||||
.placeholder(R.drawable.food_cover_placeholder)
|
||||
.fallback(R.drawable.food_cover_placeholder)
|
||||
.error(R.drawable.food_cover_placeholder)
|
||||
.centerCrop()
|
||||
.into(binding.ivFoodBanner);
|
||||
bindIndicators(position);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据接口返回的价格字段生成展示文案。
|
||||
*/
|
||||
private String getPriceText(ShopBannerEntity item) {
|
||||
String pointPrice = formatPrice(item.getPointPrice());
|
||||
String cashPrice = formatPrice(item.getCashPrice());
|
||||
boolean hasPointPrice = !TextUtils.isEmpty(pointPrice);
|
||||
boolean hasCashPrice = !TextUtils.isEmpty(cashPrice);
|
||||
if (hasPointPrice && hasCashPrice) {
|
||||
return binding.getRoot().getContext().getString(
|
||||
R.string.food_banner_price_both,
|
||||
pointPrice,
|
||||
cashPrice);
|
||||
}
|
||||
if (hasPointPrice) {
|
||||
return binding.getRoot().getContext().getString(
|
||||
R.string.food_banner_point_price,
|
||||
pointPrice);
|
||||
}
|
||||
if (hasCashPrice) {
|
||||
return binding.getRoot().getContext().getString(
|
||||
R.string.food_banner_cash_price,
|
||||
cashPrice);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接解析接口价格字符串,去掉末尾多余的 0;空值或异常价格不展示。
|
||||
*/
|
||||
private String formatPrice(String price) {
|
||||
if (TextUtils.isEmpty(price)) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
BigDecimal value = new BigDecimal(price.trim());
|
||||
return value.signum() > 0 ? value.stripTrailingZeros().toPlainString() : "";
|
||||
} catch (NumberFormatException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 Banner 数量动态生成指示器,并高亮当前页。
|
||||
*/
|
||||
private void bindIndicators(int selectedPosition) {
|
||||
LinearLayout indicators = binding.llBannerIndicators;
|
||||
indicators.removeAllViews();
|
||||
int count = getItemCount();
|
||||
if (count <= 1) {
|
||||
indicators.setVisibility(View.GONE);
|
||||
return;
|
||||
}
|
||||
indicators.setVisibility(View.VISIBLE);
|
||||
for (int index = 0; index < count; index++) {
|
||||
View indicator = new View(indicators.getContext());
|
||||
int width = dp(indicators, index == selectedPosition ? 16 : 6);
|
||||
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, dp(indicators, 6));
|
||||
if (index > 0) {
|
||||
params.setMarginStart(dp(indicators, 6));
|
||||
}
|
||||
indicator.setLayoutParams(params);
|
||||
indicator.setBackgroundResource(index == selectedPosition
|
||||
? R.drawable.food_banner_indicator_active
|
||||
: R.drawable.food_banner_indicator_inactive);
|
||||
indicator.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
|
||||
indicators.addView(indicator);
|
||||
}
|
||||
}
|
||||
|
||||
private int dp(View view, int value) {
|
||||
return Math.round(value * view.getResources().getDisplayMetrics().density);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.ckkj.griddle.shop.adapter;
|
||||
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.ckkj.griddle.databinding.FoodCategoryItemBinding;
|
||||
import com.ckkj.griddle.shop.mvp.ShopContract;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商城美食分类适配器。
|
||||
*/
|
||||
public class ShopCategoryAdapter extends RecyclerView.Adapter<ShopCategoryAdapter.CategoryViewHolder> {
|
||||
|
||||
public interface OnCategorySelectedListener {
|
||||
void onCategorySelected(ShopContract.Category category);
|
||||
}
|
||||
|
||||
private final List<ShopContract.Category> items = new ArrayList<>();
|
||||
private final OnCategorySelectedListener listener;
|
||||
private int selectedPosition = RecyclerView.NO_POSITION;
|
||||
|
||||
public ShopCategoryAdapter(OnCategorySelectedListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
public void submitList(List<ShopContract.Category> categories) {
|
||||
items.clear();
|
||||
if (categories != null) {
|
||||
items.addAll(categories);
|
||||
}
|
||||
selectedPosition = items.isEmpty() ? RecyclerView.NO_POSITION : 0;
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
public void select(int position) {
|
||||
if (position < 0 || position >= items.size() || position == selectedPosition) {
|
||||
return;
|
||||
}
|
||||
int previousPosition = selectedPosition;
|
||||
selectedPosition = position;
|
||||
if (previousPosition != RecyclerView.NO_POSITION) {
|
||||
notifyItemChanged(previousPosition);
|
||||
}
|
||||
notifyItemChanged(selectedPosition);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
FoodCategoryItemBinding binding = FoodCategoryItemBinding.inflate(
|
||||
LayoutInflater.from(parent.getContext()), parent, false);
|
||||
return new CategoryViewHolder(binding);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull CategoryViewHolder holder, int position) {
|
||||
holder.bind(items.get(position), position == selectedPosition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return items.size();
|
||||
}
|
||||
|
||||
class CategoryViewHolder extends RecyclerView.ViewHolder {
|
||||
private final FoodCategoryItemBinding binding;
|
||||
|
||||
CategoryViewHolder(FoodCategoryItemBinding binding) {
|
||||
super(binding.getRoot());
|
||||
this.binding = binding;
|
||||
}
|
||||
|
||||
void bind(ShopContract.Category item, boolean selected) {
|
||||
binding.tvFoodCategory.setText(item.getTitleRes());
|
||||
binding.getRoot().setSelected(selected);
|
||||
binding.getRoot().setOnClickListener(view -> {
|
||||
int position = getBindingAdapterPosition();
|
||||
if (position == RecyclerView.NO_POSITION) {
|
||||
return;
|
||||
}
|
||||
select(position);
|
||||
if (listener != null) {
|
||||
listener.onCategorySelected(items.get(position));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.ckkj.griddle.shop.adapter;
|
||||
|
||||
import android.text.TextUtils;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.LayoutRes;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.bumptech.glide.Glide;
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.shop.mvp.ShopContract;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商城横向列表和推荐宫格共用的美食适配器。
|
||||
*/
|
||||
public class ShopFoodAdapter extends RecyclerView.Adapter<ShopFoodAdapter.FoodViewHolder> {
|
||||
|
||||
@LayoutRes
|
||||
private final int layoutResId;
|
||||
private final List<ShopContract.Food> items = new ArrayList<>();
|
||||
|
||||
public ShopFoodAdapter(@LayoutRes int layoutResId) {
|
||||
this.layoutResId = layoutResId;
|
||||
}
|
||||
|
||||
public void submitList(List<ShopContract.Food> foods) {
|
||||
items.clear();
|
||||
if (foods != null) {
|
||||
items.addAll(foods);
|
||||
}
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
View view = LayoutInflater.from(parent.getContext())
|
||||
.inflate(layoutResId, parent, false);
|
||||
return new FoodViewHolder(view);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull FoodViewHolder holder, int position) {
|
||||
holder.bind(items.get(position));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return items.size();
|
||||
}
|
||||
|
||||
static class FoodViewHolder extends RecyclerView.ViewHolder {
|
||||
private final ImageView cover;
|
||||
private final TextView name;
|
||||
|
||||
FoodViewHolder(View itemView) {
|
||||
super(itemView);
|
||||
cover = itemView.findViewById(R.id.iv_food_cover);
|
||||
name = itemView.findViewById(R.id.tv_food_name);
|
||||
}
|
||||
|
||||
void bind(ShopContract.Food item) {
|
||||
String title = itemView.getContext().getString(item.getTitleRes());
|
||||
name.setText(item.getTitleRes());
|
||||
cover.setContentDescription(title);
|
||||
if (!TextUtils.isEmpty(item.getImageUrl())) {
|
||||
Glide.with(cover)
|
||||
.load(item.getImageUrl())
|
||||
.placeholder(item.getImageRes())
|
||||
.error(item.getImageRes())
|
||||
.centerCrop()
|
||||
.into(cover);
|
||||
} else {
|
||||
cover.setImageResource(item.getImageRes());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.ckkj.griddle.shop.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 商城轮播商品实体,对应 Banner 接口返回的单个商品。
|
||||
*/
|
||||
public class ShopBannerEntity implements Serializable {
|
||||
|
||||
/**
|
||||
* 商品 ID,按接口字符串接收,保留完整编号。
|
||||
*/
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 商品名称,用作 Banner 标题。
|
||||
*/
|
||||
private String goodsName;
|
||||
|
||||
/**
|
||||
* 商品图片地址。
|
||||
*/
|
||||
private String goodsImg;
|
||||
|
||||
/**
|
||||
* 积分价格,接口以字符串返回。
|
||||
*/
|
||||
private String pointPrice;
|
||||
|
||||
/**
|
||||
* 现金价格,接口以字符串返回,避免浮点转换损失精度。
|
||||
*/
|
||||
private String cashPrice;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getGoodsName() {
|
||||
return goodsName;
|
||||
}
|
||||
|
||||
public void setGoodsName(String goodsName) {
|
||||
this.goodsName = goodsName;
|
||||
}
|
||||
|
||||
public String getGoodsImg() {
|
||||
return goodsImg;
|
||||
}
|
||||
|
||||
public void setGoodsImg(String goodsImg) {
|
||||
this.goodsImg = goodsImg;
|
||||
}
|
||||
|
||||
public String getPointPrice() {
|
||||
return pointPrice;
|
||||
}
|
||||
|
||||
public void setPointPrice(String pointPrice) {
|
||||
this.pointPrice = pointPrice;
|
||||
}
|
||||
|
||||
public String getCashPrice() {
|
||||
return cashPrice;
|
||||
}
|
||||
|
||||
public void setCashPrice(String cashPrice) {
|
||||
this.cashPrice = cashPrice;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ckkj.griddle.shop.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 商城商品分类实体,对应商品分类列表接口返回项。
|
||||
*/
|
||||
public class ShopCategoryEntity implements Serializable {
|
||||
|
||||
/**
|
||||
* 分类 ID,用于查询该分类下的商品。
|
||||
*/
|
||||
private long id;
|
||||
|
||||
/**
|
||||
* 分类名称。
|
||||
*/
|
||||
private String categoryName;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getCategoryName() {
|
||||
return categoryName;
|
||||
}
|
||||
|
||||
public void setCategoryName(String categoryName) {
|
||||
this.categoryName = categoryName;
|
||||
}
|
||||
}
|
||||
134
app/src/main/java/com/ckkj/griddle/shop/mvp/ShopContract.java
Normal file
134
app/src/main/java/com/ckkj/griddle/shop/mvp/ShopContract.java
Normal file
@@ -0,0 +1,134 @@
|
||||
package com.ckkj.griddle.shop.mvp;
|
||||
|
||||
import androidx.annotation.StringRes;
|
||||
|
||||
import com.ckkj.griddle.base.IView;
|
||||
import com.ckkj.griddle.shop.entity.ShopBannerEntity;
|
||||
import com.ckkj.griddle.shop.entity.ShopCategoryEntity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商城页面与数据层协议。
|
||||
*/
|
||||
public final class ShopContract {
|
||||
|
||||
private ShopContract() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据层统一结果回调。
|
||||
*/
|
||||
public interface CallBack<T> {
|
||||
void success(T data);
|
||||
|
||||
void fail(String message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 商城业务的数据层接口。
|
||||
*/
|
||||
public interface DataModel {
|
||||
/**
|
||||
* 获取商城顶部轮播商品。
|
||||
*/
|
||||
void getShopBanners(CallBack<List<ShopBannerEntity>> callback);
|
||||
|
||||
/**
|
||||
* 获取商城商品分类列表。
|
||||
*/
|
||||
void getShopCategories(CallBack<List<ShopCategoryEntity>> callback);
|
||||
|
||||
void loadContent(CallBack<ShopContent> callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* 商城页面需要实现的视图接口。
|
||||
*/
|
||||
public interface ShopView extends IView {
|
||||
/**
|
||||
* 轮播商品获取成功,将数据交给页面展示。
|
||||
*/
|
||||
void getShopBannersSuccess(List<ShopBannerEntity> banners);
|
||||
|
||||
/**
|
||||
* 商品分类获取成功。
|
||||
*/
|
||||
void getShopCategoriesSuccess(List<ShopCategoryEntity> categories);
|
||||
|
||||
void showShopContent(ShopContent content);
|
||||
}
|
||||
|
||||
public static final class ShopContent {
|
||||
private final List<Category> categories;
|
||||
private final List<Food> recommendations;
|
||||
|
||||
public ShopContent(List<Category> categories, List<Food> recommendations) {
|
||||
this.categories = immutableCopy(categories);
|
||||
this.recommendations = immutableCopy(recommendations);
|
||||
}
|
||||
|
||||
public List<Category> getCategories() {
|
||||
return categories;
|
||||
}
|
||||
|
||||
public List<Food> getRecommendations() {
|
||||
return recommendations;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Category {
|
||||
@StringRes
|
||||
private final int titleRes;
|
||||
private final List<Food> foods;
|
||||
|
||||
public Category(@StringRes int titleRes, List<Food> foods) {
|
||||
this.titleRes = titleRes;
|
||||
this.foods = immutableCopy(foods);
|
||||
}
|
||||
|
||||
@StringRes
|
||||
public int getTitleRes() {
|
||||
return titleRes;
|
||||
}
|
||||
|
||||
public List<Food> getFoods() {
|
||||
return foods;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Food {
|
||||
@StringRes
|
||||
private final int titleRes;
|
||||
private final String imageUrl;
|
||||
private final int imageRes;
|
||||
|
||||
public Food(@StringRes int titleRes, String imageUrl, int imageRes) {
|
||||
this.titleRes = titleRes;
|
||||
this.imageUrl = imageUrl;
|
||||
this.imageRes = imageRes;
|
||||
}
|
||||
|
||||
@StringRes
|
||||
public int getTitleRes() {
|
||||
return titleRes;
|
||||
}
|
||||
|
||||
public String getImageUrl() {
|
||||
return imageUrl;
|
||||
}
|
||||
|
||||
public int getImageRes() {
|
||||
return imageRes;
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> List<T> immutableCopy(List<T> source) {
|
||||
if (source == null || source.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return Collections.unmodifiableList(new ArrayList<>(source));
|
||||
}
|
||||
}
|
||||
149
app/src/main/java/com/ckkj/griddle/shop/mvp/ShopImpl.java
Normal file
149
app/src/main/java/com/ckkj/griddle/shop/mvp/ShopImpl.java
Normal file
@@ -0,0 +1,149 @@
|
||||
package com.ckkj.griddle.shop.mvp;
|
||||
|
||||
import com.ckkj.griddle.R;
|
||||
import com.ckkj.griddle.network.BaseBean;
|
||||
import com.ckkj.griddle.network.NetWorkManager;
|
||||
import com.ckkj.griddle.shop.entity.ShopBannerEntity;
|
||||
import com.ckkj.griddle.shop.entity.ShopCategoryEntity;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import io.reactivex.Observer;
|
||||
import io.reactivex.android.schedulers.AndroidSchedulers;
|
||||
import io.reactivex.annotations.NonNull;
|
||||
import io.reactivex.disposables.Disposable;
|
||||
import io.reactivex.schedulers.Schedulers;
|
||||
|
||||
/**
|
||||
* 商城页面数据实现。
|
||||
*/
|
||||
public class ShopImpl implements ShopContract.DataModel {
|
||||
|
||||
/**
|
||||
* 请求商城轮播商品,并将接口结果转换为页面可直接使用的列表。
|
||||
*/
|
||||
@Override
|
||||
public void getShopBanners(ShopContract.CallBack<List<ShopBannerEntity>> callback) {
|
||||
try {
|
||||
// 网络请求运行在 IO 线程,响应结果切回主线程后再通知页面更新。
|
||||
NetWorkManager.getRequest().getShopBanners(NetWorkManager.getToken())
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean<List<ShopBannerEntity>>>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean<List<ShopBannerEntity>> bean) {
|
||||
// Banner 实际接口使用 200,兼容项目原有的成功码判断。
|
||||
if (bean != null && (bean.getCode() == 200 || bean.isSuccess())) {
|
||||
// 接口未返回数据时统一转成空列表,页面无需重复判空。
|
||||
List<ShopBannerEntity> banners = bean.getData();
|
||||
callback.success(banners == null
|
||||
? Collections.emptyList()
|
||||
: banners);
|
||||
} else {
|
||||
callback.fail(bean == null ? "轮播图获取失败" : bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callback.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
callback.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求商城商品分类列表。
|
||||
*/
|
||||
@Override
|
||||
public void getShopCategories(ShopContract.CallBack<List<ShopCategoryEntity>> callback) {
|
||||
try {
|
||||
// 网络请求运行在 IO 线程,响应结果切回主线程后再通知页面。
|
||||
NetWorkManager.getRequest().getShopCategories(NetWorkManager.getToken())
|
||||
.subscribeOn(Schedulers.io())
|
||||
.unsubscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(new Observer<BaseBean<List<ShopCategoryEntity>>>() {
|
||||
@Override
|
||||
public void onSubscribe(@NonNull Disposable d) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNext(@NonNull BaseBean<List<ShopCategoryEntity>> bean) {
|
||||
if (bean != null && bean.isSuccess()) {
|
||||
// 分类接口未返回数据时统一转成空列表。
|
||||
List<ShopCategoryEntity> categories = bean.getData();
|
||||
callback.success(categories == null
|
||||
? Collections.emptyList()
|
||||
: categories);
|
||||
} else {
|
||||
callback.fail(bean == null ? "商品分类获取失败" : bean.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull Throwable e) {
|
||||
callback.fail(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
callback.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadContent(ShopContract.CallBack<ShopContract.ShopContent> callback) {
|
||||
List<ShopContract.Category> categories = Arrays.asList(
|
||||
category(R.string.food_category_breakfast,
|
||||
food(R.string.food_item_injera_firfir),
|
||||
food(R.string.food_item_chechebsa),
|
||||
food(R.string.food_item_firfir)),
|
||||
category(R.string.food_category_main_dishes,
|
||||
food(R.string.food_item_doro_wat),
|
||||
food(R.string.food_item_kitfo),
|
||||
food(R.string.food_item_tibs)),
|
||||
category(R.string.food_category_drinks,
|
||||
food(R.string.food_item_ethiopian_coffee),
|
||||
food(R.string.food_item_spiced_tea)),
|
||||
category(R.string.food_category_snack,
|
||||
food(R.string.food_item_sambusa),
|
||||
food(R.string.food_item_kolo))
|
||||
);
|
||||
|
||||
List<ShopContract.Food> recommendations = Arrays.asList(
|
||||
food(R.string.food_item_doro_wat),
|
||||
food(R.string.food_item_kitfo),
|
||||
food(R.string.food_item_beyaynetu),
|
||||
food(R.string.food_item_shiro)
|
||||
);
|
||||
|
||||
callback.success(new ShopContract.ShopContent(categories, recommendations));
|
||||
}
|
||||
|
||||
private ShopContract.Category category(int titleRes, ShopContract.Food... foods) {
|
||||
return new ShopContract.Category(titleRes, Arrays.asList(foods));
|
||||
}
|
||||
|
||||
private ShopContract.Food food(int titleRes) {
|
||||
return new ShopContract.Food(titleRes, null, R.drawable.food_cover_placeholder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.ckkj.griddle.shop.mvp;
|
||||
|
||||
import com.ckkj.griddle.base.BasePresenter;
|
||||
import com.ckkj.griddle.shop.entity.ShopBannerEntity;
|
||||
import com.ckkj.griddle.shop.entity.ShopCategoryEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商城页面业务协调层。
|
||||
*/
|
||||
public class ShopPresenter extends BasePresenter<ShopContract.ShopView> {
|
||||
|
||||
private final ShopImpl mImpl;
|
||||
|
||||
public ShopPresenter(ShopImpl mImpl) {
|
||||
this.mImpl = mImpl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取商城顶部轮播数据,并将结果转发给页面。
|
||||
*/
|
||||
public void getShopBanners() {
|
||||
mImpl.getShopBanners(new ShopContract.CallBack<List<ShopBannerEntity>>() {
|
||||
@Override
|
||||
public void success(List<ShopBannerEntity> data) {
|
||||
if (getView() != null) {
|
||||
getView().getShopBannersSuccess(data);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String message) {
|
||||
if (getView() != null) {
|
||||
getView().showError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取商城商品分类列表,并将结果转发给页面。
|
||||
*/
|
||||
public void getShopCategories() {
|
||||
mImpl.getShopCategories(new ShopContract.CallBack<List<ShopCategoryEntity>>() {
|
||||
@Override
|
||||
public void success(List<ShopCategoryEntity> data) {
|
||||
if (getView() != null) {
|
||||
getView().getShopCategoriesSuccess(data);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String message) {
|
||||
if (getView() != null) {
|
||||
getView().showError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void loadContent() {
|
||||
mImpl.loadContent(new ShopContract.CallBack<ShopContract.ShopContent>() {
|
||||
@Override
|
||||
public void success(ShopContract.ShopContent data) {
|
||||
if (getView() != null) {
|
||||
getView().showShopContent(data);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fail(String message) {
|
||||
if (getView() != null) {
|
||||
getView().showError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<set xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<scale
|
||||
android:fromXScale="1"
|
||||
android:toXScale="1.5"
|
||||
android:fromYScale="1"
|
||||
android:toYScale="1.5"
|
||||
android:pivotX="50%"
|
||||
android:pivotY="50%"
|
||||
android:duration="200"
|
||||
android:interpolator="@android:interpolator/accelerate_decelerate"/>
|
||||
<alpha
|
||||
android:fromAlpha="1"
|
||||
android:toAlpha="0"
|
||||
android:duration="200"/>
|
||||
</set>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="@mipmap/icon_talk_select" android:state_checked="true" />
|
||||
<item android:drawable="@mipmap/icon_talk_unselect"/>
|
||||
</selector>
|
||||
7
app/src/main/res/drawable/bottom_shop_select.xml
Normal file
7
app/src/main/res/drawable/bottom_shop_select.xml
Normal file
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item
|
||||
android:drawable="@drawable/ic_bottom_shop_selected"
|
||||
android:state_checked="true" />
|
||||
<item android:drawable="@drawable/ic_bottom_shop_unselected" />
|
||||
</selector>
|
||||
25
app/src/main/res/drawable/food_cover_placeholder.xml
Normal file
25
app/src/main/res/drawable/food_cover_placeholder.xml
Normal file
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="72dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="72">
|
||||
<path
|
||||
android:fillColor="#FFF3E8"
|
||||
android:pathData="M0,0h108v72h-108z" />
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M54,14a23,23 0,1 0,0,46a23,23 0,1 0,0,-46" />
|
||||
<path
|
||||
android:fillColor="#FFD7B8"
|
||||
android:pathData="M54,19a18,18 0,1 0,0,36a18,18 0,1 0,0,-36" />
|
||||
<path
|
||||
android:fillColor="#FF8A3D"
|
||||
android:pathData="M43,34c5,-5 17,-5 22,0c-3,8 -19,8 -22,0" />
|
||||
<path
|
||||
android:fillColor="#FF6900"
|
||||
android:pathData="M25,28h2v8h2v-8h2v8h2v-8h2v10c0,4 -3,7 -6,7v12h-4v-12c-3,0 -6,-3 -6,-7v-10h2v8h2v-8h2z" />
|
||||
<path
|
||||
android:fillColor="#FF6900"
|
||||
android:pathData="M82,25c4,0 7,4 7,9c0,4 -2,7 -5,8v15h-4v-15c-3,-1 -5,-4 -5,-8c0,-5 3,-9 7,-9z" />
|
||||
</vector>
|
||||
10
app/src/main/res/drawable/ic_bottom_shop_selected.xml
Normal file
10
app/src/main/res/drawable/ic_bottom_shop_selected.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="@color/device_home_orange"
|
||||
android:pathData="M18,6h-2C16,3.79 14.21,2 12,2S8,3.79 8,6H6C4.9,6 4,6.9 4,8v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2V8c0,-1.1 -0.9,-2 -2,-2zM12,4c1.1,0 2,0.9 2,2h-4c0,-1.1 0.9,-2 2,-2zM18,20H6V8h2v2h2V8h4v2h2V8h2v12z" />
|
||||
</vector>
|
||||
10
app/src/main/res/drawable/ic_bottom_shop_unselected.xml
Normal file
10
app/src/main/res/drawable/ic_bottom_shop_unselected.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#98A2B3"
|
||||
android:pathData="M18,6h-2C16,3.79 14.21,2 12,2S8,3.79 8,6H6C4.9,6 4,6.9 4,8v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2V8c0,-1.1 -0.9,-2 -2,-2zM12,4c1.1,0 2,0.9 2,2h-4c0,-1.1 0.9,-2 2,-2zM18,20H6V8h2v2h2V8h4v2h2V8h2v12z" />
|
||||
</vector>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<solid android:color="@color/color_F7F9FA"/>
|
||||
<corners android:radius="@dimen/dp_10"/>
|
||||
</shape>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<solid android:color="@color/color_F0F6FF"/>
|
||||
<corners android:radius="@dimen/dp_15"/>
|
||||
</shape>
|
||||
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<corners android:radius="@dimen/dp_10"/>
|
||||
<solid android:color="@color/white"/>
|
||||
<stroke android:color="@color/color_C1CFE6" android:width="1px"/>
|
||||
</shape>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<solid android:color="@color/color_FAEFFF"/>
|
||||
<corners android:radius="@dimen/dp_8"/>
|
||||
</shape>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<solid android:color="@color/color_F8F9FA"/>
|
||||
<corners android:radius="@dimen/dp_20"/>
|
||||
</shape>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<corners android:radius="@dimen/dp_18"/>
|
||||
<solid android:color="@color/color_zhu"/>
|
||||
</shape>
|
||||
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<corners android:radius="@dimen/dp_18"/>
|
||||
<solid android:color="@color/color_F0F6FF"/>
|
||||
<stroke android:color="@color/color_D1DCEE" android:width="@dimen/dp_1"/>
|
||||
</shape>
|
||||
@@ -1,5 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<solid android:color="@color/color_E5F2FB"/>
|
||||
<corners android:radius="15dp"/>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
|
||||
<solid android:color="@color/wifi_setup_accent" />
|
||||
</shape>
|
||||
9
app/src/main/res/drawable/wifi_setup_button_bg.xml
Normal file
9
app/src/main/res/drawable/wifi_setup_button_bg.xml
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="#26FFFFFF">
|
||||
<item>
|
||||
<shape android:shape="rectangle">
|
||||
<solid android:color="@color/wifi_setup_accent" />
|
||||
<corners android:radius="12dp" />
|
||||
</shape>
|
||||
</item>
|
||||
</ripple>
|
||||
5
app/src/main/res/drawable/wifi_setup_selected_bg.xml
Normal file
5
app/src/main/res/drawable/wifi_setup_selected_bg.xml
Normal file
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<solid android:color="#FFF3EA" />
|
||||
<corners android:radius="8dp" />
|
||||
</shape>
|
||||
@@ -83,6 +83,36 @@
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="30dp"
|
||||
android:layout_marginEnd="29dp"
|
||||
android:layout_marginBottom="12dp"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/scan_progress"
|
||||
style="?android:attr/progressBarStyleSmall"
|
||||
android:layout_width="16dp"
|
||||
android:layout_height="16dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
android:indeterminateTint="@color/device_home_orange"
|
||||
android:visibility="gone" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_scan_status"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:accessibilityLiveRegion="polite"
|
||||
android:text="@string/bl_device_searching"
|
||||
android:textColor="#9AA0A6"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_devices"
|
||||
android:layout_width="match_parent"
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
android:maxLines="1"
|
||||
android:textColor="#9AA0A6"
|
||||
android:textSize="11sp"
|
||||
tools:text="SN-20260110001" />
|
||||
tools:text="MAC: 20:D5:C2:42:F1:60" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Bind the signal text, background and text color together in the adapter. -->
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:orientation="vertical"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/shape_chat_ques_detail_bg"
|
||||
android:paddingHorizontal="@dimen/dp_9"
|
||||
android:paddingVertical="@dimen/dp_8">
|
||||
<TextView
|
||||
android:id="@+id/tv_title"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textStyle="bold"
|
||||
android:textSize="11sp"
|
||||
android:textColor="@color/color_zhu"
|
||||
android:text="命理入门"/>
|
||||
<TextView
|
||||
android:id="@+id/tv_content"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="@dimen/dp_5"
|
||||
android:singleLine="true"
|
||||
android:ellipsize="end"
|
||||
android:textSize="10sp"
|
||||
android:textColor="@color/color_7A8699"
|
||||
android:text="命理入门"/>
|
||||
</LinearLayout>
|
||||
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:orientation="vertical"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_horizontal"
|
||||
android:layout_marginHorizontal="@dimen/dp_3">
|
||||
<TextView
|
||||
android:id="@+id/tv_content"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingHorizontal="@dimen/dp_10"
|
||||
android:paddingVertical="@dimen/dp_5"
|
||||
android:textSize="10sp"
|
||||
android:textColor="@color/color_zhu"
|
||||
android:textStyle="bold"
|
||||
android:text="专项咨询"/>
|
||||
</LinearLayout>
|
||||
@@ -4,7 +4,7 @@
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/device_home_background"
|
||||
android:background="@color/white"
|
||||
android:clipChildren="false"
|
||||
android:clipToPadding="false"
|
||||
android:orientation="vertical"
|
||||
@@ -37,66 +37,22 @@
|
||||
android:textSize="25sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<androidx.cardview.widget.CardView
|
||||
android:id="@+id/cv_notifications"
|
||||
android:layout_width="38dp"
|
||||
android:layout_height="38dp"
|
||||
android:clickable="true"
|
||||
android:contentDescription="@string/device_home_notifications"
|
||||
android:focusable="true"
|
||||
android:foreground="?attr/selectableItemBackground"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="19dp"
|
||||
app:cardElevation="4dp"
|
||||
app:cardPreventCornerOverlap="false">
|
||||
|
||||
<FrameLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/iv_notifications"
|
||||
android:layout_width="20dp"
|
||||
android:layout_height="20dp"
|
||||
android:layout_gravity="center"
|
||||
android:contentDescription="@null"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
|
||||
<View
|
||||
android:id="@+id/view_notification_dot"
|
||||
android:layout_width="7dp"
|
||||
android:layout_height="7dp"
|
||||
android:layout_gravity="top|end"
|
||||
android:layout_marginTop="7dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
android:background="@drawable/device_home_notification_dot"
|
||||
android:visibility="gone"
|
||||
tools:visibility="visible" />
|
||||
</FrameLayout>
|
||||
</androidx.cardview.widget.CardView>
|
||||
|
||||
<androidx.cardview.widget.CardView
|
||||
android:id="@+id/cv_add_device"
|
||||
android:layout_width="38dp"
|
||||
android:layout_height="38dp"
|
||||
android:layout_marginStart="10dp"
|
||||
android:clickable="true"
|
||||
android:contentDescription="@string/device_home_add_device"
|
||||
android:focusable="true"
|
||||
android:foreground="?attr/selectableItemBackground"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="19dp"
|
||||
app:cardElevation="4dp"
|
||||
app:cardPreventCornerOverlap="false">
|
||||
android:layout_gravity="center"
|
||||
android:contentDescription="@null"
|
||||
android:src="@mipmap/icon_notice" />
|
||||
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/iv_add_device"
|
||||
android:layout_width="20dp"
|
||||
android:layout_height="20dp"
|
||||
android:layout_width="38dp"
|
||||
android:layout_height="38dp"
|
||||
android:layout_gravity="center"
|
||||
android:contentDescription="@null"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
</androidx.cardview.widget.CardView>
|
||||
android:src="@mipmap/icon_top_right_add" />
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.cardview.widget.CardView
|
||||
@@ -131,8 +87,7 @@
|
||||
android:layout_height="38dp"
|
||||
android:background="@drawable/device_home_stat_icon_bg"
|
||||
android:contentDescription="@null"
|
||||
android:padding="9dp"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
android:src="@mipmap/icon_charcoal" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_charcoal_saved"
|
||||
@@ -172,8 +127,7 @@
|
||||
android:layout_height="44dp"
|
||||
android:background="@drawable/device_home_stat_icon_bg"
|
||||
android:contentDescription="@null"
|
||||
android:padding="11dp"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
android:src="@mipmap/icon_balance" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_balance"
|
||||
@@ -213,8 +167,7 @@
|
||||
android:layout_height="38dp"
|
||||
android:background="@drawable/device_home_stat_icon_bg"
|
||||
android:contentDescription="@null"
|
||||
android:padding="9dp"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
android:src="@mipmap/icon_birr" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_saving_birr"
|
||||
@@ -284,13 +237,13 @@
|
||||
<androidx.cardview.widget.CardView
|
||||
android:id="@+id/cv_empty_devices"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="239dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginHorizontal="5dp"
|
||||
android:layout_marginTop="20dp"
|
||||
android:layout_marginBottom="12dp"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="16dp"
|
||||
app:cardElevation="1dp"
|
||||
app:cardElevation="3dp"
|
||||
app:cardPreventCornerOverlap="false">
|
||||
|
||||
<LinearLayout
|
||||
@@ -299,23 +252,13 @@
|
||||
android:gravity="center_horizontal"
|
||||
android:orientation="vertical"
|
||||
android:paddingTop="34dp">
|
||||
|
||||
<androidx.cardview.widget.CardView
|
||||
android:layout_width="64dp"
|
||||
android:layout_height="64dp"
|
||||
app:cardBackgroundColor="#FFF3EA"
|
||||
app:cardCornerRadius="32dp"
|
||||
app:cardElevation="0dp"
|
||||
app:cardPreventCornerOverlap="false">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/iv_empty_devices"
|
||||
android:layout_width="26dp"
|
||||
android:layout_height="26dp"
|
||||
android:layout_width="65dp"
|
||||
android:layout_height="65dp"
|
||||
android:layout_gravity="center"
|
||||
android:contentDescription="@null"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
</androidx.cardview.widget.CardView>
|
||||
android:src="@mipmap/icon_add_device" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_empty_devices"
|
||||
|
||||
205
app/src/main/res/layout/device_wifi_connect.xml
Normal file
205
app/src/main/res/layout/device_wifi_connect.xml
Normal file
@@ -0,0 +1,205 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.core.widget.NestedScrollView 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:background="@android:color/white"
|
||||
android:fitsSystemWindows="true"
|
||||
android:fillViewport="true"
|
||||
android:scrollbars="none"
|
||||
tools:locale="en">
|
||||
|
||||
<!-- 系统状态栏与导航栏由窗口绘制,小屏或大字体时允许内容滚动。 -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingTop="16dp"
|
||||
android:paddingBottom="24dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_title"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp"
|
||||
android:gravity="center"
|
||||
android:text="@string/wifi_setup_title"
|
||||
android:textColor="#252529"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<!-- 浅橙色底环 + 橙色圆头进度弧,避免默认控件样式影响设计效果。 -->
|
||||
<com.ckkj.griddle.custom.view.ProvisionProgressView
|
||||
android:id="@+id/provision_progress"
|
||||
android:layout_width="110dp"
|
||||
android:layout_height="110dp"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginTop="24dp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_provision_stage"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
android:layout_marginHorizontal="29dp"
|
||||
android:gravity="center"
|
||||
android:minHeight="21dp"
|
||||
android:accessibilityLiveRegion="polite"
|
||||
android:text="@string/wifi_connect_connecting"
|
||||
android:textColor="@color/wifi_setup_text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:layout_marginHorizontal="38dp"
|
||||
android:minHeight="30dp"
|
||||
android:text="@string/wifi_connect_keep_nearby"
|
||||
android:textColor="#C4C9D0"
|
||||
android:textSize="10sp" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="28dp"
|
||||
android:layout_marginStart="29dp"
|
||||
android:layout_marginEnd="26dp"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:minHeight="44dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<ImageView
|
||||
android:layout_width="32dp"
|
||||
android:layout_height="32dp"
|
||||
android:background="@drawable/wifi_connect_step_bg"
|
||||
android:backgroundTint="#22A45D"
|
||||
android:contentDescription="@null"
|
||||
android:padding="9dp"
|
||||
android:src="@drawable/ef_ic_done_white" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:layout_marginStart="12dp"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
style="@style/WifiConnectStepTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/wifi_connect_bluetooth_title" />
|
||||
|
||||
<TextView
|
||||
style="@style/WifiConnectStepDescription"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="@string/wifi_connect_bluetooth_description" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:minHeight="44dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_transfer_step"
|
||||
style="@style/WifiConnectStepNumber"
|
||||
android:layout_width="32dp"
|
||||
android:layout_height="32dp"
|
||||
android:backgroundTint="@color/wifi_setup_accent"
|
||||
android:text="2"
|
||||
android:textColor="@android:color/white" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:layout_marginStart="12dp"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
style="@style/WifiConnectStepTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/wifi_connect_transfer_title" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_transfer_description"
|
||||
style="@style/WifiConnectStepDescription"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="@string/wifi_connect_transfer_description" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="11dp"
|
||||
android:minHeight="60dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_network_step"
|
||||
style="@style/WifiConnectStepNumber"
|
||||
android:layout_width="32dp"
|
||||
android:layout_height="32dp"
|
||||
android:backgroundTint="#F5F6F8"
|
||||
android:text="3"
|
||||
android:textColor="@color/wifi_setup_secondary_text" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:layout_marginStart="12dp"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_network_title"
|
||||
style="@style/WifiConnectStepTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/wifi_connect_network_title"
|
||||
android:textColor="@color/wifi_setup_secondary_text" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_network_description"
|
||||
style="@style/WifiConnectStepDescription"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="3dp"
|
||||
android:text="@string/wifi_connect_network_description" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_cancel_setup"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginTop="14dp"
|
||||
android:background="?attr/selectableItemBackground"
|
||||
android:clickable="true"
|
||||
android:focusable="true"
|
||||
android:gravity="center"
|
||||
android:text="@string/wifi_connect_cancel"
|
||||
android:textColor="@color/wifi_setup_secondary_text"
|
||||
android:textSize="14sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</androidx.core.widget.NestedScrollView>
|
||||
@@ -13,7 +13,7 @@
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:scaleType="centerCrop"
|
||||
android:src="@mipmap/ic_launcher"
|
||||
android:src="@drawable/food_cover_placeholder"
|
||||
android:contentDescription="@null" />
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
@@ -27,7 +27,7 @@
|
||||
android:orientation="vertical"
|
||||
android:paddingHorizontal="16dp"
|
||||
android:paddingBottom="14dp">
|
||||
<!-- The adapter marks the current page; page count is supplied by banner data. -->
|
||||
<!-- 指示器由适配器根据 Banner 数量和当前页动态生成。 -->
|
||||
<LinearLayout
|
||||
android:id="@+id/ll_banner_indicators"
|
||||
android:layout_width="match_parent"
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:scaleType="centerCrop"
|
||||
android:src="@mipmap/ic_launcher"
|
||||
android:src="@drawable/food_cover_placeholder"
|
||||
android:contentDescription="@null" />
|
||||
</androidx.cardview.widget.CardView>
|
||||
<TextView
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:scaleType="centerCrop"
|
||||
android:src="@mipmap/ic_launcher"
|
||||
android:src="@drawable/food_cover_placeholder"
|
||||
android:contentDescription="@null" />
|
||||
</androidx.cardview.widget.CardView>
|
||||
<TextView
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:orientation="horizontal"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/shape_history_item_bg"
|
||||
android:layout_marginBottom="@dimen/dp_12">
|
||||
<ImageView
|
||||
android:id="@+id/img_logo"
|
||||
android:layout_width="@dimen/dp_32"
|
||||
android:layout_height="@dimen/dp_32"
|
||||
android:layout_marginLeft="@dimen/dp_10"
|
||||
android:layout_gravity="center_vertical"
|
||||
android:src="@mipmap/ic_launcher"/>
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical"
|
||||
android:layout_marginHorizontal="@dimen/dp_10"
|
||||
android:layout_marginVertical="@dimen/dp_10">
|
||||
<TextView
|
||||
android:id="@+id/tv_type_content"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginVertical="5dp"
|
||||
android:textSize="14sp"
|
||||
android:textColor="@color/color_666666"
|
||||
android:text="帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格帮我看看我的命格"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="2"/>
|
||||
<TextView
|
||||
android:id="@+id/tv_time"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_alignParentRight="true"
|
||||
android:textSize="12sp"
|
||||
android:textColor="@color/color_ff999999"
|
||||
android:text="7月 11日"/>
|
||||
</LinearLayout>
|
||||
<RelativeLayout
|
||||
android:layout_width="@dimen/dp_30"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center_vertical">
|
||||
<TextView
|
||||
android:id="@+id/tv_type_name"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingHorizontal="@dimen/dp_8"
|
||||
android:paddingVertical="@dimen/dp_2"
|
||||
android:gravity="center"
|
||||
android:textSize="10sp"
|
||||
android:textColor="@color/color_319EF4"
|
||||
android:text=""
|
||||
android:background="@drawable/shape_history_type_bzml_bg"
|
||||
android:visibility="gone"/>
|
||||
<ImageView
|
||||
android:id="@+id/img_delete"
|
||||
android:layout_width="@dimen/dp_15"
|
||||
android:layout_height="@dimen/dp_15"
|
||||
android:layout_alignParentRight="true"
|
||||
android:src="@mipmap/icon_delete"/>
|
||||
</RelativeLayout>
|
||||
</LinearLayout>
|
||||
@@ -1,17 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content">
|
||||
<TextView
|
||||
android:id="@+id/tv_quick_ask_name"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="@dimen/dp_15"
|
||||
android:layout_marginHorizontal="@dimen/dp_40"
|
||||
android:padding="@dimen/dp_10"
|
||||
android:textSize="13sp"
|
||||
android:textColor="@color/color_zhu"
|
||||
android:text=""
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:background="@drawable/shape_gray1_radus10_bg"/>
|
||||
</RelativeLayout>
|
||||
@@ -1,54 +0,0 @@
|
||||
<?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:orientation="vertical"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/white">
|
||||
<RelativeLayout
|
||||
android:id="@+id/rl_title"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp">
|
||||
<include
|
||||
android:id="@+id/included_title"
|
||||
layout="@layout/include_activity_back_layout"/>
|
||||
</RelativeLayout>
|
||||
<com.scwang.smart.refresh.layout.SmartRefreshLayout
|
||||
android:id="@+id/refresh"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginHorizontal="@dimen/dp_12">
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:layout_marginTop="@dimen/dp_12">
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_data"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
tools:listitem="@layout/history_item_layout"
|
||||
tools:itemCount="2"
|
||||
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
|
||||
<RelativeLayout
|
||||
android:id="@+id/rel_no_more"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:visibility="gone" >
|
||||
<include
|
||||
android:id="@+id/lay_no_more"
|
||||
layout="@layout/layout_no_more"/>
|
||||
</RelativeLayout>
|
||||
</LinearLayout>
|
||||
</com.scwang.smart.refresh.layout.SmartRefreshLayout>
|
||||
<RelativeLayout
|
||||
android:id="@+id/rel_noresult"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:visibility="gone">
|
||||
<include
|
||||
android:id="@+id/included_noresult"
|
||||
layout="@layout/include_no_result_layout"/>
|
||||
</RelativeLayout>
|
||||
</LinearLayout>
|
||||
@@ -1,17 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginHorizontal="5dp">
|
||||
<TextView
|
||||
android:id="@+id/tv_option_name"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center"
|
||||
android:textSize="10sp"
|
||||
android:textColor="@color/color_zhu"
|
||||
android:text=""
|
||||
android:paddingVertical="@dimen/dp_5"
|
||||
android:paddingHorizontal="@dimen/dp_10"
|
||||
android:background="@drawable/shape_index_option_un_selected"/>
|
||||
</RelativeLayout>
|
||||
@@ -1,17 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingVertical="@dimen/dp_5"
|
||||
android:layout_marginHorizontal="5dp">
|
||||
<TextView
|
||||
android:id="@+id/tv_quick_ask_name"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textSize="12sp"
|
||||
android:textColor="@color/color_319EF4"
|
||||
android:text=""
|
||||
android:paddingVertical="@dimen/dp_5"
|
||||
android:paddingHorizontal="@dimen/dp_12"
|
||||
android:background="@drawable/shape_index_quick_ask_bg"/>
|
||||
</RelativeLayout>
|
||||
@@ -1,328 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<RelativeLayout 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:background="@color/white"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_above="@+id/ll_bottom"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingTop="@dimen/dp_5"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingHorizontal="@dimen/dp_15">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="3"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/img_title_icon"
|
||||
android:layout_width="@dimen/dp_30"
|
||||
android:layout_height="@dimen/dp_30"
|
||||
android:src="@mipmap/icon_loading_taiji" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginLeft="@dimen/dp_5"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="星语明灯"
|
||||
android:textColor="@color/color_zhu"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_title_expert"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text=""
|
||||
android:textColor="@color/color_666666"
|
||||
android:textSize="10sp"
|
||||
android:visibility="gone"/>
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="3"
|
||||
android:gravity="center"
|
||||
android:text="明灯小助手"
|
||||
android:textColor="@color/color_333333"
|
||||
android:textSize="17sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="3"
|
||||
android:gravity="center_vertical|right"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/img_history"
|
||||
android:layout_width="@dimen/dp_20"
|
||||
android:layout_height="@dimen/dp_20"
|
||||
android:src="@mipmap/icon_index_history" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/img_refresh"
|
||||
android:layout_width="@dimen/dp_20"
|
||||
android:layout_height="@dimen/dp_20"
|
||||
android:layout_marginLeft="@dimen/dp_20"
|
||||
android:src="@mipmap/icon_index_refresh" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_options"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="@dimen/dp_16"
|
||||
android:layout_marginBottom="@dimen/dp_10"
|
||||
android:orientation="horizontal"
|
||||
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
|
||||
tools:listitem="@layout/index_home_option_item"
|
||||
android:visibility="gone"/>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1px"
|
||||
android:layout_marginTop="@dimen/dp_5"
|
||||
android:background="@color/color_DDE6F5" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/linear_option_hint"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="@dimen/dp_5"
|
||||
android:orientation="vertical"
|
||||
android:visibility="gone">
|
||||
|
||||
<com.makeramen.roundedimageview.RoundedImageView
|
||||
android:id="@+id/img_select_option"
|
||||
android:layout_width="@dimen/dp_70"
|
||||
android:layout_height="@dimen/dp_70"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginTop="@dimen/dp_10"
|
||||
android:src="@mipmap/icon_loading_taiji" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_select_option"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginTop="@dimen/dp_5"
|
||||
android:text="玄机大师"
|
||||
android:textColor="@color/color_zhu"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_select_option_lable"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginTop="@dimen/dp_5"
|
||||
android:text=""
|
||||
android:textColor="@color/color_666666"
|
||||
android:textSize="12sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_select_option_slogan"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginTop="@dimen/dp_5"
|
||||
android:text="精通四柱八字、十神分析、大运流年"
|
||||
android:textColor="@color/color_zhu"
|
||||
android:textSize="12sp" />
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_enter_hint"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- 将聊天区域改为NestedScrollView嵌套RecyclerView -->
|
||||
<androidx.core.widget.NestedScrollView
|
||||
android:id="@+id/nested_scroll_chat"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:fillViewport="true"
|
||||
android:scrollbars="none">
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_chat"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:nestedScrollingEnabled="false"
|
||||
android:overScrollMode="never" />
|
||||
|
||||
</androidx.core.widget.NestedScrollView>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/ll_bottom"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_alignParentBottom="true"
|
||||
android:orientation="vertical">
|
||||
<FrameLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content">
|
||||
<androidx.cardview.widget.CardView
|
||||
android:id="@+id/card_question"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginHorizontal="@dimen/dp_13"
|
||||
android:layout_marginTop="@dimen/dp_5"
|
||||
android:layout_marginBottom="@dimen/dp_5"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="10dp"
|
||||
app:cardElevation="4dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_horizontal"
|
||||
android:orientation="vertical"
|
||||
android:paddingHorizontal="@dimen/dp_10"
|
||||
android:paddingBottom="@dimen/dp_10"
|
||||
android:layout_gravity="center_horizontal">
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_chat_type"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="@dimen/dp_10"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:orientation="horizontal"
|
||||
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
|
||||
tools:listitem="@layout/index_home_option_item"/>
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_chat_quick"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="@dimen/dp_10"
|
||||
android:orientation="horizontal" />
|
||||
</LinearLayout>
|
||||
</androidx.cardview.widget.CardView>
|
||||
|
||||
</FrameLayout>
|
||||
|
||||
<RelativeLayout
|
||||
android:id="@+id/rl_quick_ask"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@color/color_F7F9FA"
|
||||
android:visibility="gone">
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/linear_colse"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingVertical="@dimen/dp_10">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_quick_ask"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginLeft="@dimen/dp_15"
|
||||
android:layout_weight="2"
|
||||
android:text="快速提问"
|
||||
android:textColor="@color/color_zhu"
|
||||
android:textSize="13sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<View
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="1px"
|
||||
android:layout_weight="5" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/img_close_quick"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_alignTop="@+id/tv_quick_ask"
|
||||
android:layout_alignParentRight="true"
|
||||
android:layout_marginRight="@dimen/dp_15"
|
||||
android:layout_weight="0.5"
|
||||
android:src="@mipmap/icon_index_close" />
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_quick_ask"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_below="@+id/linear_colse"
|
||||
android:orientation="horizontal"
|
||||
app:layoutManager="me.rosuh.filepicker.widget.PosLinearLayoutManager" />
|
||||
</RelativeLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@color/white"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
<ImageView
|
||||
android:id="@+id/img_close"
|
||||
android:layout_width="@dimen/dp_22"
|
||||
android:layout_height="@dimen/dp_22"
|
||||
android:layout_marginLeft="@dimen/dp_15"
|
||||
android:src="@mipmap/icon_chat_up" />
|
||||
<EditText
|
||||
android:id="@+id/edit_input"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginHorizontal="@dimen/dp_15"
|
||||
android:layout_marginVertical="@dimen/dp_10"
|
||||
android:layout_weight="9"
|
||||
android:background="@drawable/shape_index_input_bg"
|
||||
android:hint="请输入您的问题..."
|
||||
android:maxLines="4"
|
||||
android:minHeight="39dp"
|
||||
android:paddingHorizontal="@dimen/dp_15"
|
||||
android:text=""
|
||||
android:textColor="@color/black"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/img_send"
|
||||
android:layout_width="@dimen/dp_38"
|
||||
android:layout_height="@dimen/dp_38"
|
||||
android:layout_marginRight="@dimen/dp_15"
|
||||
android:src="@mipmap/icon_index_send" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/img_stop"
|
||||
android:layout_width="@dimen/dp_38"
|
||||
android:layout_height="@dimen/dp_38"
|
||||
android:layout_marginRight="@dimen/dp_15"
|
||||
android:src="@mipmap/icon_index_stop"
|
||||
android:visibility="gone" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</RelativeLayout>
|
||||
@@ -1,86 +0,0 @@
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:padding="8dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical">
|
||||
<LinearLayout
|
||||
android:id="@+id/linear_thinking"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingHorizontal="@dimen/dp_10"
|
||||
android:gravity="center_vertical"
|
||||
android:background="@drawable/shape_gray1_radus10_bg"
|
||||
android:visibility="gone">
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textSize="13sp"
|
||||
android:textColor="@color/color_333333"
|
||||
android:text="努力思考中"/>
|
||||
<com.airbnb.lottie.LottieAnimationView
|
||||
android:id="@+id/lottieDots"
|
||||
android:layout_width="@dimen/dp_50"
|
||||
android:layout_height="50dp"
|
||||
app:lottie_autoPlay="true"
|
||||
app:lottie_loop="true"
|
||||
app:lottie_rawRes="@raw/three_point_typing" />
|
||||
</LinearLayout>
|
||||
|
||||
<RelativeLayout
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content">
|
||||
<TextView
|
||||
android:id="@+id/tv_text"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:padding="10dp"
|
||||
android:lineSpacingExtra="@dimen/dp_2"
|
||||
android:text=""
|
||||
android:textColor="@color/color_333333"
|
||||
android:textSize="13sp"
|
||||
android:textIsSelectable="false"
|
||||
android:scrollHorizontally="false"
|
||||
android:scrollbars="none"
|
||||
android:overScrollMode="never"
|
||||
android:hardwareAccelerated="true"
|
||||
android:layerType="hardware"
|
||||
android:minHeight="20dp" />
|
||||
</RelativeLayout>
|
||||
<LinearLayout
|
||||
android:id="@+id/linear_stop"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:gravity="center_vertical"
|
||||
android:paddingLeft="@dimen/dp_20"
|
||||
android:visibility="gone">
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textSize="12sp"
|
||||
android:textColor="@color/color_E9A01C"
|
||||
android:text="您停止了本次输出"/>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/linear_tips"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:gravity="center_vertical"
|
||||
android:visibility="gone"
|
||||
android:paddingHorizontal="@dimen/dp_4"
|
||||
android:layout_marginTop="@dimen/dp_12"
|
||||
android:paddingVertical="@dimen/dp_4">
|
||||
<include layout="@layout/include_ai_hint_layout"/>
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
android:padding="8dp"
|
||||
android:gravity="end"
|
||||
android:orientation="vertical">
|
||||
<LinearLayout
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal">
|
||||
<TextView
|
||||
android:id="@+id/tv_text"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/color_333333"
|
||||
android:textSize="16sp"
|
||||
android:padding="10dp"
|
||||
android:maxWidth="240dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
android:background="@drawable/shape_index_quick_ask_bg"/>
|
||||
</LinearLayout>
|
||||
|
||||
</LinearLayout>
|
||||
@@ -190,7 +190,7 @@
|
||||
android:id="@+id/checkbox_read"
|
||||
android:layout_width="16dp"
|
||||
android:layout_height="16dp"
|
||||
android:background="@mipmap/ic_launcher"
|
||||
android:background="@mipmap/icon_uncheck"
|
||||
android:button="@null"
|
||||
android:checked="false"
|
||||
android:contentDescription="@string/login_design_agreement_description"
|
||||
@@ -262,8 +262,7 @@
|
||||
android:layout_height="52dp"
|
||||
android:background="@drawable/login_design_email_bg"
|
||||
android:contentDescription="@null"
|
||||
android:padding="15dp"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
android:src="@mipmap/icon_login_lock" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_email_login"
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.core.widget.NestedScrollView
|
||||
<com.scwang.smart.refresh.layout.SmartRefreshLayout
|
||||
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:id="@+id/refresh_shop"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/white">
|
||||
<androidx.core.widget.NestedScrollView
|
||||
android:id="@+id/sv_food_content"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/device_home_background"
|
||||
android:background="@color/white"
|
||||
android:fillViewport="true"
|
||||
android:scrollbars="none"
|
||||
tools:locale="zh">
|
||||
<!-- Fragment content only; MainActivity owns system insets and the bottom TabBar. -->
|
||||
<!-- 仅承载商城页面内容,系统栏和底部 TabBar 由 MainActivity 统一处理。 -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingTop="16dp"
|
||||
android:paddingBottom="16dp">
|
||||
<TextView
|
||||
android:id="@+id/tv_food_title"
|
||||
@@ -122,3 +126,4 @@
|
||||
tools:listitem="@layout/food_recommend_item" />
|
||||
</LinearLayout>
|
||||
</androidx.core.widget.NestedScrollView>
|
||||
</com.scwang.smart.refresh.layout.SmartRefreshLayout>
|
||||
@@ -39,9 +39,7 @@
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
app:layoutManager="me.rosuh.filepicker.widget.PosLinearLayoutManager"
|
||||
android:orientation="horizontal"
|
||||
tools:listitem="@layout/chat_zixun_type_item"
|
||||
tools:itemCount="3"/>
|
||||
android:orientation="horizontal"/>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_content"
|
||||
|
||||
53
app/src/main/res/layout/wifi_list_item.xml
Normal file
53
app/src/main/res/layout/wifi_list_item.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 普通 Wi-Fi 行:网络名称、加密标识、信号图标和底部分隔线。图标后续替换。 -->
|
||||
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="43dp"
|
||||
android:background="?attr/selectableItemBackground"
|
||||
android:clickable="true"
|
||||
android:focusable="true">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_wifi_name"
|
||||
style="@style/WifiSetupNetworkText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginStart="14dp"
|
||||
android:layout_marginEnd="60dp"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center_vertical"
|
||||
android:maxLines="1"
|
||||
tools:text="Home_2.4G" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_gravity="end"
|
||||
android:layout_marginEnd="14dp"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/iv_wifi_lock"
|
||||
android:layout_width="14dp"
|
||||
android:layout_height="14dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
android:contentDescription="@string/wifi_setup_secured_network"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/iv_wifi_signal"
|
||||
android:layout_width="15dp"
|
||||
android:layout_height="15dp"
|
||||
android:contentDescription="@string/wifi_setup_signal"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:id="@+id/wifi_divider"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:layout_gravity="bottom"
|
||||
android:background="@color/wifi_setup_divider" />
|
||||
</FrameLayout>
|
||||
254
app/src/main/res/layout/wifi_list_layout.xml
Normal file
254
app/src/main/res/layout/wifi_list_layout.xml
Normal file
@@ -0,0 +1,254 @@
|
||||
<?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:background="@android:color/white"
|
||||
android:fitsSystemWindows="true"
|
||||
android:orientation="vertical"
|
||||
tools:locale="en">
|
||||
|
||||
<!-- 系统状态栏和导航栏交给宿主页面处理,不绘制设计稿中的时间、电量和底部横条。 -->
|
||||
<FrameLayout
|
||||
android:id="@+id/rl_title"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_title"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:gravity="center"
|
||||
android:letterSpacing="-0.016111111"
|
||||
android:text="@string/wifi_setup_title"
|
||||
android:textColor="#252529"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
</FrameLayout>
|
||||
|
||||
<!-- 表单可滚动,兼容小屏幕和软键盘弹出后的可用高度。 -->
|
||||
<androidx.core.widget.NestedScrollView
|
||||
android:id="@+id/sv_wifi_setup"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:clipToPadding="false"
|
||||
android:fillViewport="true"
|
||||
android:scrollbars="none">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:clipChildren="false"
|
||||
android:clipToPadding="false"
|
||||
android:orientation="vertical"
|
||||
android:paddingBottom="24dp">
|
||||
|
||||
<!-- 设备图片先用启动图标占位;名称、序列号和连接状态由后续业务填充。 -->
|
||||
<androidx.cardview.widget.CardView
|
||||
android:id="@+id/cv_device_info"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="82dp"
|
||||
android:layout_marginStart="26dp"
|
||||
android:layout_marginTop="6dp"
|
||||
android:layout_marginEnd="29dp"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="16dp"
|
||||
app:cardElevation="1dp"
|
||||
app:cardPreventCornerOverlap="false"
|
||||
app:cardUseCompatPadding="false">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingHorizontal="16dp">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/iv_device_image"
|
||||
android:layout_width="46dp"
|
||||
android:layout_height="46dp"
|
||||
android:contentDescription="@string/wifi_setup_device_image"
|
||||
android:scaleType="centerCrop"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="50dp"
|
||||
android:layout_marginStart="12dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_device_name"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="32dp"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center_vertical"
|
||||
android:maxLines="2"
|
||||
android:textColor="@color/wifi_setup_text"
|
||||
android:textSize="12sp"
|
||||
android:textStyle="bold"
|
||||
tools:text="Smart Electric Pancake Maker" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_device_sn"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="15dp"
|
||||
android:layout_marginTop="3dp"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center_vertical"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/wifi_setup_secondary_text"
|
||||
android:textSize="11sp"
|
||||
tools:text="SN: 2024-10-001" />
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_bluetooth_status"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="143dp"
|
||||
android:layout_height="24dp"
|
||||
android:background="@drawable/bl_device_signal_strong_bg"
|
||||
android:ellipsize="end"
|
||||
android:fontFamily="sans-serif-medium"
|
||||
android:gravity="center"
|
||||
android:letterSpacing="-0.016363637"
|
||||
android:maxLines="1"
|
||||
android:paddingHorizontal="5dp"
|
||||
android:textColor="@color/bl_device_signal_strong"
|
||||
android:textSize="11sp"
|
||||
tools:text="@string/wifi_setup_bluetooth_connected" />
|
||||
</LinearLayout>
|
||||
</androidx.cardview.widget.CardView>
|
||||
|
||||
<androidx.cardview.widget.CardView
|
||||
android:id="@+id/cv_wifi_networks"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="26dp"
|
||||
android:layout_marginTop="14dp"
|
||||
android:layout_marginEnd="29dp"
|
||||
app:cardBackgroundColor="@android:color/white"
|
||||
app:cardCornerRadius="16dp"
|
||||
app:cardElevation="1dp"
|
||||
app:cardPreventCornerOverlap="false"
|
||||
app:cardUseCompatPadding="false">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_wifi_network_title"
|
||||
style="@style/WifiSetupSectionTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="36dp"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:gravity="center_vertical"
|
||||
android:text="@string/wifi_setup_select_network" />
|
||||
|
||||
<!-- 运行时绑定设备返回的网络;选中行与普通行分别使用对应的列表项样式。 -->
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rv_wifi_networks"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="129dp"
|
||||
android:layout_marginTop="8dp"
|
||||
android:nestedScrollingEnabled="false"
|
||||
android:overScrollMode="never"
|
||||
android:scrollbars="none"
|
||||
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
|
||||
tools:itemCount="3"
|
||||
tools:listitem="@layout/wifi_list_item" />
|
||||
|
||||
<!-- 空列表、扫描中、断连和失败时显示状态,正常列表不占用该区域。 -->
|
||||
<TextView
|
||||
android:id="@+id/tv_wifi_status"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:paddingHorizontal="14dp"
|
||||
android:paddingVertical="12dp"
|
||||
android:textColor="@color/wifi_setup_secondary_text"
|
||||
android:textSize="12sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_other_networks"
|
||||
style="@style/WifiSetupNetworkText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="42dp"
|
||||
android:background="?attr/selectableItemBackground"
|
||||
android:clickable="true"
|
||||
android:focusable="true"
|
||||
android:gravity="center_vertical"
|
||||
android:paddingHorizontal="14dp"
|
||||
android:text="@string/wifi_setup_other_networks" />
|
||||
</LinearLayout>
|
||||
</androidx.cardview.widget.CardView>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_wifi_password_label"
|
||||
style="@style/WifiSetupSectionTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="16dp"
|
||||
android:layout_marginStart="42dp"
|
||||
android:layout_marginTop="30dp"
|
||||
android:layout_marginEnd="45dp"
|
||||
android:gravity="center_vertical"
|
||||
android:labelFor="@id/et_wifi_password"
|
||||
android:text="@string/wifi_setup_password" />
|
||||
|
||||
<androidx.appcompat.widget.AppCompatEditText
|
||||
android:id="@+id/et_wifi_password"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="46dp"
|
||||
android:layout_marginStart="42dp"
|
||||
android:layout_marginTop="8dp"
|
||||
android:layout_marginEnd="45dp"
|
||||
android:background="@drawable/login_design_input_bg"
|
||||
android:gravity="center_vertical"
|
||||
android:hint="@string/wifi_setup_password_hint"
|
||||
android:imeOptions="actionDone"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="textPassword"
|
||||
android:maxLines="1"
|
||||
android:paddingHorizontal="20dp"
|
||||
android:paddingVertical="0dp"
|
||||
android:singleLine="true"
|
||||
android:textColor="@color/wifi_setup_text"
|
||||
android:textColorHint="@color/wifi_setup_text"
|
||||
android:textSize="14sp"
|
||||
app:backgroundTint="@null" />
|
||||
|
||||
<androidx.appcompat.widget.AppCompatButton
|
||||
android:id="@+id/btn_start_setup"
|
||||
style="@style/LoginDesignText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="50dp"
|
||||
android:layout_marginStart="26dp"
|
||||
android:layout_marginTop="36dp"
|
||||
android:layout_marginEnd="29dp"
|
||||
android:background="@drawable/wifi_setup_button_bg"
|
||||
android:fontFamily="sans-serif-medium"
|
||||
android:gravity="center"
|
||||
android:minWidth="0dp"
|
||||
android:minHeight="0dp"
|
||||
android:padding="0dp"
|
||||
android:stateListAnimator="@null"
|
||||
android:text="@string/wifi_setup_start"
|
||||
android:textAllCaps="false"
|
||||
android:textColor="@android:color/white"
|
||||
android:textSize="16sp"
|
||||
app:backgroundTint="@null" />
|
||||
</LinearLayout>
|
||||
</androidx.core.widget.NestedScrollView>
|
||||
</LinearLayout>
|
||||
37
app/src/main/res/layout/wifi_list_selected_item.xml
Normal file
37
app/src/main/res/layout/wifi_list_selected_item.xml
Normal file
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 已选 Wi-Fi 行:按设计稿显示浅橙底、橙色名称和信号图标。 -->
|
||||
<FrameLayout 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="43dp"
|
||||
android:background="@drawable/wifi_setup_selected_bg"
|
||||
android:clickable="true"
|
||||
android:focusable="true"
|
||||
android:foreground="?attr/selectableItemBackground">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_wifi_name"
|
||||
style="@style/WifiSetupNetworkText"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginStart="14dp"
|
||||
android:layout_marginEnd="46dp"
|
||||
android:ellipsize="end"
|
||||
android:fontFamily="sans-serif"
|
||||
android:gravity="center_vertical"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/wifi_setup_accent"
|
||||
android:textStyle="bold"
|
||||
tools:text="Home5_2.4G" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/iv_wifi_signal"
|
||||
android:layout_width="16dp"
|
||||
android:layout_height="16dp"
|
||||
android:layout_gravity="end|center_vertical"
|
||||
android:layout_marginEnd="14dp"
|
||||
app:tint="@color/wifi_setup_accent"
|
||||
android:contentDescription="@string/wifi_setup_signal"
|
||||
android:src="@mipmap/ic_launcher" />
|
||||
</FrameLayout>
|
||||
@@ -61,9 +61,7 @@
|
||||
android:layout_height="wrap_content"
|
||||
app:layoutManager="me.rosuh.filepicker.widget.PosLinearLayoutManager"
|
||||
android:orientation="horizontal"
|
||||
android:layout_gravity="center_horizontal"
|
||||
tools:listitem="@layout/chat_zixun_type_item"
|
||||
tools:itemCount="3"/>
|
||||
android:layout_gravity="center_horizontal"/>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_content"
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
android:title="@string/device_tab_title"/>
|
||||
|
||||
<item
|
||||
android:id="@+id/navigation_index"
|
||||
android:icon="@drawable/bottom_index_select"
|
||||
android:title="AI分析"
|
||||
android:id="@+id/navigation_shop"
|
||||
android:icon="@drawable/bottom_shop_select"
|
||||
android:title="@string/shop_tab_title"
|
||||
android:visible="true"/>
|
||||
<item
|
||||
android:id="@+id/navigation_fate"
|
||||
|
||||
BIN
app/src/main/res/mipmap-xhdpi/icon_add_device.png
Normal file
BIN
app/src/main/res/mipmap-xhdpi/icon_add_device.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
BIN
app/src/main/res/mipmap-xhdpi/icon_balance.png
Normal file
BIN
app/src/main/res/mipmap-xhdpi/icon_balance.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 900 B |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user