Compare commits

..

10 Commits

Author SHA1 Message Date
2b745f362b <positions>APK 15.0.9 release Publish. 2025-10-03 23:10:42 +08:00
ZhanGSKen
5f5652170f 添加任务铃声循环播放功能。 2025-10-03 23:09:25 +08:00
0e41d954ca <positions>APK 15.0.8 release Publish. 2025-10-03 11:38:10 +08:00
ZhanGSKen
f0f248b018 添加任务触发通知发送功能。 2025-10-03 11:24:44 +08:00
ZhanGSKen
721a0af8c0 任务列表基本编辑功能实现,未调试。 2025-10-03 04:34:15 +08:00
ZhanGSKen
977ff5497b 20251003_042915_870 2025-10-03 04:29:28 +08:00
ZhanGSKen
1e17d326a0 20251003_035831_435 2025-10-03 03:58:36 +08:00
ZhanGSKen
2d78681d9d 窗口速切换数据丢失问题解决 2025-10-03 03:26:04 +08:00
ZhanGSKen
31f6c3a9ec 20251003_031830_311 2025-10-03 03:18:34 +08:00
ZhanGSKen
00df478c32 实现位置管理窗口实时位置显示。 2025-10-03 02:45:47 +08:00
31 changed files with 3052 additions and 4056 deletions

View File

@@ -19,21 +19,18 @@ def genVersionName(def versionName){
android { android {
// 1. compileSdkVersion:必须 ≥ targetSdkVersion建议直接等于 targetSdkVersion30 compileSdkVersion 32
compileSdkVersion 30 buildToolsVersion "32.0.0"
// 2. buildToolsVersion需匹配 compileSdkVersion建议使用 30.x.x 最新稳定版(无需高于 compileSdkVersion
buildToolsVersion "30.0.3" // 这是 30 对应的最新稳定版,避免使用 beta 版
defaultConfig { defaultConfig {
applicationId "cc.winboll.studio.appbase" applicationId "cc.winboll.studio.appbase"
minSdkVersion 23 minSdkVersion 24
targetSdkVersion 30 targetSdkVersion 30
versionCode 1 versionCode 1
// versionName 更新后需要手动设置 // versionName 更新后需要手动设置
// .winboll/winbollBuildProps.properties 文件的 stageCount=0 // .winboll/winbollBuildProps.properties 文件的 stageCount=0
// Gradle编译环境下合起来的 versionName 就是 "${versionName}.0" // Gradle编译环境下合起来的 versionName 就是 "${versionName}.0"
versionName "15.11" versionName "15.10"
if(true) { if(true) {
versionName = genVersionName("${versionName}") versionName = genVersionName("${versionName}")
} }

View File

@@ -1,8 +1,8 @@
#Created by .winboll/winboll_app_build.gradle #Created by .winboll/winboll_app_build.gradle
#Thu Nov 13 05:16:16 HKT 2025 #Fri Sep 26 05:36:14 HKT 2025
stageCount=1 stageCount=9
libraryProject=libappbase libraryProject=libappbase
baseVersion=15.11 baseVersion=15.10
publishVersion=15.11.0 publishVersion=15.10.8
buildCount=0 buildCount=0
baseBetaVersion=15.11.1 baseBetaVersion=15.10.9

View File

@@ -3,6 +3,9 @@
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:android="http://schemas.android.com/apk/res/android"
package="cc.winboll.studio.appbase"> package="cc.winboll.studio.appbase">
<!-- 网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<application <application
android:name=".App" android:name=".App"
android:icon="@drawable/ic_winboll" android:icon="@drawable/ic_winboll"

View File

@@ -1,40 +1,19 @@
package cc.winboll.studio.appbase; package cc.winboll.studio.appbase;
import cc.winboll.studio.libappbase.GlobalApplication;
import cc.winboll.studio.libappbase.ToastUtils;
/** /**
* @Author ZhanGSKen<zhangsken@qq.com> * @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/01/05 09:54:42 * @Date 2025/01/05 09:54:42
* @Describe 应用全局入口类(继承基础库 GlobalApplication * @Describe APPbase 应用类
* 负责应用初始化、全局资源管理与生命周期回调处理,是整个应用的核心入口
*/ */
import android.content.IntentFilter;
import cc.winboll.studio.libappbase.GlobalApplication;
public class App extends GlobalApplication { public class App extends GlobalApplication {
/** 当前应用类的日志 TAG用于调试输出标识日志来源 */
public static final String TAG = "App"; public static final String TAG = "App";
/**
* 应用创建时回调(全局初始化入口)
* 在应用进程启动时执行,仅调用一次,用于初始化全局工具类、第三方库等
*/
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); // 调用父类初始化逻辑(如基础库配置、全局上下文设置) super.onCreate();
// 初始化 Toast 工具类(传入应用全局上下文,确保 Toast 可在任意地方调用)
ToastUtils.init(getApplicationContext());
}
/**
* 应用终止时回调(资源释放入口)
* 仅在模拟环境(如 Android Studio 模拟器)中可靠触发,真机上可能因系统回收进程不执行
* 用于释放全局资源,避免内存泄漏
*/
@Override
public void onTerminate() {
super.onTerminate(); // 调用父类终止逻辑(如基础库资源释放)
// 释放 Toast 工具类资源(销毁全局 Toast 实例,避免内存泄漏)
ToastUtils.release();
} }
} }

View File

@@ -8,133 +8,67 @@ import android.os.Bundle;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.widget.Toast;
import android.widget.Toolbar; import android.widget.Toolbar;
import cc.winboll.studio.appbase.R; import cc.winboll.studio.appbase.R;
import cc.winboll.studio.libappbase.LogActivity; import cc.winboll.studio.libappbase.LogActivity;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils; import cc.winboll.studio.libappbase.ToastUtils;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 未标注(建议补充创建日期)
* @Describe 应用主界面 Activity入口界面
* 包含功能测试按钮崩溃测试、日志查看、Toast测试、顶部工具栏菜单功能是应用交互的核心入口
*/
public class MainActivity extends Activity { public class MainActivity extends Activity {
/** 当前 Activity 的日志 TAG用于调试输出标识日志来源 */
public static final String TAG = "MainActivity"; public static final String TAG = "MainActivity";
/** 顶部工具栏(用于展示标题、菜单,绑定布局中的 Toolbar 控件) */ Toolbar mToolbar;
private Toolbar mToolbar;
/**
* Activity 创建时回调(初始化界面)
* 在 Activity 首次创建时执行,用于加载布局、初始化控件、设置事件监听
* @param savedInstanceState 保存 Activity 状态的 Bundle如屏幕旋转时的数据恢复
*/
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
ToastUtils.show("onCreate"); // 显示 Activity 创建提示(调试用) ToastUtils.show("onCreate");
setContentView(R.layout.activity_main); // 加载主界面布局 setContentView(R.layout.activity_main);
// 初始化 Toolbar 并设置为 ActionBar
mToolbar = findViewById(R.id.toolbar); mToolbar = findViewById(R.id.toolbar);
setActionBar(mToolbar); // 将 Toolbar 替代系统默认 ActionBar setActionBar(mToolbar);
} }
/**
* 创建菜单时回调(加载工具栏菜单)
* 初始化 ActionBar 菜单,加载自定义菜单布局
* @param menu 菜单对象(用于承载菜单项)
* @return true显示菜单false不显示菜单
*/
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
// 加载菜单布局R.menu.toolbar_main 为自定义菜单文件)
getMenuInflater().inflate(R.menu.toolbar_main, menu); getMenuInflater().inflate(R.menu.toolbar_main, menu);
return super.onCreateOptionsMenu(menu); return super.onCreateOptionsMenu(menu);
} }
/**
* 菜单 item 点击时回调(处理菜单事件)
* 响应 Toolbar 菜单项的点击事件,执行对应业务逻辑
* @param item 被点击的菜单项
* @return true消费点击事件false不消费传递给父类
*/
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.item_home: case R.id.item_home : {
// 点击 "首页/官网" 菜单项,唤起浏览器打开指定网站 openWebsiteInBrowser(this);
openWebsiteInBrowser(this); }
break; }
// 可扩展其他菜单项(如设置、关于等)的处理逻辑 // 在switch语句中处理每个ID并在处理完后返回true未处理的情况返回false。
}
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
/**
* 崩溃测试按钮点击事件(触发应用崩溃,用于调试异常捕获)
* 故意执行非法操作(循环获取不存在的字符串资源),强制应用崩溃
* @param view 触发事件的 View对应布局中的崩溃测试按钮
*/
public void onCrashTest(View view) { public void onCrashTest(View view) {
// 循环从 Integer.MIN_VALUEInteger.MAX_VALUE,获取不存在的字符串资源 ID触发崩溃 for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) {
for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) { getString(i);
getString(i); // i 超出资源 ID 范围,抛出 Resources.NotFoundException 导致崩溃 }
}
} }
/**
* 日志测试按钮点击事件(打开日志查看界面)
* 启动 LogActivity用于查看应用运行日志
* @param view 触发事件的 View对应布局中的日志测试按钮
*/
public void onLogTest(View view) { public void onLogTest(View view) {
// 启动日志查看 Activity通过静态方法传入上下文简化跳转逻辑
LogActivity.startLogActivity(this); LogActivity.startLogActivity(this);
} }
/** /**
* Toast 工具测试按钮点击事件(测试全局 Toast 功能) * 唤起默认浏览器打开指定网站
* 测试主线程、子线程中 Toast 的显示效果,验证 ToastUtils 的可用性 * @param context 上下文(如 Activity.this
* @param view 触发事件的 View对应布局中的 Toast 测试按钮) */
*/ public void openWebsiteInBrowser(Context context) {
public void onToastUtilsTest(View view) { // 目标网站地址
LogUtils.d(TAG, "onToastUtilsTest"); // 打印调试日志,标识进入 Toast 测试 String url = "https://www.winboll.cc";
ToastUtils.show("Hello, WinBoLL!"); // 主线程显示 Toast // 构建打开浏览器的意图
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// 开启子线程,延迟 2 秒后显示 Toast测试子线程 Toast 兼容性 // 设置标志:避免创建新的任务栈(可选,按需求调整
new Thread(new Runnable() { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
@Override context.startActivity(intent);
public void run() {
try { }
Thread.sleep(2000); // 线程休眠 2 秒
// 若 ToastUtils 已处理主线程切换,此处可直接调用;否则需通过 Handler 切换到主线程
ToastUtils.show("Thread.sleep(2000);ToastUtils.show...");
} catch (InterruptedException e) {
// 捕获线程中断异常(如线程被销毁时),不做处理(测试场景)
e.printStackTrace();
}
}
}).start();
}
/**
* 唤起系统默认浏览器打开指定网站(跳转至应用官网)
* 通过 Intent.ACTION_VIEW 隐式意图,触发浏览器打开目标 URL
* @param context 上下文对象(如 Activity、Application此处为 MainActivity
*/
public void openWebsiteInBrowser(Context context) {
String url = "https://www.winboll.cc"; // 目标网站 URL应用官网
// 构建隐式意图ACTION_VIEW 表示查看指定数据Uri 为网站地址)
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// 设置标志:在新的任务栈中启动 Activity避免与当前应用任务栈混淆
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动意图(唤起浏览器)
context.startActivity(intent);
}
} }

View File

@@ -28,8 +28,7 @@
android:background="#81C7F5" android:background="#81C7F5"
android:paddingVertical="12dp" android:paddingVertical="12dp"
android:layout_marginHorizontal="24dp" android:layout_marginHorizontal="24dp"
android:onClick="onCrashTest" android:onClick="onCrashTest"/>
android:layout_margin="10dp"/>
<Button <Button
android:layout_width="match_parent" android:layout_width="match_parent"
@@ -40,20 +39,7 @@
android:background="#81C7F5" android:background="#81C7F5"
android:paddingVertical="12dp" android:paddingVertical="12dp"
android:layout_marginHorizontal="24dp" android:layout_marginHorizontal="24dp"
android:onClick="onLogTest" android:onClick="onLogTest"/>
android:layout_margin="10dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="应用吐司测试"
android:textSize="16sp"
android:textColor="@android:color/white"
android:background="#81C7F5"
android:paddingVertical="12dp"
android:layout_marginHorizontal="24dp"
android:onClick="onToastUtilsTest"
android:layout_margin="10dp"/>
</LinearLayout> </LinearLayout>

View File

@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="app_name">AppBase</string> <string name="app_name">AppBase</string>
<string name="tileservice_name">WinBoLL</string>
</resources> </resources>

View File

@@ -5,14 +5,11 @@ apply from: '../.winboll/winboll_lint_build.gradle'
android { android {
// 1. compileSdkVersion:必须 ≥ targetSdkVersion建议直接等于 targetSdkVersion30 compileSdkVersion 32
compileSdkVersion 30 buildToolsVersion "32.0.0"
// 2. buildToolsVersion需匹配 compileSdkVersion建议使用 30.x.x 最新稳定版(无需高于 compileSdkVersion
buildToolsVersion "30.0.3" // 这是 30 对应的最新稳定版,避免使用 beta 版
defaultConfig { defaultConfig {
minSdkVersion 23 minSdkVersion 24
targetSdkVersion 30 targetSdkVersion 30
} }
buildTypes { buildTypes {
@@ -25,4 +22,9 @@ android {
dependencies { dependencies {
api fileTree(dir: 'libs', include: ['*.jar']) api fileTree(dir: 'libs', include: ['*.jar'])
// 网络连接类库
api 'com.squareup.okhttp3:okhttp:4.4.1'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
api 'com.google.code.gson:gson:2.10.1'
} }

View File

@@ -1,8 +1,8 @@
#Created by .winboll/winboll_app_build.gradle #Created by .winboll/winboll_app_build.gradle
#Thu Nov 13 05:16:16 HKT 2025 #Fri Sep 26 05:36:14 HKT 2025
stageCount=1 stageCount=9
libraryProject=libappbase libraryProject=libappbase
baseVersion=15.11 baseVersion=15.10
publishVersion=15.11.0 publishVersion=15.10.8
buildCount=0 buildCount=0
baseBetaVersion=15.11.1 baseBetaVersion=15.10.9

View File

@@ -1,138 +1,73 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/03/02 10:28:08
* @Describe 应用调试模型
*/
import android.util.JsonReader; import android.util.JsonReader;
import android.util.JsonWriter; import android.util.JsonWriter;
import cc.winboll.studio.libappbase.BaseBean;
import java.io.IOException; import java.io.IOException;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:01
* @Describe WinBoLL 应用全局数据模型类
* 继承自 BaseBean用于存储和管理应用的核心配置信息如调试状态
* 支持 JSON 序列化/反序列化,便于数据持久化或跨组件传递
*/
public class APPModel extends BaseBean { public class APPModel extends BaseBean {
/**
* 日志打印标签,用于区分当前类的日志输出
*/
public static final String TAG = "APPModel"; public static final String TAG = "APPModel";
/** // 应用是否处于正在调试状态
* 应用调试状态标识 //
* true应用处于调试模式可输出详细日志、启用调试功能等 boolean isDebuging = false;
* false应用处于正式模式关闭调试相关功能优化性能
*/
private boolean isDebugging = false; // 修正拼写:原 isDebuging -> isDebugging符合命名规范
/**
* 无参构造方法
* 初始化调试状态为默认值false正式模式
*/
public APPModel() { public APPModel() {
this.isDebugging = false; this.isDebuging = false;
} }
/** public APPModel(boolean isDebuging) {
* 带参构造方法 this.isDebuging = isDebuging;
* 可通过参数指定应用的初始调试状态
* @param isDebugging 初始调试状态true调试模式false正式模式
*/
public APPModel(boolean isDebugging) {
this.isDebugging = isDebugging;
} }
/** public void setIsDebuging(boolean isDebuging) {
* 设置应用调试状态 this.isDebuging = isDebuging;
* @param isDebugging 目标调试状态true开启调试false关闭调试
*/
public void setIsDebugging(boolean isDebugging) {
this.isDebugging = isDebugging;
} }
/** public boolean isDebuging() {
* 获取当前应用调试状态 return isDebuging;
* @return 调试状态true调试中false非调试
*/
public boolean isDebugging() {
return isDebugging;
} }
/**
* 重写父类方法,返回当前类的全限定名
* 用于标识数据模型的类类型(可用于反射、序列化校验等场景)
* @return 类的全限定名cc.winboll.studio.libappbase.APPModel
*/
@Override @Override
public String getName() { public String getName() {
return APPModel.class.getName(); return APPModel.class.getName();
} }
/**
* 重写父类方法,将当前模型的字段序列化到 JSON 中
* 用于将调试状态等核心数据转换为 JSON 格式(如持久化到文件、网络传输)
* @param jsonWriter JSON 写入器对象,用于输出 JSON 数据
* @throws IOException 当 JSON 写入失败时抛出(如流关闭、格式错误)
*/
@Override @Override
public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException { public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException {
// 先调用父类方法,序列化父类中的字段(若 BaseBean 有可序列化字段)
super.writeThisToJsonWriter(jsonWriter); super.writeThisToJsonWriter(jsonWriter);
// 序列化当前类的调试状态字段key 为 "isDebuging"保持与原代码一致避免兼容性问题value 为当前状态 jsonWriter.name("isDebuging").value(isDebuging());
jsonWriter.name("isDebuging").value(isDebugging());
} }
/**
* 重写父类方法,从 JSON 中解析字段并初始化当前对象
* 用于将 JSON 格式的配置数据解析为 APPModel 实例(如从文件读取、网络接收后解析)
* @param jsonReader JSON 读取器对象,用于读取 JSON 数据
* @param name 当前解析的 JSON 字段名
* @return true字段解析成功false字段不属于当前类需由调用者处理
* @throws IOException 当 JSON 读取失败时抛出(如流关闭、数据格式错误)
*/
@Override @Override
public boolean initObjectsFromJsonReader(JsonReader jsonReader, String name) throws IOException { public boolean initObjectsFromJsonReader(JsonReader jsonReader, String name) throws IOException {
// 先调用父类方法,解析父类中的字段(若 BaseBean 有可解析字段) if (super.initObjectsFromJsonReader(jsonReader, name)) { return true; } else {
if (super.initObjectsFromJsonReader(jsonReader, name)) {
return true; // 父类已处理该字段,直接返回成功
} else {
// 解析当前类的字段
if (name.equals("isDebuging")) { if (name.equals("isDebuging")) {
// 读取 JSON 中 "isDebuging" 字段的值,设置为当前对象的调试状态 setIsDebuging(jsonReader.nextBoolean());
setIsDebugging(jsonReader.nextBoolean());
} else { } else {
// 字段不属于当前类,返回 false 提示调用者跳过该字段
return false; return false;
} }
} }
// 字段解析成功,返回 true
return true; return true;
} }
/**
* 重写父类方法,从 JSON 读取器中完整解析一个 APPModel 实例
* 负责处理 JSON 对象的开始/结束标记,循环解析所有字段
* @param jsonReader JSON 读取器对象,用于读取 JSON 数据
* @return 解析完成的当前 APPModel 实例(支持链式调用)
* @throws IOException 当 JSON 读取失败时抛出(如流关闭、数据格式错误)
*/
@Override @Override
public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException { public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException {
// 开始解析 JSON 对象(对应 JSON 中的 '{'
jsonReader.beginObject(); jsonReader.beginObject();
// 循环读取 JSON 中的所有字段(直到对象结束)
while (jsonReader.hasNext()) { while (jsonReader.hasNext()) {
// 获取当前字段名
String name = jsonReader.nextName(); String name = jsonReader.nextName();
// 解析字段:若当前类无法处理该字段,则跳过(避免解析异常)
if (!initObjectsFromJsonReader(jsonReader, name)) { if (!initObjectsFromJsonReader(jsonReader, name)) {
jsonReader.skipValue(); jsonReader.skipValue();
} }
} }
// 结束解析 JSON 对象(对应 JSON 中的 '}' // 结束 JSON 对象
jsonReader.endObject(); jsonReader.endObject();
// 返回解析完成的实例(当前对象)
return this; return this;
} }
} }

View File

@@ -1,5 +1,10 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/01/15 11:11:52
* @Describe Json Bean 基础类。
*/
import android.content.Context; import android.content.Context;
import android.util.JsonReader; import android.util.JsonReader;
import android.util.JsonWriter; import android.util.JsonWriter;
@@ -9,428 +14,274 @@ import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.ArrayList; import java.util.ArrayList;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:03
* @Describe WinBoLL JSON 数据模型基类(抽象类)
* 定义 Json Bean 的核心规范:序列化/反序列化、文件持久化、列表处理等通用逻辑,
* 子类(如 APPModel需实现抽象方法实现自身字段的 JSON 读写
* @param <T> 泛型约束,限定子类必须继承自 BaseBean
*/
public abstract class BaseBean<T extends BaseBean> { public abstract class BaseBean<T extends BaseBean> {
/** 日志标签,用于当前基类的日志输出标识 */ public static final String TAG = "BaseBean";
public static final String TAG = "BaseBean"; static final String BEAN_NAME = "BeanName";
/** JSON 中存储 Bean 类名的字段键(用于校验 Bean 类型一致性) */
static final String BEAN_NAME = "BeanName";
/** public BaseBean() {}
* 无参构造方法(子类需默认实现,支持反射实例化)
*/
public BaseBean() {}
/** public abstract String getName();
* 抽象方法:获取当前 Bean 的全限定类名
* 子类需实现,用于标识 Bean 类型(序列化/校验时使用)
* @return 类的全限定名cc.winboll.studio.libappbase.APPModel
*/
public abstract String getName();
/** public String getBeanJsonFilePath(Context context) {
* 获取单个 Bean 的 JSON 持久化文件路径
* 路径:外部存储/应用私有目录/BaseBean/[类名].json
* @param context 上下文(用于获取应用存储目录)
* @return 单个 Bean 的文件绝对路径
*/
public String getBeanJsonFilePath(Context context) {
return context.getExternalFilesDir(TAG) + "/" + getName() + ".json";
}
/** return context.getExternalFilesDir(TAG) + "/" + getName() + ".json";
* 获取 Bean 列表的 JSON 持久化文件路径 }
* 路径:外部存储/应用私有目录/BaseBean/[类名]_List.json
* @param context 上下文(用于获取应用存储目录)
* @return Bean 列表的文件绝对路径
*/
public String getBeanListJsonFilePath(Context context) {
return context.getExternalFilesDir(TAG) + "/" + getName() + "_List.json";
}
/** public String getBeanListJsonFilePath(Context context) {
* 将 Bean 类名写入 JSON序列化基础字段
* 子类可重写扩展,添加自身字段的 JSON 写入逻辑
* @param jsonWriter JSON 写入器(用于输出 JSON 数据)
* @throws IOException JSON 写入失败时抛出(如流异常)
*/
public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException {
// 写入 Bean 类名字段(用于反序列化时校验类型)
jsonWriter.name(BEAN_NAME).value(getName());
}
/** return context.getExternalFilesDir(TAG) + "/" + getName() + "_List.json";
* 从 JSON 读取字段并初始化 Bean反序列化基础逻辑 }
* 子类需重写,实现自身字段的解析逻辑
* @param jsonReader JSON 读取器(用于读取 JSON 数据)
* @param name 当前解析的 JSON 字段名
* @return true字段解析成功当前类处理false字段未处理需跳过
* @throws IOException JSON 读取失败时抛出(如流异常)
*/
public boolean initObjectsFromJsonReader(JsonReader jsonReader, String name) throws IOException {
return false; // 基类未处理任何字段,返回 false
}
/** public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException {
* 抽象方法:从 JSON 读取器解析并返回 Bean 实例 jsonWriter.name(BEAN_NAME).value(getName());
* 子类需实现,处理自身字段的完整解析逻辑 }
* @param jsonReader JSON 读取器(用于读取 JSON 数据)
* @return 解析完成的 Bean 实例
* @throws IOException JSON 读取失败时抛出(如流异常)
*/
abstract public T readBeanFromJsonReader(JsonReader jsonReader) throws IOException;
/** public boolean initObjectsFromJsonReader(JsonReader jsonReader, String name) throws IOException {
* 校验 JSON 文件中的 Bean 列表与目标类是否一致 return false;
* 对比文件中每个 Bean 的类名与目标类名,返回不一致信息 }
* @param szFilePath JSON 文件路径(存储 Bean 列表的文件)
* @param clazz 目标 Bean 类(用于校验类型)
* @return 空串:校验一致;非空串:不一致信息(总数/差异数)或异常信息
* @param <T> 泛型约束,限定为 BaseBean 子类
*/
public static <T extends BaseBean> String checkIsTheSameBeanListAndFile(String szFilePath, Class<T> clazz) {
StringBuilder sbResult = new StringBuilder();
String szErrorInfo = "Check Is The Same Bean List And File Error : ";
try { abstract public T readBeanFromJsonReader(JsonReader jsonReader) throws IOException;
int sameCount = 0; // 类名匹配的 Bean 数量
int totalCount = 0; // 文件中 Bean 总数量
// 反射创建目标 Bean 实例(用于获取类名) public static <T extends BaseBean> String checkIsTheSameBeanListAndFile(String szFilePath, Class<T> clazz) {
T beanTemp = clazz.newInstance(); StringBuilder sbResult = new StringBuilder();
String targetBeanName = beanTemp.getName(); String szErrorInfo = "Check Is The Same Bean List And File Error : ";
// 读取文件中的 JSON 字符串
String listJson = UTF8FileUtils.readStringFromFile(szFilePath);
StringReader stringReader = new StringReader(listJson);
JsonReader jsonReader = new JsonReader(stringReader);
jsonReader.beginArray(); // 开始解析 JSON 数组Bean 列表) try {
while (jsonReader.hasNext()) { int nSameCount = 0;
totalCount++; int nBeanListCout = 0;
jsonReader.beginObject(); // 开始解析单个 Bean 对象
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
// 只校验 BEAN_NAME 字段,其他字段跳过
if (name.equals(BEAN_NAME)) {
// 对比当前 Bean 类名与目标类名
if (targetBeanName.equals(jsonReader.nextString())) {
sameCount++;
}
} else {
jsonReader.skipValue(); // 跳过非目标字段
}
}
jsonReader.endObject(); // 结束单个 Bean 对象解析
}
jsonReader.endArray(); // 结束 JSON 数组解析
// 生成校验结果 T beanTemp = clazz.newInstance();
if (sameCount == totalCount) { String szBeanSimpleName = beanTemp.getName();
return ""; // 全部匹配,返回空串 String szListJson = UTF8FileUtils.readStringFromFile(szFilePath);
} else { StringReader stringReader = new StringReader(szListJson);
// 部分不匹配,返回统计信息 JsonReader jsonReader = new JsonReader(stringReader);
sbResult.append("Total : ").append(totalCount) jsonReader.beginArray();
.append(" Diff : ").append(totalCount - sameCount); while (jsonReader.hasNext()) {
} nBeanListCout++;
} catch (InstantiationException e) { jsonReader.beginObject();
// 反射实例化失败(如无无参构造) while (jsonReader.hasNext()) {
sbResult.append(szErrorInfo).append(e); String name = jsonReader.nextName();
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace()); if (name.equals(BEAN_NAME)) {
} catch (IllegalAccessException e) { if (szBeanSimpleName.equals(jsonReader.nextString())) {
// 反射访问权限异常 nSameCount++;
sbResult.append(szErrorInfo).append(e); }
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace()); } else {
} catch (IOException e) { jsonReader.skipValue();
// 文件读取或 JSON 解析异常 }
sbResult.append(szErrorInfo).append(e); }
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace()); jsonReader.endObject();
} }
return sbResult.toString(); jsonReader.endArray();
}
/** // 返回检查结果
* 将 JSON 字符串解析为目标 Bean 实例 if (nSameCount == nBeanListCout) {
* 通过反射创建 Bean 实例,调用子类解析逻辑完成初始化 // 检查一致直接返回空串
* @param szBean JSON 字符串(单个 Bean 的 JSON 数据) return "";
* @param clazz 目标 Bean 类(用于反射实例化) } else {
* @return 解析成功的 Bean 实例;失败返回 null // 检查不一致返回对比信息
* @throws IOException JSON 解析失败时抛出 sbResult.append("Total : ");
* @param <T> 泛型约束,限定为 BaseBean 子类 sbResult.append(nBeanListCout);
*/ sbResult.append(" Diff : ");
public static <T extends BaseBean> T parseStringToBean(String szBean, Class<T> clazz) throws IOException { sbResult.append(nBeanListCout - nSameCount);
StringReader stringReader = new StringReader(szBean); }
JsonReader jsonReader = new JsonReader(stringReader); } catch (InstantiationException e) {
sbResult.append(szErrorInfo);
sbResult.append(e);
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
} catch (IllegalAccessException e) {
sbResult.append(szErrorInfo);
sbResult.append(e);
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
} catch (IOException e) {
sbResult.append(szErrorInfo);
sbResult.append(e);
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return sbResult.toString();
}
try { public static <T extends BaseBean> T parseStringToBean(String szBean, Class<T> clazz) throws IOException {
// 反射创建 Bean 实例 // 创建 JsonWriter 对象
T beanTemp = clazz.newInstance(); StringReader stringReader = new StringReader(szBean);
// 调用子类解析方法,返回解析后的实例 JsonReader jsonReader = new JsonReader(stringReader);
return (T) beanTemp.readBeanFromJsonReader(jsonReader); try {
} catch (InstantiationException | IllegalAccessException e) { T beanTemp = clazz.newInstance();
// 反射异常日志记录 return (T)beanTemp.readBeanFromJsonReader(jsonReader);
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace()); } catch (InstantiationException e) {
} LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
return null; } catch (IllegalAccessException e) {
} LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return null;
}
/** public static <T extends BaseBean> boolean parseStringToBeanList(String szBeanList, ArrayList<T> beanList, Class<T> clazz) {
* 将 JSON 字符串解析为 Bean 列表 try {
* 清空目标列表,将解析后的 Bean 逐个添加到列表中 if(beanList == null) {
* @param szBeanList JSON 字符串Bean 列表的 JSON 数组) beanList = new ArrayList<T>();
* @param beanList 目标列表(存储解析后的 Bean } else {
* @param clazz 目标 Bean 类(用于反射实例化) beanList.clear();
* @return true解析成功false解析失败 }
* @param <T> 泛型约束,限定为 BaseBean 子类 StringReader stringReader = new StringReader(szBeanList);
*/ JsonReader jsonReader = new JsonReader(stringReader);
public static <T extends BaseBean> boolean parseStringToBeanList(String szBeanList, ArrayList<T> beanList, Class<T> clazz) { jsonReader.beginArray();
try { while (jsonReader.hasNext()) {
// 初始化目标列表(为空则创建,非空则清空) T beanTemp = clazz.newInstance();
if (beanList == null) { T bean = (T)beanTemp.readBeanFromJsonReader(jsonReader);
beanList = new ArrayList<T>(); if (bean != null) {
} else { beanList.add(bean);
beanList.clear(); //LogUtils.d(TAG, "beanList.add(bean)");
} }
}
jsonReader.endArray();
return true;
//LogUtils.d(TAG, "beanList.size() is " + Integer.toString(beanList.size()));
} catch (InstantiationException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
} catch (IllegalAccessException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
} catch (IOException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return false;
}
StringReader stringReader = new StringReader(szBeanList); @Override
JsonReader jsonReader = new JsonReader(stringReader); public String toString() {
// 创建 JsonWriter 对象
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setIndent(" ");
try {// 开始 JSON 对象
jsonWriter.beginObject();
// 写入键值对
writeThisToJsonWriter(jsonWriter);
// 结束 JSON 对象
jsonWriter.endObject();
return stringWriter.toString();
} catch (IOException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
// 获取 JSON 字符串
return "";
}
jsonReader.beginArray(); // 开始解析 JSON 数组 public static <T extends BaseBean> String toStringByBeanList(ArrayList<T> beanList) {
while (jsonReader.hasNext()) { try {
// 反射创建 Bean 实例,解析并添加到列表 StringWriter stringWriter = new StringWriter();
T beanTemp = clazz.newInstance(); JsonWriter jsonWriter = new JsonWriter(stringWriter);
T bean = (T) beanTemp.readBeanFromJsonReader(jsonReader); jsonWriter.setIndent(" ");
if (bean != null) { jsonWriter.beginArray();
beanList.add(bean); for (int i = 0; i < beanList.size(); i++) {
} // 开始 JSON 对象
} jsonWriter.beginObject();
jsonReader.endArray(); // 结束 JSON 数组解析 // 写入键值对
return true; beanList.get(i).writeThisToJsonWriter(jsonWriter);
} catch (InstantiationException | IllegalAccessException | IOException e) { // 结束 JSON 对象
// 异常日志记录 jsonWriter.endObject();
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace()); }
} jsonWriter.endArray();
return false; jsonWriter.close();
} return stringWriter.toString();
} catch (IOException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return "";
}
/**
* 重写 toString(),将 Bean 序列化为格式化的 JSON 字符串
* 调用自身序列化逻辑,生成带缩进的 JSON便于调试
* @return Bean 的 JSON 字符串;失败返回空串
*/
@Override
public String toString() {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setIndent(" "); // 设置 JSON 缩进(格式化输出)
try { public static <T extends BaseBean> T loadBean(Context context, Class<T> clazz) {
jsonWriter.beginObject(); // 开始 JSON 对象 try {
writeThisToJsonWriter(jsonWriter); // 写入 Bean 字段(子类扩展) T beanTemp = clazz.newInstance();
jsonWriter.endObject(); // 结束 JSON 对象 return loadBeanFromFile(beanTemp.getBeanJsonFilePath(context), clazz);
return stringWriter.toString(); } catch (InstantiationException e) {
} catch (IOException e) { LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace()); } catch (IllegalAccessException e) {
} LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
return ""; }
} return null;
}
/** public static <T extends BaseBean> T loadBeanFromFile(String szFilePath, Class<T> clazz) {
* 将 Bean 列表序列化为格式化的 JSON 字符串 try {
* 遍历列表,逐个序列化每个 Bean生成 JSON 数组 try {
* @param beanList 待序列化的 Bean 列表 File fTemp = new File(szFilePath);
* @return 列表的 JSON 字符串;失败返回空串 if (fTemp.exists()) {
* @param <T> 泛型约束,限定为 BaseBean 子类 T beanTemp = clazz.newInstance();String szJson = UTF8FileUtils.readStringFromFile(szFilePath);
*/ return beanTemp.parseStringToBean(szJson, clazz);
public static <T extends BaseBean> String toStringByBeanList(ArrayList<T> beanList) { }
try { } catch (InstantiationException e) {
StringWriter stringWriter = new StringWriter(); LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
JsonWriter jsonWriter = new JsonWriter(stringWriter); } catch (IllegalAccessException e) {
jsonWriter.setIndent(" "); // 格式化缩进 LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
jsonWriter.beginArray(); // 开始 JSON 数组 } catch (IOException e) {
for (int i = 0; i < beanList.size(); i++) { LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
jsonWriter.beginObject(); // 单个 Bean 开始 }
beanList.get(i).writeThisToJsonWriter(jsonWriter); // 调用 Bean 自身序列化 return null;
jsonWriter.endObject(); // 单个 Bean 结束 }
}
jsonWriter.endArray(); // 结束 JSON 数组
jsonWriter.close();
return stringWriter.toString();
} catch (IOException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return "";
}
/** public static <T extends BaseBean> boolean saveBean(Context context, T bean) {
* 从默认路径getBeanJsonFilePath加载 Bean 实例 return saveBeanToFile(bean.getBeanJsonFilePath(context), bean);
* 读取应用私有目录下的 JSON 文件,解析为目标 Bean }
* @param context 上下文(用于获取文件路径)
* @param clazz 目标 Bean 类(用于反射实例化)
* @return 加载成功的 Bean 实例;失败返回 null
* @param <T> 泛型约束,限定为 BaseBean 子类
*/
public static <T extends BaseBean> T loadBean(Context context, Class<T> clazz) {
try {
// 反射创建 Bean 实例,获取默认文件路径
T beanTemp = clazz.newInstance();
return loadBeanFromFile(beanTemp.getBeanJsonFilePath(context), clazz);
} catch (InstantiationException | IllegalAccessException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return null;
}
/** public static <T extends BaseBean> boolean saveBeanToFile(String szFilePath, T bean) {
* 从指定文件路径加载 Bean 实例 try {
* 检查文件是否存在,存在则读取 JSON 并解析为目标 Bean String szJson = bean.toString();
* @param szFilePath 目标文件路径(存储 Bean 的 JSON 文件) UTF8FileUtils.writeStringToFile(szFilePath, szJson);
* @param clazz 目标 Bean 类(用于反射实例化) return true;
* @return 加载成功的 Bean 实例;失败返回 null } catch (IOException e) {
* @param <T> 泛型约束,限定为 BaseBean 子类 LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
*/ }
public static <T extends BaseBean> T loadBeanFromFile(String szFilePath, Class<T> clazz) { return false;
try { }
File file = new File(szFilePath);
if (file.exists()) { // 检查文件是否存在
T beanTemp = clazz.newInstance();
// 读取文件 JSON 字符串,解析为 Bean
String json = UTF8FileUtils.readStringFromFile(szFilePath);
return beanTemp.parseStringToBean(json, clazz);
}
} catch (InstantiationException | IllegalAccessException | IOException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return null;
}
/** public static <T extends BaseBean> boolean loadBeanList(Context context, ArrayList<T> beanListDst, Class<T> clazz) {
* 将 Bean 保存到默认路径getBeanJsonFilePath的文件中 try {
* 序列化 Bean 为 JSON写入应用私有目录下的文件 T beanTemp = clazz.newInstance();
* @param context 上下文(用于获取文件路径) return loadBeanListFromFile(beanTemp.getBeanListJsonFilePath(context), beanListDst, clazz);
* @param bean 待保存的 Bean 实例 } catch (InstantiationException e) {} catch (IllegalAccessException e) {
* @return true保存成功false保存失败 LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
* @param <T> 泛型约束,限定为 BaseBean 子类 }
*/ return false;
public static <T extends BaseBean> boolean saveBean(Context context, T bean) { }
return saveBeanToFile(bean.getBeanJsonFilePath(context), bean);
}
/** public static <T extends BaseBean> boolean loadBeanListFromFile(String szFilePath, ArrayList<T> beanList, Class<T> clazz) {
* 将 Bean 保存到指定文件路径 try {
* 序列化 Bean 为 JSON 字符串,写入目标文件(覆盖原有内容) File fTemp = new File(szFilePath);
* @param szFilePath 目标文件路径(保存 JSON 的文件) if (fTemp.exists()) {
* @param bean 待保存的 Bean 实例 String szListJson = UTF8FileUtils.readStringFromFile(szFilePath);
* @return true保存成功false保存失败 return parseStringToBeanList(szListJson, beanList, clazz);
* @param <T> 泛型约束,限定为 BaseBean 子类 }
*/ } catch (IOException e) {
public static <T extends BaseBean> boolean saveBeanToFile(String szFilePath, T bean) { LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
try { }
// 序列化 Bean 为 JSON 字符串 return false;
String json = bean.toString(); }
// 写入文件UTF-8 编码)
UTF8FileUtils.writeStringToFile(szFilePath, json);
return true;
} catch (IOException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return false;
}
/** public static <T extends BaseBean> boolean saveBeanList(Context context, ArrayList<T> beanList, Class<T> clazz) {
* 从默认路径getBeanListJsonFilePath加载 Bean 列表 try {
* 读取应用私有目录下的列表 JSON 文件,解析并填充到目标列表 T beanTemp = clazz.newInstance();
* @param context 上下文(用于获取文件路径) return saveBeanListToFile(beanTemp.getBeanListJsonFilePath(context), beanList);
* @param beanListDst 目标列表(存储加载后的 Bean } catch (InstantiationException e) {
* @param clazz 目标 Bean 类(用于反射实例化) LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
* @return true加载成功false加载失败 } catch (IllegalAccessException e) {
* @param <T> 泛型约束,限定为 BaseBean 子类 LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
*/ }
public static <T extends BaseBean> boolean loadBeanList(Context context, ArrayList<T> beanListDst, Class<T> clazz) { return false;
try { }
// 反射创建 Bean 实例,获取默认列表文件路径
T beanTemp = clazz.newInstance();
return loadBeanListFromFile(beanTemp.getBeanListJsonFilePath(context), beanListDst, clazz);
} catch (InstantiationException | IllegalAccessException e) {
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return false;
}
/** public static <T extends BaseBean> boolean saveBeanListToFile(String szFilePath, ArrayList<T> beanList) {
* 从指定文件路径加载 Bean 列表 try {
* 检查文件是否存在,存在则读取 JSON 数组,解析并填充到目标列表 String szJson = toStringByBeanList(beanList);
* @param szFilePath 目标文件路径(存储列表 JSON 的文件) UTF8FileUtils.writeStringToFile(szFilePath, szJson);
* @param beanList 目标列表(存储加载后的 Bean //LogUtils.d(TAG, "FileUtil.writeFile beanList.size() is " + Integer.toString(beanList.size()));
* @param clazz 目标 Bean 类(用于反射实例化) return true;
* @return true加载成功false加载失败 } catch (IOException e) {
* @param <T> 泛型约束,限定为 BaseBean 子类 LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
*/ }
public static <T extends BaseBean> boolean loadBeanListFromFile(String szFilePath, ArrayList<T> beanList, Class<T> clazz) { return false;
try { }
File file = new File(szFilePath);
if (file.exists()) { // 检查文件是否存在
// 读取文件中的 JSON 字符串Bean 列表数组)
String listJson = UTF8FileUtils.readStringFromFile(szFilePath);
// 解析 JSON 字符串为 Bean 列表,填充到目标列表
return parseStringToBeanList(listJson, beanList, clazz);
}
} catch (IOException e) {
// 日志记录文件读取或解析异常
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return false;
}
/**
* 将 Bean 列表保存到默认路径getBeanListJsonFilePath的文件中
* 序列化列表为 JSON 数组,写入应用私有目录下的文件
* @param context 上下文(用于获取文件路径)
* @param beanList 待保存的 Bean 列表
* @param clazz 目标 Bean 类(用于反射获取保存路径)
* @return true保存成功false保存失败
* @param <T> 泛型约束,限定为 BaseBean 子类
*/
public static <T extends BaseBean> boolean saveBeanList(Context context, ArrayList<T> beanList, Class<T> clazz) {
try {
// 反射创建 Bean 实例,获取默认列表保存路径
T beanTemp = clazz.newInstance();
return saveBeanListToFile(beanTemp.getBeanListJsonFilePath(context), beanList);
} catch (InstantiationException | IllegalAccessException e) {
// 日志记录反射实例化异常
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return false;
}
/**
* 将 Bean 列表保存到指定文件路径
* 序列化列表为 JSON 数组字符串,写入目标文件(覆盖原有内容)
* @param szFilePath 目标文件路径(保存列表 JSON 的文件)
* @param beanList 待保存的 Bean 列表
* @return true保存成功false保存失败
* @param <T> 泛型约束,限定为 BaseBean 子类
*/
public static <T extends BaseBean> boolean saveBeanListToFile(String szFilePath, ArrayList<T> beanList) {
try {
// 序列化 Bean 列表为 JSON 字符串(数组格式)
String json = toStringByBeanList(beanList);
// 将 JSON 字符串写入文件UTF-8 编码)
UTF8FileUtils.writeStringToFile(szFilePath, json);
return true;
} catch (IOException e) {
// 日志记录文件写入或序列化异常
LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
}
return false;
}
} }

View File

@@ -1,5 +1,10 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2024/08/12 13:22:12
* @Describe 异常处理类
*/
import android.app.Activity; import android.app.Activity;
import android.app.Application; import android.app.Application;
import android.content.ActivityNotFoundException; import android.content.ActivityNotFoundException;
@@ -7,22 +12,29 @@ import android.content.ClipData;
import android.content.ClipboardManager; import android.content.ClipboardManager;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo; import android.content.pm.PackageInfo;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.res.Resources; import android.content.res.Resources;
import android.graphics.Color; import android.graphics.Color;
import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.text.SpannableString;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.HorizontalScrollView; import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView; import android.widget.ScrollView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import android.widget.Toolbar;
import cc.winboll.studio.libappbase.R;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@@ -36,515 +48,358 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:14
* @Describe * 应用全局崩溃处理类(单例逻辑)
* 核心功能:捕获应用未捕获异常,记录崩溃日志到文件,启动崩溃报告页面,
* 并通过「崩溃保险丝」机制防止重复崩溃,保障基础功能可用
*/
public final class CrashHandler { public final class CrashHandler {
/** 日志标签,用于当前类的日志输出标识 */ public static final String TAG = "CrashHandler";
public static final String TAG = "CrashHandler";
/** 崩溃报告页面标题 */ public static final String TITTLE = "CrashReport";
public static final String TITTLE = "CrashReport";
/** Intent 传递崩溃信息的键(用于向崩溃页面传递日志) */ public static final String EXTRA_CRASH_INFO = "crashInfo";
public static final String EXTRA_CRASH_INFO = "crashInfo";
/** SharedPreferences 存储键(用于记录崩溃状态) */ final static String PREFS = CrashHandler.class.getName() + "PREFS";
final static String PREFS = CrashHandler.class.getName() + "PREFS"; final static String PREFS_CRASHHANDLER_ISCRASHHAPPEN = "PREFS_CRASHHANDLER_ISCRASHHAPPEN";
/** SharedPreferences 中存储「是否发生崩溃」的键 */
final static String PREFS_CRASHHANDLER_ISCRASHHAPPEN = "PREFS_CRASHHANDLER_ISCRASHHAPPEN";
/** 崩溃保险丝状态文件路径(存储当前熔断等级) */ public static String _CrashCountFilePath;
public static String _CrashCountFilePath;
/** 系统默认的未捕获异常处理器(用于降级处理,避免 CrashHandler 自身崩溃) */ public static final UncaughtExceptionHandler DEFAULT_UNCAUGHT_EXCEPTION_HANDLER = Thread.getDefaultUncaughtExceptionHandler();
public static final UncaughtExceptionHandler DEFAULT_UNCAUGHT_EXCEPTION_HANDLER = Thread.getDefaultUncaughtExceptionHandler();
/** public static void init(Application app) {
* 初始化崩溃处理器(默认存储路径) _CrashCountFilePath = app.getExternalFilesDir("CrashHandler") + "/IsCrashHandlerCrashHappen.dat";
* 调用重载方法,崩溃日志默认存储在应用外部私有目录的 crash 文件夹下 LogUtils.d(TAG, String.format("_CrashCountFilePath %s", _CrashCountFilePath));
* @param app 全局 Application 实例(用于获取存储目录、包信息等) init(app, null);
*/ }
public static void init(Application app) {
// 初始化崩溃保险丝状态文件路径(外部存储/CrashHandler/IsCrashHandlerCrashHappen.dat
_CrashCountFilePath = app.getExternalFilesDir("CrashHandler") + "/IsCrashHandlerCrashHappen.dat";
LogUtils.d(TAG, String.format("_CrashCountFilePath %s", _CrashCountFilePath));
// 调用带目录参数的初始化方法,传入 null 使用默认路径
init(app, null);
}
/** public static void init(final Application app, final String crashDir) {
* 初始化崩溃处理器(指定日志存储目录) Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(){
* 替换系统默认的未捕获异常处理器,自定义崩溃处理逻辑
* @param app 全局 Application 实例
* @param crashDir 崩溃日志存储目录null 则使用默认路径)
*/
public static void init(final Application app, final String crashDir) {
// 设置自定义未捕获异常处理器
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
try {
// 尝试处理崩溃(捕获内部异常,避免 CrashHandler 自身崩溃)
tryUncaughtException(thread, throwable);
} catch (Throwable e) {
e.printStackTrace();
// 处理失败时,交给系统默认处理器兜底
if (DEFAULT_UNCAUGHT_EXCEPTION_HANDLER != null) {
DEFAULT_UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(thread, throwable);
}
}
}
/** @Override
* 实际处理崩溃的核心方法 public void uncaughtException(Thread thread, Throwable throwable) {
* 1. 熔断保险丝记录崩溃次数2. 收集崩溃信息3. 写入日志文件4. 启动崩溃报告页面 try {
* @param thread 发生崩溃的线程 tryUncaughtException(thread, throwable);
* @param throwable 崩溃异常对象(包含堆栈信息) } catch (Throwable e) {
*/ e.printStackTrace();
private void tryUncaughtException(Thread thread, Throwable throwable) { if (DEFAULT_UNCAUGHT_EXCEPTION_HANDLER != null)
// 触发崩溃保险丝(每次崩溃熔断一次,降低防护等级) DEFAULT_UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(thread, throwable);
AppCrashSafetyWire.getInstance().burnSafetyWire(); }
}
// 格式化崩溃发生时间(用于日志文件名和内容) private void tryUncaughtException(Thread thread, Throwable throwable) {
final String time = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss", Locale.getDefault()).format(new Date()); // 每到这里就燃烧一次保险丝
// 创建崩溃日志文件(默认路径:外部存储/crash/[时间].txt AppCrashSafetyWire.getInstance().burnSafetyWire();
File crashFile = new File(
TextUtils.isEmpty(crashDir) ? new File(app.getExternalFilesDir(null), "crash") : new File(crashDir),
"crash_" + time + ".txt"
);
// 获取应用版本信息(版本名、版本号) final String time = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss", Locale.getDefault()).format(new Date());
String versionName = "unknown"; File crashFile = new File(TextUtils.isEmpty(crashDir) ? new File(app.getExternalFilesDir(null), "crash")
long versionCode = 0; : new File(crashDir), "crash_" + time + ".txt");
try {
PackageInfo packageInfo = app.getPackageManager().getPackageInfo(app.getPackageName(), 0);
versionName = packageInfo.versionName;
// 适配 Android 9.0+API 28的版本号获取方式
versionCode = Build.VERSION.SDK_INT >= 28 ? packageInfo.getLongVersionCode() : packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException ignored) {}
// 将异常堆栈信息转换为字符串 String versionName = "unknown";
String fullStackTrace; long versionCode = 0;
{ try {
StringWriter sw = new StringWriter(); PackageInfo packageInfo = app.getPackageManager().getPackageInfo(app.getPackageName(), 0);
PrintWriter pw = new PrintWriter(sw); versionName = packageInfo.versionName;
throwable.printStackTrace(pw); // 将异常堆栈写入 PrintWriter versionCode = Build.VERSION.SDK_INT >= 28 ? packageInfo.getLongVersionCode()
fullStackTrace = sw.toString(); : packageInfo.versionCode;
pw.close(); } catch (PackageManager.NameNotFoundException ignored) {}
}
// 拼接崩溃信息(设备信息 + 应用信息 + 堆栈信息) String fullStackTrace; {
StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter();
sb.append("************* Crash Head ****************\n"); PrintWriter pw = new PrintWriter(sw);
sb.append("Time Of Crash : ").append(time).append("\n"); throwable.printStackTrace(pw);
sb.append("Device Manufacturer : ").append(Build.MANUFACTURER).append("\n"); // 设备厂商 fullStackTrace = sw.toString();
sb.append("Device Model : ").append(Build.MODEL).append("\n"); // 设备型号 pw.close();
sb.append("Android Version : ").append(Build.VERSION.RELEASE).append("\n"); // Android 版本 }
sb.append("Android SDK : ").append(Build.VERSION.SDK_INT).append("\n"); // SDK 版本
sb.append("App VersionName : ").append(versionName).append("\n"); // 应用版本名
sb.append("App VersionCode : ").append(versionCode).append("\n"); // 应用版本号
sb.append("************* Crash Head ****************\n");
sb.append("\n").append(fullStackTrace); // 拼接异常堆栈
final String errorLog = sb.toString(); StringBuilder sb = new StringBuilder();
sb.append("************* Crash Head ****************\n");
sb.append("Time Of Crash : ").append(time).append("\n");
sb.append("Device Manufacturer : ").append(Build.MANUFACTURER).append("\n");
sb.append("Device Model : ").append(Build.MODEL).append("\n");
sb.append("Android Version : ").append(Build.VERSION.RELEASE).append("\n");
sb.append("Android SDK : ").append(Build.VERSION.SDK_INT).append("\n");
sb.append("App VersionName : ").append(versionName).append("\n");
sb.append("App VersionCode : ").append(versionCode).append("\n");
sb.append("************* Crash Head ****************\n");
sb.append("\n").append(fullStackTrace);
// 将崩溃日志写入文件(忽略写入失败) String errorLog = sb.toString();
try {
writeFile(crashFile, errorLog);
} catch (IOException ignored) {}
// 启动崩溃报告页面(标签用于代码块折叠) try {
gotoCrashActiviy: { writeFile(crashFile, errorLog);
Intent intent = new Intent(); } catch (IOException ignored) {}
LogUtils.d(TAG, "gotoCrashActiviy: ");
// 根据保险丝状态选择启动的崩溃页面 gotoCrashActiviy: {
if (AppCrashSafetyWire.getInstance().isAppCrashSafetyWireOK()) { Intent intent = new Intent();
LogUtils.d(TAG, "gotoCrashActiviy: isAppCrashSafetyWireOK"); LogUtils.d(TAG, "gotoCrashActiviy: ");
// 保险丝正常启动自定义样式的崩溃报告页面GlobalCrashActivity if (AppCrashSafetyWire.getInstance().isAppCrashSafetyWireOK()) {
intent.setClass(app, GlobalCrashActivity.class); LogUtils.d(TAG, "gotoCrashActiviy: isAppCrashSafetyWireOK");
intent.putExtra(EXTRA_CRASH_INFO, errorLog); // 传递崩溃日志 intent.setClass(app, GlobalCrashActivity.class);
} else { intent.putExtra(EXTRA_CRASH_INFO, errorLog);
LogUtils.d(TAG, "gotoCrashActiviy: else"); // 如果发生了 CrashHandler 内部崩溃, 就调用基础的应用崩溃显示类
// 保险丝熔断启动基础版崩溃页面CrashActivity避免复杂页面再次崩溃 // intent.setClass(app, GlobalCrashActiviy.class);
intent.setClass(app, CrashActivity.class); // intent.putExtra(GlobalCrashActiviy.EXTRA_CRASH_INFO, errorLog);
intent.putExtra(EXTRA_CRASH_INFO, errorLog); } else {
} LogUtils.d(TAG, "gotoCrashActiviy: else");
// 正常状态调用进阶的应用崩溃显示页
intent.setClass(app, CrashActivity.class);
intent.putExtra(EXTRA_CRASH_INFO, errorLog);
}
// 设置意图标志:清除原有任务栈,创建新任务(避免回到崩溃前页面)
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK
);
try {
// 启动崩溃页面,终止当前进程(确保完全重启)
app.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
} catch (ActivityNotFoundException e) {
// 未找到崩溃页面(如未在 Manifest 注册),交给系统默认处理器
e.printStackTrace();
if (DEFAULT_UNCAUGHT_EXCEPTION_HANDLER != null) {
DEFAULT_UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(thread, throwable);
}
} catch (Exception e) {
// 其他异常,兜底处理
e.printStackTrace();
if (DEFAULT_UNCAUGHT_EXCEPTION_HANDLER != null) {
DEFAULT_UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(thread, throwable);
}
}
}
}
/** // intent.setClass(app, CrashActiviy.class);
* 将字符串内容写入文件(创建父目录、覆盖写入) // intent.putExtra(CrashActiviy.EXTRA_CRASH_INFO, errorLog);
* @param file 目标文件(包含路径)
* @param content 待写入的内容(崩溃日志)
* @throws IOException 文件创建或写入失败时抛出
*/
private void writeFile(File file, String content) throws IOException {
File parentFile = file.getParentFile();
// 父目录不存在则创建
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
file.createNewFile(); // 创建文件
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes()); // 写入内容(默认 UTF-8 编码)
try {
fos.close(); // 关闭流
} catch (IOException e) {}
}
});
}
/**
* 应用崩溃保险丝内部类(单例)
* 核心作用:限制短时间内重复崩溃,通过「熔断等级」控制崩溃页面启动策略
* 等级范围MINI1~ MAX2每次崩溃等级-1熔断后启动基础版崩溃页面
*/
public static final class AppCrashSafetyWire {
/** 单例实例volatile 保证多线程可见性) */ intent.addFlags(
private static volatile AppCrashSafetyWire _AppCrashSafetyWire; Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
);
/** 当前熔断等级1最低防护2最高防护≤0熔断 */ try {
private volatile Integer currentSafetyLevel; app.startActivity(intent);
/** 最低熔断等级1再崩溃则熔断 */ android.os.Process.killProcess(android.os.Process.myPid());
private static final int _MINI = 1; System.exit(0);
/** 最高熔断等级2初始状态 */ } catch (ActivityNotFoundException e) {
private static final int _MAX = 2; e.printStackTrace();
if (DEFAULT_UNCAUGHT_EXCEPTION_HANDLER != null)
DEFAULT_UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(thread, throwable);
} catch (Exception e) {
e.printStackTrace();
if (DEFAULT_UNCAUGHT_EXCEPTION_HANDLER != null)
DEFAULT_UNCAUGHT_EXCEPTION_HANDLER.uncaughtException(thread, throwable);
}
}
/** }
* 私有构造方法(单例模式,禁止外部实例化)
* 初始化时加载本地存储的熔断等级
*/
private AppCrashSafetyWire() {
LogUtils.d(TAG, "AppCrashSafetyWire()");
currentSafetyLevel = loadCurrentSafetyLevel();
}
/** private void writeFile(File file, String content) throws IOException {
* 获取单例实例(双重检查锁定,线程安全) File parentFile = file.getParentFile();
* @return AppCrashSafetyWire 单例 if (parentFile != null && !parentFile.exists()) {
*/ parentFile.mkdirs();
public static synchronized AppCrashSafetyWire getInstance() { }
if (_AppCrashSafetyWire == null) { file.createNewFile();
_AppCrashSafetyWire = new AppCrashSafetyWire(); FileOutputStream fos = new FileOutputStream(file);
} fos.write(content.getBytes());
return _AppCrashSafetyWire; try {
} fos.close();
} catch (IOException e) {}
}
/** });
* 设置当前熔断等级(内存中) }
* @param currentSafetyLevel 目标等级1~2
*/
public void setCurrentSafetyLevel(int currentSafetyLevel) {
this.currentSafetyLevel = currentSafetyLevel;
}
/** //
* 获取当前熔断等级(内存中) // 应用崩溃保险丝
* @return 当前等级1~2 或 null //
*/ public static final class AppCrashSafetyWire {
public int getCurrentSafetyLevel() {
return currentSafetyLevel;
}
/** volatile static AppCrashSafetyWire _AppCrashSafetyWire;
* 保存熔断等级到本地文件(持久化,重启应用生效)
* @param currentSafetyLevel 待保存的等级
*/
public void saveCurrentSafetyLevel(int currentSafetyLevel) {
LogUtils.d(TAG, "saveCurrentSafetyLevel()");
this.currentSafetyLevel = currentSafetyLevel;
try {
// 序列化等级到文件ObjectOutputStream 写入 int
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(_CrashCountFilePath));
oos.writeInt(currentSafetyLevel);
oos.flush();
oos.close();
LogUtils.d(TAG, String.format("saveCurrentSafetyLevel writeInt currentSafetyLevel %d", currentSafetyLevel));
} catch (IOException e) {
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
}
}
/** volatile Integer currentSafetyLevel; // 熔断值,为 0 表示熔断了。
* 从本地文件加载熔断等级(应用启动时初始化) private static final int _MINI = 1;
* @return 加载的等级(文件不存在则初始化为 MAX2 private static final int _MAX = 2;
*/
public int loadCurrentSafetyLevel() {
LogUtils.d(TAG, "loadCurrentSafetyLevel()");
try {
File f = new File(_CrashCountFilePath);
if (f.exists()) {
// 反序列化从文件读取等级
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(_CrashCountFilePath));
currentSafetyLevel = ois.readInt();
LogUtils.d(TAG, String.format("loadCurrentSafetyLevel() readInt currentSafetyLevel %d", currentSafetyLevel));
} else {
// 文件不存在初始化等级为最高2并保存
currentSafetyLevel = _MAX;
LogUtils.d(TAG, String.format("loadCurrentSafetyLevel() currentSafetyLevel init to _MAX->%d", _MAX));
saveCurrentSafetyLevel(currentSafetyLevel);
}
} catch (IOException e) {
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
}
return currentSafetyLevel;
}
/** AppCrashSafetyWire() {
* 熔断保险丝(每次崩溃调用,降低防护等级) LogUtils.d(TAG, "AppCrashSafetyWire()");
* @return 熔断后是否仍在防护范围内truefalse已熔断 currentSafetyLevel = loadCurrentSafetyLevel();
*/ }
boolean burnSafetyWire() {
LogUtils.d(TAG, "burnSafetyWire()");
// 加载当前等级
int safeLevel = loadCurrentSafetyLevel();
// 若在防护范围内1~2等级-1 并保存
if (isSafetyWireWorking(safeLevel)) {
LogUtils.d(TAG, "burnSafetyWire() use");
saveCurrentSafetyLevel(safeLevel - 1);
// 返回熔断后的状态
return isSafetyWireWorking(safeLevel - 1);
}
return false;
}
/** public static synchronized AppCrashSafetyWire getInstance() {
* 检查熔断等级是否在有效范围内1~2 if (_AppCrashSafetyWire == null) {
* @param safetyLevel 待检查的等级 _AppCrashSafetyWire = new AppCrashSafetyWire();
* @return true在范围内防护有效false超出范围已熔断 }
*/ return _AppCrashSafetyWire;
boolean isSafetyWireWorking(int safetyLevel) { }
LogUtils.d(TAG, "isSafetyWireOK()");
LogUtils.d(TAG, String.format("SafetyLevel %d", safetyLevel));
if (safetyLevel >= _MINI && safetyLevel <= _MAX) { public void setCurrentSafetyLevel(int currentSafetyLevel) {
LogUtils.d(TAG, String.format("In Safety Level")); this.currentSafetyLevel = currentSafetyLevel;
return true; }
}
LogUtils.d(TAG, String.format("Out of Safety Level"));
return false;
}
/** public int getCurrentSafetyLevel() {
* 立即恢复熔断等级到最高2 return currentSafetyLevel;
* 用于重启应用后重置防护状态 }
*/
void resumeToMaximumImmediately() {
LogUtils.d(TAG, "resumeToMaximumImmediately() call saveCurrentSafetyLevel(_MAX)");
AppCrashSafetyWire.getInstance().saveCurrentSafetyLevel(_MAX);
}
/** public void saveCurrentSafetyLevel(int currentSafetyLevel) {
* 关闭防护设置等级为最低1 LogUtils.d(TAG, "saveCurrentSafetyLevel()");
* 下次崩溃直接熔断 this.currentSafetyLevel = currentSafetyLevel;
*/ try {
void off() { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(_CrashCountFilePath));
LogUtils.d(TAG, "off()"); oos.writeInt(currentSafetyLevel);
saveCurrentSafetyLevel(_MINI); oos.flush();
} oos.close();
LogUtils.d(TAG, String.format("saveCurrentSafetyLevel writeInt currentSafetyLevel %d", currentSafetyLevel));
} catch (IOException e) {
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
}
}
/** public int loadCurrentSafetyLevel() {
* 检查当前保险丝是否有效(防护未熔断) LogUtils.d(TAG, "loadCurrentSafetyLevel()");
* @return true有效等级 1~2false已熔断 try {
*/ File f = new File(_CrashCountFilePath);
boolean isAppCrashSafetyWireOK() { if (f.exists()) {
LogUtils.d(TAG, "isAppCrashSafetyWireOK()"); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(_CrashCountFilePath));
currentSafetyLevel = loadCurrentSafetyLevel(); currentSafetyLevel = ois.readInt();
return isSafetyWireWorking(currentSafetyLevel); LogUtils.d(TAG, String.format("loadCurrentSafetyLevel() readInt currentSafetyLevel %d", currentSafetyLevel));
} } else {
currentSafetyLevel = _MAX;
LogUtils.d(TAG, String.format("loadCurrentSafetyLevel() currentSafetyLevel init to _MAX->%d", _MAX));
saveCurrentSafetyLevel(currentSafetyLevel);
}
} catch (IOException e) {
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
}
return currentSafetyLevel;
}
/** boolean burnSafetyWire() {
* 延迟恢复保险丝到最高等级500ms 后) LogUtils.d(TAG, "burnSafetyWire()");
* 核心作用:崩溃页面启动后,若下次即将熔断,提前恢复防护等级,避免持续崩溃 // 崩溃计数进入崩溃保险值
* @param context 上下文(用于获取主线程 Handler int safeLevel = loadCurrentSafetyLevel();
*/ if (isSafetyWireWorking(safeLevel)) {
void postResumeCrashSafetyWireHandler(final Context context) { // 如果保险丝未熔断, 就增加一次熔断值
// 主线程延迟 500ms 执行(避免页面启动时阻塞) LogUtils.d(TAG, "burnSafetyWire() use");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { saveCurrentSafetyLevel(safeLevel - 1);
@Override return isSafetyWireWorking(safeLevel - 1);
public void run() { }
LogUtils.d(TAG, "Handler run()"); return false;
// 检查:若当前等级-1 后超出防护范围(即将熔断),则恢复到最高等级 }
if (!AppCrashSafetyWire.getInstance().isSafetyWireWorking(currentSafetyLevel - 1)) {
AppCrashSafetyWire.getInstance().resumeToMaximumImmediately();
LogUtils.d(TAG, "postResumeCrashSafetyWireHandler: 恢复保险丝到最高等级");
}
}
}, 500);
}
}
/** boolean isSafetyWireWorking(int safetyLevel) {
* 基础版崩溃报告页面(保险丝熔断时启动) LogUtils.d(TAG, "isSafetyWireOK()");
* 极简实现:仅展示崩溃日志,提供复制、重启功能,避免复杂布局导致二次崩溃 //safetyLevel = _MINI;
*/ //safetyLevel = _MINI - 1;
public static final class CrashActivity extends Activity implements MenuItem.OnMenuItemClickListener { //safetyLevel = _MINI + 1;
/** 菜单标识:复制崩溃日志 */ //safetyLevel = _MAX;
private static final int MENUITEM_COPY = 0; //safetyLevel = _MAX + 1;
/** 菜单标识:重启应用 */ LogUtils.d(TAG, String.format("SafetyLevel %d", safetyLevel));
private static final int MENUITEM_RESTART = 1;
/** 崩溃日志文本(从 CrashHandler 传递过来) */ if (safetyLevel >= _MINI && safetyLevel <= _MAX) {
private String mLog; // 如果在保险值之内
LogUtils.d(TAG, String.format("In Safety Level"));
return true;
}
LogUtils.d(TAG, String.format("Out of Safety Level"));
return false;
}
@Override void resumeToMaximumImmediately() {
protected void onCreate(Bundle savedInstanceState) { LogUtils.d(TAG, "resumeToMaximumImmediately() call saveCurrentSafetyLevel(_MAX)");
super.onCreate(savedInstanceState); AppCrashSafetyWire.getInstance().saveCurrentSafetyLevel(_MAX);
// 初始化崩溃保险丝延迟恢复机制 }
AppCrashSafetyWire.getInstance().postResumeCrashSafetyWireHandler(getApplicationContext());
// 获取传递的崩溃日志 void off() {
mLog = getIntent().getStringExtra(EXTRA_CRASH_INFO); LogUtils.d(TAG, "off()");
// 设置系统默认主题(避免自定义主题冲突) saveCurrentSafetyLevel(_MINI);
setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar); }
// 动态创建布局(避免 XML 布局加载异常) boolean isAppCrashSafetyWireOK() {
setContentView: { LogUtils.d(TAG, "isAppCrashSafetyWireOK()");
// 垂直滚动视图(处理日志过长) currentSafetyLevel = loadCurrentSafetyLevel();
ScrollView contentView = new ScrollView(this); return isSafetyWireWorking(currentSafetyLevel);
contentView.setFillViewport(true); }
// 水平滚动视图(处理日志行过长) // 调用函数以启用持续崩溃保险,从而调用 CrashHandler 内部崩溃处理窗口
HorizontalScrollView hw = new HorizontalScrollView(this); void postResumeCrashSafetyWireHandler(final Context context) {
hw.setBackgroundColor(Color.GRAY); // 背景色设为灰色 new Handler(Looper.getMainLooper()).postDelayed(new Runnable(){
@Override
public void run() {
LogUtils.d(TAG, "Handler run()");
if (!AppCrashSafetyWire.getInstance().isSafetyWireWorking(currentSafetyLevel - 1)) {
// 如果下一次应用崩溃时,保险丝熔断,则先恢复保险丝满能状态
// 进程持续运行时,恢复保险丝熔断值
//Resume to maximum
AppCrashSafetyWire.getInstance().resumeToMaximumImmediately();
LogUtils.d(TAG, "postResumeCrashSafetyWireHandler");
}
}
}, 500);
}
}
// 日志显示文本框 public static final class CrashActivity extends Activity implements MenuItem.OnMenuItemClickListener {
TextView message = new TextView(this); private static final int MENUITEM_COPY = 0;
{ private static final int MENUITEM_RESTART = 1;
int padding = dp2px(16); // 内边距 16dp适配不同屏幕
message.setPadding(padding, padding, padding, padding);
message.setText(mLog); // 设置崩溃日志
message.setTextColor(Color.BLACK); // 文字黑色
message.setTextIsSelectable(true); // 支持文本选择(便于手动复制)
}
// 组装布局TextView -> HorizontalScrollView -> ScrollView private String mLog;
hw.addView(message);
contentView.addView(hw, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
// 设置当前 Activity 布局
setContentView(contentView);
// 配置 ActionBar 标题和副标题 @Override
getActionBar().setTitle(TITTLE); protected void onCreate(Bundle savedInstanceState) {
getActionBar().setSubtitle(GlobalApplication.class.getSimpleName() + " Error"); super.onCreate(savedInstanceState);
} AppCrashSafetyWire.getInstance().postResumeCrashSafetyWireHandler(getApplicationContext());
}
/** mLog = getIntent().getStringExtra(EXTRA_CRASH_INFO);
* 重写返回键逻辑:点击返回键直接重启应用 setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
*/ setContentView: {
@Override ScrollView contentView = new ScrollView(this);
public void onBackPressed() { contentView.setFillViewport(true);
restart();
}
/** HorizontalScrollView hw = new HorizontalScrollView(this);
* 重启当前应用(与 GlobalCrashActivity 逻辑一致) hw.setBackgroundColor(Color.GRAY);
* 清除任务栈,启动主 Activity终止当前进程 TextView message = new TextView(this); {
*/ int padding = dp2px(16);
private void restart() { message.setPadding(padding, padding, padding, padding);
PackageManager pm = getPackageManager(); message.setText(mLog);
// 获取应用启动意图(默认启动主 Activity message.setTextColor(Color.BLACK);
Intent intent = pm.getLaunchIntentForPackage(getPackageName()); message.setTextIsSelectable(true);
if (intent != null) { }
// 设置意图标志:清除原有任务栈,创建新任务 hw.addView(message);
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK
);
startActivity(intent);
}
// 关闭当前页面,终止进程,确保完全重启
finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
/** contentView.addView(hw, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
* dp 转 px适配不同屏幕密度 setContentView(contentView);
* @param dpValue dp 值 getActionBar().setTitle(TITTLE);
* @return 转换后的 px 值 getActionBar().setSubtitle(GlobalApplication.class.getSimpleName() + " Error");
*/ }
private int dp2px(final float dpValue) { }
final float scale = Resources.getSystem().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f); // 四舍五入确保精度
}
/** @Override
* 菜单点击事件回调(处理复制、重启) public void onBackPressed() {
* @param item 被点击的菜单项 restart();
* @return false不消费事件保持默认行为 }
*/
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case MENUITEM_COPY:
// 复制日志到剪贴板
ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cm.setPrimaryClip(ClipData.newPlainText(getPackageName(), mLog));
Toast.makeText(getApplication(), "The text is copied.", Toast.LENGTH_SHORT).show();
break;
case MENUITEM_RESTART:
// 恢复保险丝到最高等级,然后重启应用
AppCrashSafetyWire.getInstance().resumeToMaximumImmediately();
restart();
break;
}
return false;
}
/** private void restart() {
* 创建 ActionBar 菜单(添加复制、重启项) PackageManager pm = getPackageManager();
* @param menu 菜单容器 Intent intent = pm.getLaunchIntentForPackage(getPackageName());
* @return true显示菜单 if (intent != null) {
*/ intent.addFlags(
@Override Intent.FLAG_ACTIVITY_NEW_TASK
public boolean onCreateOptionsMenu(Menu menu) { | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
// 添加「复制」菜单:有空间时显示在 ActionBar否则放入溢出菜单 );
menu.add(0, MENUITEM_COPY, 0, "Copy") startActivity(intent);
.setOnMenuItemClickListener(this) }
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); finish();
// 添加「重启」菜单:同上 android.os.Process.killProcess(android.os.Process.myPid());
menu.add(0, MENUITEM_RESTART, 0, "Restart") System.exit(0);
.setOnMenuItemClickListener(this) }
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true; private int dp2px(final float dpValue) {
} final float scale = Resources.getSystem().getDisplayMetrics().density;
} return (int) (dpValue * scale + 0.5f);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case MENUITEM_COPY:
ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cm.setPrimaryClip(ClipData.newPlainText(getPackageName(), mLog));
Toast.makeText(getApplication(), "The text is copied.", Toast.LENGTH_SHORT).show();
break;
case MENUITEM_RESTART:
AppCrashSafetyWire.getInstance().resumeToMaximumImmediately();
restart();
break;
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENUITEM_COPY, 0, "Copy").setOnMenuItemClickListener(this)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(0, MENUITEM_RESTART, 0, "Restart").setOnMenuItemClickListener(this)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
}
} }

View File

@@ -1,174 +1,70 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/01/05 10:10:23
* @Describe 全局应用类
*/
import android.app.Application; import android.app.Application;
import android.content.Context; import android.content.Context;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException; import cc.winboll.studio.libappbase.GlobalApplication;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 19:56
* @Describe 全局 Application 类,用于初始化应用核心组件、管理全局状态(如调试模式)
* 需在 AndroidManifest.xml 中配置 android:name=".GlobalApplication" 使其生效
*/
public class GlobalApplication extends Application { public class GlobalApplication extends Application {
/** 日志标签 */
public static final String TAG = "GlobalApplication"; public static final String TAG = "GlobalApplication";
/** 全局 Application 单例实例volatile 保证多线程可见性,避免指令重排) */ // 应用是否处于调试状态
private static volatile GlobalApplication sInstance; volatile static boolean isDebuging = false;
/** public static void setIsDebuging(boolean isDebuging) {
* 应用调试模式标记volatile 保证多线程可见性) GlobalApplication.isDebuging = isDebuging;
* true调试模式开启日志、调试功能false正式模式关闭调试相关功能
*/
private static volatile boolean isDebugging = false;
/**
* 获取全局 Application 单例实例(外部可通过此方法获取上下文)
* @return GlobalApplication 单例(未初始化时返回 null需确保配置 AndroidManifest
*/
public static GlobalApplication getInstance() {
return sInstance;
} }
/**
* 设置应用调试模式
* @param debugging 调试模式状态true/false
*/
public static void setIsDebugging(boolean debugging) {
isDebugging = debugging;
}
/**
* 保存调试模式状态到本地文件(持久化存储,重启应用后生效)
* @param application 全局 Application 实例(通过 getInstance() 获取更规范)
*/
public static void saveDebugStatus(GlobalApplication application) { public static void saveDebugStatus(GlobalApplication application) {
if (application == null) { APPModel.saveBeanToFile(application.getAPPModelFilePath(application), new APPModel(GlobalApplication.isDebuging));
LogUtils.e(TAG, "saveDebugStatus: Application 实例为空,保存失败");
return;
}
// 将调试状态封装为 APPModel 并保存到文件
APPModel.saveBeanToFile(
getAppModelFilePath(application),
new APPModel(isDebugging)
);
} }
/** static String getAPPModelFilePath(GlobalApplication application) {
* 获取 APPModel 配置文件的存储路径
* 路径:应用私有数据目录 / APPModel.json仅当前应用可访问安全
* @param application 全局 Application 实例
* @return 配置文件绝对路径
*/
private static String getAppModelFilePath(GlobalApplication application) {
return application.getDataDir().getPath() + "/APPModel.json"; return application.getDataDir().getPath() + "/APPModel.json";
} }
/** public static boolean isDebuging() {
* 获取当前应用调试模式状态 return isDebuging;
* @return true调试模式false正式模式
*/
public static boolean isDebugging() {
return isDebugging;
} }
/**
* 应用启动时初始化(仅执行一次)
* 初始化核心框架、恢复调试状态、配置全局异常处理等
*/
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
// 初始化单例实例(确保在所有初始化操作前完成)
sInstance = this; setIsDebuging(true);
// 添加日志模块
// 初始化基础组件日志、崩溃处理、Toast
initCoreComponents();
// 恢复/初始化调试模式状态(从本地文件读取,无文件则默认关闭调试)
restoreDebugStatus();
LogUtils.d(TAG, "GlobalApplication 初始化完成,单例实例已创建");
}
/**
* 初始化应用核心组件日志、崩溃处理、Toast 框架)
*/
private void initCoreComponents() {
// 初始化日志工具(传入 Application 上下文)
LogUtils.init(this); LogUtils.init(this);
// 初始化全局异常处理器(捕获应用崩溃信息,用于调试或上报) // 设置应用异常处理窗口
CrashHandler.init(this); CrashHandler.init(this);
// 初始化 Toast 工具(统一 Toast 样式、避免内存泄漏等) // 初始化 Toast 框架
ToastUtils.init(this); ToastUtils.init(this);
}
/**
* 恢复调试模式状态(从本地配置文件读取)
* 1. 读取本地 APPModel.json 文件
* 2. 读取成功:使用保存的调试状态;读取失败(文件不存在):默认关闭调试并创建配置文件
*/
private void restoreDebugStatus() {
// 从文件加载 APPModel 实例(存储调试状态的模型类)
APPModel appModel = APPModel.loadBeanFromFile(
getAppModelFilePath(this),
APPModel.class
);
// 应用保存的调试标志
APPModel appModel = APPModel.loadBeanFromFile(getAPPModelFilePath(this), APPModel.class);
if (appModel == null) { if (appModel == null) {
// 配置文件不存在,默认关闭调试模式并创建文件 setIsDebuging(false);
setIsDebugging(false);
saveDebugStatus(this); saveDebugStatus(this);
LogUtils.d(TAG, "调试配置文件不存在,默认关闭调试模式并创建配置文件");
} else { } else {
// 配置文件存在,使用保存的调试状态 setIsDebuging(appModel.isDebuging());
setIsDebugging(appModel.isDebugging());
LogUtils.d(TAG, "从配置文件恢复调试模式:" + isDebugging);
} }
} }
/** public static String getAppName(Context context) {
* 获取应用名称(从 AndroidManifest.xml 的 android:label 读取)
* @param context 上下文(建议传入 Application 上下文,避免内存泄漏)
* @return 应用名称(读取失败返回 null
*/
public static String getAppName(Context context) {
if (context == null) {
LogUtils.w(TAG, "getAppName: 上下文为空,返回 null");
return null;
}
PackageManager packageManager = context.getPackageManager(); PackageManager packageManager = context.getPackageManager();
try { try {
// 获取应用信息(包含应用名称、图标等)
ApplicationInfo applicationInfo = packageManager.getApplicationInfo( ApplicationInfo applicationInfo = packageManager.getApplicationInfo(
context.getPackageName(), // 当前应用包名 context.getPackageName(), 0);
0 // 额外标志0 表示默认获取基本信息) return (String) packageManager.getApplicationLabel(applicationInfo);
); } catch (PackageManager.NameNotFoundException e) {
// 从应用信息中获取应用名称(支持多语言)
String appName = (String) packageManager.getApplicationLabel(applicationInfo);
LogUtils.d(TAG, "获取应用名称成功:" + appName);
return appName;
} catch (NameNotFoundException e) {
// 包名不存在(理论上不会发生,捕获异常避免崩溃)
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
//LogUtils.e(TAG, "获取应用名称失败:包名不存在", e);
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
/**
* 应用终止时调用(仅用于释放全局资源)
*/
@Override
public void onTerminate() {
super.onTerminate();
// 释放单例引用(可选,避免内存泄漏风险)
sInstance = null;
LogUtils.d(TAG, "GlobalApplication 终止,单例实例已释放");
}
} }

View File

@@ -1,5 +1,9 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/02/11 00:14:05
*/
import android.app.Activity; import android.app.Activity;
import android.content.ClipData; import android.content.ClipData;
import android.content.ClipboardManager; import android.content.ClipboardManager;
@@ -12,175 +16,79 @@ import android.view.MenuItem;
import android.widget.Toast; import android.widget.Toast;
import cc.winboll.studio.libappbase.R; import cc.winboll.studio.libappbase.R;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 19:58
* @Describe 应用异常报告观察活动窗口类
* 核心功能:应用发生未捕获崩溃时,由 CrashHandler 启动此页面,展示崩溃日志详情,
* 并提供「复制日志」「重启应用」操作入口,便于开发者定位问题和用户恢复应用
*/
public final class GlobalCrashActivity extends Activity implements MenuItem.OnMenuItemClickListener { public final class GlobalCrashActivity extends Activity implements MenuItem.OnMenuItemClickListener {
/** 日志标签(用于调试日志输出,唯一标识当前 Activity */ private static final int MENUITEM_COPY = 0;
private static final int MENUITEM_RESTART = 1;
GlobalCrashReportView mGlobalCrashReportView;
String mLog;
public static final String TAG = "GlobalCrashActivity"; public static final String TAG = "GlobalCrashActivity";
/** 菜单标识:复制崩溃日志(用于区分菜单项点击事件) */
private static final int MENU_ITEM_COPY = 0;
/** 菜单标识:重启应用(用于区分菜单项点击事件) */
private static final int MENU_ITEM_RESTART = 1;
/** 崩溃报告展示自定义视图 */
// 负责渲染崩溃日志文本、提供 Toolbar 容器,封装了日志展示和菜单样式控制逻辑
private GlobalCrashReportView mCrashReportView;
/** 崩溃日志文本内容 */
// 从 CrashHandler 通过 Intent 传递过来,包含异常堆栈、设备信息等完整崩溃数据
private String mCrashLog;
/**
* Activity 创建时初始化(生命周期核心方法,仅执行一次)
* @param savedInstanceState 保存的实例状态(崩溃页面无需恢复状态,此处仅作兼容)
*/
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
CrashHandler.AppCrashSafetyWire.getInstance().postResumeCrashSafetyWireHandler(getApplicationContext());
// 初始化崩溃安全防护机制 mLog = getIntent().getStringExtra(CrashHandler.EXTRA_CRASH_INFO);
// 作用:防止应用重启后短时间内再次崩溃,由 CrashHandler 内部实现防护逻辑 //setTheme(android.R.style.Theme_Holo_Light_NoActionBar);
CrashHandler.AppCrashSafetyWire.getInstance() //setTheme(R.style.APPBaseTheme);
.postResumeCrashSafetyWireHandler(getApplicationContext());
// 从 Intent 中获取崩溃日志数据EXTRA_CRASH_INFO 为 CrashHandler 定义的常量键)
mCrashLog = getIntent().getStringExtra(CrashHandler.EXTRA_CRASH_INFO);
// 设置当前 Activity 的布局文件(展示崩溃报告的 UI 结构)
setContentView(R.layout.activity_globalcrash); setContentView(R.layout.activity_globalcrash);
mGlobalCrashReportView = findViewById(R.id.activityglobalcrashGlobalCrashReportView1);
// 初始化崩溃报告展示视图(通过布局 ID 找到自定义 View 实例) mGlobalCrashReportView.setReport(mLog);
mCrashReportView = findViewById(R.id.activityglobalcrashGlobalCrashReportView1); setActionBar(mGlobalCrashReportView.getToolbar());
// 将崩溃日志设置到视图中,由自定义 View 负责排版和显示
mCrashReportView.setReport(mCrashLog); getActionBar().setTitle(CrashHandler.TITTLE);
getActionBar().setSubtitle(GlobalApplication.getAppName(getApplicationContext()));
// 设置页面的 ActionBar复用自定义 View 中的 Toolbar 作为系统 ActionBar
setActionBar(mCrashReportView.getToolbar());
// 配置 ActionBar 标题和副标题(非空判断避免空指针异常)
if (getActionBar() != null) {
// 设置标题:使用 CrashHandler 中定义的统一标题(如 "应用崩溃报告"
getActionBar().setTitle(CrashHandler.TITTLE);
// 设置副标题:显示当前应用名称(从全局 Application 工具方法获取)
getActionBar().setSubtitle(GlobalApplication.getAppName(getApplicationContext()));
}
} }
/**
* 重写返回键点击事件
* 逻辑:点击手机返回键时,直接重启应用(而非返回上一页,因崩溃后上一页状态可能异常)
*/
@Override @Override
public void onBackPressed() { public void onBackPressed() {
restartApp(); restart();
} }
/** private void restart() {
* 重启当前应用(核心工具方法) PackageManager pm = getPackageManager();
* 实现逻辑: Intent intent = pm.getLaunchIntentForPackage(getPackageName());
* 1. 获取应用的启动意图(默认启动 AndroidManifest 中配置的主 Activity if (intent != null) {
* 2. 设置意图标志,清除原有任务栈,避免残留异常页面 intent.addFlags(
* 3. 启动主 Activity 并终止当前进程,确保应用完全重启 Intent.FLAG_ACTIVITY_NEW_TASK
*/ | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
private void restartApp() { );
// 获取 PackageManager 实例(用于获取应用相关信息和意图) startActivity(intent);
PackageManager packageManager = getPackageManager();
// 获取应用的启动意图(参数为当前应用包名,返回主 Activity 的意图)
Intent launchIntent = packageManager.getLaunchIntentForPackage(getPackageName());
if (launchIntent != null) {
// 设置意图标志:
// FLAG_ACTIVITY_NEW_TASK创建新的任务栈启动 Activity
// FLAG_ACTIVITY_CLEAR_TOP清除目标 Activity 之上的所有 Activity
// FLAG_ACTIVITY_CLEAR_TASK清除当前任务栈中的所有 Activity
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
// 启动应用主 Activity
startActivity(launchIntent);
} }
// 关闭当前崩溃报告页面
finish(); finish();
// 终止当前应用进程(确保释放所有资源,避免内存泄漏)
android.os.Process.killProcess(android.os.Process.myPid()); android.os.Process.killProcess(android.os.Process.myPid());
// 强制退出虚拟机(彻底终止应用,防止残留线程继续运行)
System.exit(0); System.exit(0);
} }
/**
* 菜单项点击事件回调(实现 MenuItem.OnMenuItemClickListener 接口)
* @param item 被点击的菜单项实例
* @return booleantrue 表示事件已消费不再向下传递false 表示未消费
*/
@Override @Override
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
// 根据菜单项 ID 判断点击的是哪个功能
switch (item.getItemId()) { switch (item.getItemId()) {
case MENU_ITEM_COPY: case MENUITEM_COPY:
// 点击「复制」菜单,执行复制崩溃日志到剪贴板 ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
copyCrashLogToClipboard(); cm.setPrimaryClip(ClipData.newPlainText(getPackageName(), mLog));
Toast.makeText(getApplication(), "The text is copied.", Toast.LENGTH_SHORT).show();
break; break;
case MENU_ITEM_RESTART: case MENUITEM_RESTART:
// 点击「重启」菜单:先恢复崩溃防护机制到最大等级,再重启应用
CrashHandler.AppCrashSafetyWire.getInstance().resumeToMaximumImmediately(); CrashHandler.AppCrashSafetyWire.getInstance().resumeToMaximumImmediately();
restartApp(); restart();
break; break;
} }
return false; return false;
} }
/**
* 创建页面顶部菜单ActionBar 菜单)
* @param menu 菜单容器,用于添加菜单项
* @return booleantrue 表示显示菜单false 表示不显示
*/
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) { public boolean onCreateOptionsMenu(Menu menu) {
// 添加「复制」菜单项: menu.add(0, MENUITEM_COPY, 0, "Copy").setOnMenuItemClickListener(this)
// 参数说明:菜单组 ID0 表示默认组)、菜单项 IDMENU_ITEM_COPY、排序号0、菜单文本"Copy" .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
// setOnMenuItemClickListener(this):绑定点击事件到当前 Activity menu.add(0, MENUITEM_RESTART, 0, "Restart").setOnMenuItemClickListener(this)
// setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM):有空间时显示在 ActionBar 上,否则放入溢出菜单 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(0, MENU_ITEM_COPY, 0, "Copy")
.setOnMenuItemClickListener(this) // 更新菜单文字风格
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); mGlobalCrashReportView.updateMenuStyle();
// 添加「重启」菜单项(参数含义同上)
menu.add(0, MENU_ITEM_RESTART, 0, "Restart")
.setOnMenuItemClickListener(this)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
// 调用自定义视图的方法,更新菜单文字样式(如颜色、字体大小等,由自定义 View 内部实现)
mCrashReportView.updateMenuStyle();
return true; return true;
} }
/**
* 将崩溃日志复制到系统剪贴板(工具方法)
* 功能:用户点击复制菜单后,将完整崩溃日志存入剪贴板,方便粘贴到聊天工具或文档中
*/
private void copyCrashLogToClipboard() {
// 获取系统剪贴板服务(需通过 getSystemService 方法获取)
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建剪贴板数据:
// 参数 1标签用于标识剪贴板内容来源此处用应用包名
// 参数 2实际复制的文本内容崩溃日志
ClipData clipData = ClipData.newPlainText(getPackageName(), mCrashLog);
// 将数据设置到剪贴板(完成复制操作)
clipboardManager.setPrimaryClip(clipData);
// 显示复制成功的 Toast 提示(告知用户操作结果)
Toast.makeText(getApplication(), "The text is copied.", Toast.LENGTH_SHORT).show();
}
} }

View File

@@ -1,5 +1,10 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/02/11 20:18:30
* @Describe 应用崩溃报告视图
*/
import android.content.Context; import android.content.Context;
import android.content.res.TypedArray; import android.content.res.TypedArray;
import android.graphics.Color; import android.graphics.Color;
@@ -13,297 +18,121 @@ import android.widget.TextView;
import android.widget.Toolbar; import android.widget.Toolbar;
import cc.winboll.studio.libappbase.R; import cc.winboll.studio.libappbase.R;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:21
* @Describe 全局崩溃报告视图控件
* 用于展示应用崩溃信息,包含顶部工具栏和崩溃日志文本区域,支持自定义配色
*/
public class GlobalCrashReportView extends LinearLayout { public class GlobalCrashReportView extends LinearLayout {
// 日志标签 public static final String TAG = "GlobalCrashReportView";
public static final String TAG = "GlobalCrashReportView";
// 上下文对象 Context mContext;
private Context mContext; Toolbar mToolbar;
// 顶部工具栏(标题栏) int colorTittle;
private Toolbar mToolbar; int colorTittleBackground;
// 标题文字颜色 int colorText;
private int mTitleColor; int colorTextBackground;
// 标题栏背景颜色 TextView mtvReport;
private int mTitleBackgroundColor;
// 日志文本颜色
private int mTextColor;
// 日志区域背景颜色
private int mTextBackgroundColor;
// 崩溃日志显示文本控件
private TextView mTvReport;
/** public GlobalCrashReportView(Context context) {
* 构造方法:仅上下文 super(context);
* @param context 上下文 mContext = context;
*/ //initView();
public GlobalCrashReportView(Context context) { }
super(context);
mContext = context;
// 初始化默认配置(无自定义属性)
initDefaultConfig();
}
/** public GlobalCrashReportView(Context context, AttributeSet attrs) {
* 构造方法:上下文 + 自定义属性 super(context, attrs);
* @param context 上下文 mContext = context;
* @param attrs 自定义属性集合 initView(attrs);
*/ }
public GlobalCrashReportView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
// 初始化视图(解析自定义属性)
initView(attrs);
}
/** public GlobalCrashReportView(Context context, AttributeSet attrs, int defStyleAttr) {
* 构造方法:上下文 + 自定义属性 + 样式属性 super(context, attrs, defStyleAttr);
* @param context 上下文 mContext = context;
* @param attrs 自定义属性集合 //initView();
* @param defStyleAttr 样式属性 }
*/
public GlobalCrashReportView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
// 初始化视图(解析自定义属性)
initView(attrs);
}
/** public GlobalCrashReportView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
* 构造方法:上下文 + 自定义属性 + 样式属性 + 样式资源 super(context, attrs, defStyleAttr, defStyleRes);
* @param context 上下文 mContext = context;
* @param attrs 自定义属性集合 //initView();
* @param defStyleAttr 样式属性 }
* @param defStyleRes 样式资源
*/
public GlobalCrashReportView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mContext = context;
// 初始化视图(解析自定义属性)
initView(attrs);
}
/** public void setColorTittle(int colorTittle) {
* 设置标题文字颜色 this.colorTittle = colorTittle;
* @param titleColor 颜色值(如 Color.WHITE 或 #FFFFFF }
*/
public void setTitleColor(int titleColor) {
this.mTitleColor = titleColor;
// 实时更新工具栏标题颜色
if (mToolbar != null) {
mToolbar.setTitleTextColor(titleColor);
mToolbar.setSubtitleTextColor(titleColor);
}
}
/** public int getColorTittle() {
* 获取标题文字颜色 return colorTittle;
* @return 标题文字颜色值 }
*/
public int getTitleColor() {
return mTitleColor;
}
/** public void setColorTittleBackground(int colorTittleBackground) {
* 设置标题栏背景颜色 this.colorTittleBackground = colorTittleBackground;
* @param titleBackgroundColor 颜色值(如 Color.BLACK 或 #000000 }
*/
public void setTitleBackgroundColor(int titleBackgroundColor) {
this.mTitleBackgroundColor = titleBackgroundColor;
// 实时更新工具栏背景颜色
if (mToolbar != null) {
mToolbar.setBackgroundColor(titleBackgroundColor);
}
}
/** public int getColorTittleBackground() {
* 获取标题栏背景颜色 return colorTittleBackground;
* @return 标题栏背景颜色值 }
*/
public int getTitleBackgroundColor() {
return mTitleBackgroundColor;
}
/** public void setColorText(int colorText) {
* 设置日志文本颜色 this.colorText = colorText;
* @param textColor 颜色值(如 Color.BLACK 或 #000000 }
*/
public void setTextColor(int textColor) {
this.mTextColor = textColor;
// 实时更新日志文本颜色
if (mTvReport != null) {
mTvReport.setTextColor(textColor);
}
}
/** public int getColorText() {
* 获取日志文本颜色 return colorText;
* @return 日志文本颜色值 }
*/
public int getTextColor() {
return mTextColor;
}
/** public void setColorTextBackground(int colorTextBackground) {
* 设置日志区域背景颜色 this.colorTextBackground = colorTextBackground;
* @param textBackgroundColor 颜色值(如 Color.WHITE 或 #FFFFFF }
*/
public void setTextBackgroundColor(int textBackgroundColor) {
this.mTextBackgroundColor = textBackgroundColor;
// 实时更新日志区域和主布局背景颜色
if (mTvReport != null) {
mTvReport.setBackgroundColor(textBackgroundColor);
}
setBackgroundColor(textBackgroundColor);
}
/** public int getColorTextBackground() {
* 获取日志区域背景颜色 return colorTextBackground;
* @return 日志区域背景颜色值 }
*/
public int getTextBackgroundColor() {
return mTextBackgroundColor;
}
/** void initView(AttributeSet attrs) {
* 初始化默认配置(无自定义属性时使用) TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.GlobalCrashActivity, R.attr.themeGlobalCrashActivity, 0);
*/ this.colorTittle = a.getColor(R.styleable.GlobalCrashActivity_colorTittle, Color.WHITE);
private void initDefaultConfig() { this.colorTittleBackground = a.getColor(R.styleable.GlobalCrashActivity_colorTittleBackgound, Color.BLACK);
// 设置默认配色 this.colorText = a.getColor(R.styleable.GlobalCrashActivity_colorText, Color.BLACK);
mTitleColor = Color.WHITE; this.colorTextBackground = a.getColor(R.styleable.GlobalCrashActivity_colorTextBackgound, Color.WHITE);
mTitleBackgroundColor = Color.BLACK; // 返回一个绑定资源结束的信号给资源
mTextColor = Color.BLACK; a.recycle();
mTextBackgroundColor = Color.WHITE;
// 加载布局
inflateView();
// 初始化控件样式
initWidgetStyle();
}
/** /*this.colorTittle = Color.WHITE;
* 初始化视图(解析自定义属性 + 加载布局 + 设置样式) this.colorTittleBackground = Color.BLACK;
* @param attrs 自定义属性集合 this.colorText = Color.BLACK;
*/ this.colorTextBackground = Color.WHITE;
private void initView(AttributeSet attrs) { */
// 解析自定义属性(关联 attrs.xml 中的 GlobalCrashActivity 样式)
TypedArray typedArray = mContext.obtainStyledAttributes( inflate(mContext, R.layout.view_globalcrashreport, this);
attrs,
R.styleable.GlobalCrashActivity,
R.attr.themeGlobalCrashActivity,
0
);
// 读取自定义属性值(无设置时使用默认值) LinearLayout llMain = findViewById(R.id.viewglobalcrashreportLinearLayout1);
mTitleColor = typedArray.getColor( llMain.setBackgroundColor(this.colorTextBackground);
R.styleable.GlobalCrashActivity_colorTittle, mToolbar = findViewById(R.id.viewglobalcrashreportToolbar1);
Color.WHITE mToolbar.setBackgroundColor(this.colorTittleBackground);
); mToolbar.setTitleTextColor(this.colorTittle);
mTitleBackgroundColor = typedArray.getColor( mToolbar.setSubtitleTextColor(this.colorTittle);
R.styleable.GlobalCrashActivity_colorTittleBackgound, // 注原拼写错误Backgound→Background保持与 attrs.xml 一致 mtvReport = findViewById(R.id.viewglobalcrashreportTextView1);
Color.BLACK mtvReport.setTextColor(this.colorText);
); mtvReport.setBackgroundColor(this.colorTextBackground);
mTextColor = typedArray.getColor( }
R.styleable.GlobalCrashActivity_colorText,
Color.BLACK
);
mTextBackgroundColor = typedArray.getColor(
R.styleable.GlobalCrashActivity_colorTextBackgound, // 注:原拼写错误,保持与 attrs.xml 一致
Color.WHITE
);
// 回收 TypedArray避免内存泄漏 public void setReport(String report) {
typedArray.recycle(); mtvReport.setText(report);
}
// 加载布局文件 public Toolbar getToolbar() {
inflateView(); return mToolbar;
// 初始化控件样式 }
initWidgetStyle();
}
/** //
* 加载布局文件 // 更新菜单文字风格
*/ //
private void inflateView() { public void updateMenuStyle() {
// 加载自定义布局R.layout.view_globalcrashreport // 设置菜单文本颜色
inflate(mContext, R.layout.view_globalcrashreport, this); Menu menu = mToolbar.getMenu();
// 绑定控件 for (int i = 0; i < menu.size(); i++) {
mToolbar = findViewById(R.id.viewglobalcrashreportToolbar1); MenuItem item = menu.getItem(i);
mTvReport = findViewById(R.id.viewglobalcrashreportTextView1); SpannableString spanString = new SpannableString(item.getTitle().toString());
} spanString.setSpan(new ForegroundColorSpan(this.colorTittle), 0, spanString.length(), 0);
item.setTitle(spanString);
/** }
* 初始化控件样式(设置配色和基础属性) }
*/
private void initWidgetStyle() {
// 设置主布局背景颜色
setBackgroundColor(mTextBackgroundColor);
// 配置工具栏样式
if (mToolbar != null) {
mToolbar.setBackgroundColor(mTitleBackgroundColor);
mToolbar.setTitleTextColor(mTitleColor);
mToolbar.setSubtitleTextColor(mTitleColor);
}
// 配置日志文本控件样式
if (mTvReport != null) {
mTvReport.setTextColor(mTextColor);
mTvReport.setBackgroundColor(mTextBackgroundColor);
// 可选:设置日志文本换行方式(默认已换行,此处增强可读性)
mTvReport.setSingleLine(false);
mTvReport.setHorizontallyScrolling(false);
}
}
/**
* 设置崩溃报告内容到文本控件
* @param report 崩溃日志字符串(通常包含异常信息、调用栈等)
*/
public void setReport(String report) {
if (mTvReport != null) {
mTvReport.setText(report);
}
}
/**
* 获取顶部工具栏对象(用于外部设置标题、添加菜单等)
* @return Toolbar 实例
*/
public Toolbar getToolbar() {
return mToolbar;
}
/**
* 更新工具栏菜单文字颜色(与标题颜色保持一致)
* 需在菜单加载完成后调用(如 Toolbar 加载菜单后)
*/
public void updateMenuStyle() {
if (mToolbar == null) return;
// 获取工具栏菜单
Menu menu = mToolbar.getMenu();
if (menu == null || menu.size() == 0) return;
// 遍历所有菜单项,设置文字颜色
for (int i = 0; i < menu.size(); i++) {
MenuItem menuItem = menu.getItem(i);
String title = menuItem.getTitle().toString();
// 使用 SpannableString 设置文字颜色
SpannableString spanString = new SpannableString(title);
spanString.setSpan(
new ForegroundColorSpan(mTitleColor),
0,
spanString.length(),
0 // Spannable.SPAN_INCLUSIVE_EXCLUSIVE默认值包含起始位置不包含结束位置
);
menuItem.setTitle(spanString);
}
}
} }

View File

@@ -1,240 +1,129 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/03/12 12:29:01
* @Describe 水平布局的 ListView
*/
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.View; import android.view.View;
import android.widget.ListView; import android.widget.ListView;
import android.widget.Scroller; import android.widget.Scroller;
import cc.winboll.studio.libappbase.LogUtils;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:26
* @Describe 水平滚动 ListView 控件
* 继承自 ListView重写布局和测量逻辑实现子项水平排列和滚动替代默认垂直布局
*/
public class HorizontalListView extends ListView { public class HorizontalListView extends ListView {
/** 日志标签,用于当前控件的日志输出标识 */ public static final String TAG = "HorizontalListView";
public static final String TAG = "HorizontalListView"; private int verticalOffset = 0;
private Scroller scroller;
private int totalWidth;
/** 子项垂直偏移量(用于调整子项在垂直方向的位置,默认 0 */ public HorizontalListView(Context context) {
private int mVerticalOffset = 0; super(context);
/** 平滑滚动控制器(用于实现水平方向的平滑滚动动画) */ init();
private Scroller mScroller; }
/** 所有子项总宽度(包含内边距),用于计算滚动范围 */
private int mTotalWidth;
/** public HorizontalListView(Context context, AttributeSet attrs) {
* 构造方法:仅上下文 super(context, attrs);
* @param context 上下文Activity/Fragment init();
*/ }
public HorizontalListView(Context context) {
super(context);
init();
}
/** public HorizontalListView(Context context, AttributeSet attrs, int defStyle) {
* 构造方法:上下文 + 自定义属性 super(context, attrs, defStyle);
* @param context 上下文 init();
* @param attrs 自定义属性集合(如布局文件中设置的属性) }
*/
public HorizontalListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/** private void init() {
* 构造方法:上下文 + 自定义属性 + 样式属性 scroller = new Scroller(getContext());
* @param context 上下文 setHorizontalScrollBarEnabled(true);
* @param attrs 自定义属性集合 setVerticalScrollBarEnabled(false);
* @param defStyle 样式属性(如系统默认样式) }
*/
public HorizontalListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
/** public void setVerticalOffset(int verticalOffset) {
* 初始化控件配置 this.verticalOffset = verticalOffset;
* 初始化滚动控制器,设置滚动条显示状态 }
*/
private void init() {
// 初始化平滑滚动器(上下文为当前控件所在上下文)
mScroller = new Scroller(getContext());
// 启用水平滚动条(默认显示)
setHorizontalScrollBarEnabled(true);
// 禁用垂直滚动条(水平列表无需垂直滚动)
setVerticalScrollBarEnabled(false);
}
/** @Override
* 设置子项垂直偏移量 protected void onLayout(boolean changed, int l, int t, int r, int b) {
* 用于整体调整所有子项在垂直方向的位置(如居中、偏移) super.onLayout(changed, l, t, r, b);
* @param verticalOffset 垂直偏移像素值(正数向下偏移,负数向上偏移) int childCount = getChildCount();
*/ int left = getPaddingLeft();
public void setVerticalOffset(int verticalOffset) { int viewHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
this.mVerticalOffset = verticalOffset; totalWidth = left;
}
/** for (int i = 0; i < childCount; i++) {
* 重写布局方法:实现子项水平排列 View child = getChildAt(i);
* 遍历所有子项,按水平方向依次布局(左对齐,叠加排列) int width = child.getMeasuredWidth();
* @param changed 布局是否发生变化true首次布局或尺寸变化false重绘 int height = child.getMeasuredHeight();
* @param l 控件左边界坐标 child.layout(left, verticalOffset, left + width, verticalOffset + height);
* @param t 控件上边界坐标 left += width;
* @param r 控件右边界坐标 }
* @param b 控件下边界坐标 totalWidth = left + getPaddingRight();
*/ }
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b); // 执行父类布局逻辑(确保基础配置生效)
int childCount = getChildCount(); // 获取当前可见子项数量 @Override
int left = getPaddingLeft(); // 子项起始左坐标(包含控件左内边距) protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 控件可用高度(总高度 - 上下内边距) int newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
int viewHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); int newWidthMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
mTotalWidth = left; // 初始化总宽度为左内边距 super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec);
}
// 遍历子项,水平排列 @Override
for (int i = 0; i < childCount; i++) { public void computeScroll() {
View child = getChildAt(i); // 获取当前子项 if (scroller.computeScrollOffset()) {
int childWidth = child.getMeasuredWidth(); // 子项测量宽度 scrollTo(scroller.getCurrX(), scroller.getCurrY());
int childHeight = child.getMeasuredHeight(); // 子项测量高度 postInvalidate();
}
}
// 布局子项:水平方向从 left 开始,垂直方向偏移 mVerticalOffset public void smoothScrollTo(int x, int y) {
child.layout( int dx = x - getScrollX();
left, // 子项左边界 int dy = y - getScrollY();
mVerticalOffset, // 子项上边界(带垂直偏移) scroller.startScroll(getScrollX(), getScrollY(), dx, dy, 300); // 300ms平滑动画
left + childWidth, // 子项右边界(左 + 宽度) invalidate();
mVerticalOffset + childHeight // 子项下边界(偏移 + 高度) }
);
left += childWidth; // 更新下一个子项的起始左坐标 @Override
} public int computeHorizontalScrollRange() {
return totalWidth;
}
// 计算总宽度(所有子项宽度 + 左右内边距) @Override
mTotalWidth = left + getPaddingRight(); public int computeHorizontalScrollOffset() {
} return getScrollX();
}
/** @Override
* 重写测量方法:设置控件测量规则 public int computeHorizontalScrollExtent() {
* 水平方向:允许无限宽度(适应所有子项总宽度);垂直方向:自适应内容高度 return getWidth();
* @param widthMeasureSpec 父控件传递的宽度测量规格 }
* @param heightMeasureSpec 父控件传递的高度测量规格
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 重写宽度测量规则最大值Integer.MAX_VALUE >> 2 避免溢出),自适应内容
int newWidthMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
// 重写高度测量规则:同上,自适应子项高度
int newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
// 执行父类测量逻辑(使用重写后的测量规格) public void scrollToItem(int position) {
super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec); if (position < 0 || position >= getChildCount()) {
} LogUtils.d(TAG, "无效的position: " + position);
return;
}
/** View targetView = getChildAt(position);
* 重写滚动计算方法:实现平滑滚动 int targetLeft = targetView.getLeft();
* 配合 Scroller 实现水平方向的平滑滚动动画(需在滚动时调用 invalidate() 触发) int scrollX = targetLeft - getPaddingLeft();
*/
@Override
public void computeScroll() {
// 判断滚动是否正在进行Scroller 计算当前滚动位置)
if (mScroller.computeScrollOffset()) {
// 滚动到当前计算的位置x 轴水平滚动y 轴固定 0
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
// 触发重绘,持续更新滚动状态
postInvalidate();
}
}
/** // 修正最大滚动范围计算
* 平滑滚动到指定坐标 int maxScrollX = totalWidth;
* 基于 Scroller 实现水平方向的平滑滚动300ms 动画时长) scrollX = Math.max(0, Math.min(scrollX, maxScrollX));
* @param x 目标 x 轴坐标(水平滚动位置)
* @param y 目标 y 轴坐标(固定 0无需垂直滚动
*/
public void smoothScrollTo(int x, int y) {
// 计算滚动距离(目标坐标 - 当前滚动坐标)
int dx = x - getScrollX();
int dy = y - getScrollY();
// 启动平滑滚动起始坐标当前滚动位置、滚动距离、动画时长300ms // 强制重新布局和绘制
mScroller.startScroll(getScrollX(), getScrollY(), dx, dy, 300); requestLayout();
// 触发重绘,启动滚动动画 invalidateViews();
invalidate(); smoothScrollTo(scrollX, 0);
} LogUtils.d(TAG, String.format("滚动到position: %d, scrollX: %d computeHorizontalScrollRange() %d", position, scrollX, computeHorizontalScrollRange()));
}
/**
* 计算水平滚动总范围(用于滚动条显示比例) public void resetScrollToStart() {
* @return 滚动总宽度(所有子项总宽度 + 内边距) // 强制重新布局和绘制
*/ requestLayout();
@Override invalidateViews();
public int computeHorizontalScrollRange() { smoothScrollTo(0, 0);
return mTotalWidth; }
}
/**
* 计算当前水平滚动偏移量(用于滚动条位置)
* @return 当前 x 轴滚动坐标
*/
@Override
public int computeHorizontalScrollOffset() {
return getScrollX();
}
/**
* 计算水平滚动可视范围(用于滚动条大小)
* @return 控件可见宽度(当前显示区域宽度)
*/
@Override
public int computeHorizontalScrollExtent() {
return getWidth();
}
/**
* 滚动到指定位置的子项(水平方向)
* 定位目标子项,计算滚动坐标,执行平滑滚动
* @param position 子项索引(从 0 开始,仅当前可见子项有效)
*/
public void scrollToItem(int position) {
// 校验索引有效性(避免数组越界)
if (position < 0 || position >= getChildCount()) {
LogUtils.d(TAG, "无效的子项索引: " + position);
return;
}
View targetView = getChildAt(position); // 获取目标子项
int targetLeft = targetView.getLeft(); // 目标子项左边界坐标
// 计算目标滚动坐标(子项左边界 - 控件左内边距,确保子项左对齐显示)
int scrollX = targetLeft - getPaddingLeft();
// 修正滚动范围(避免超出总宽度或小于 0
int maxScrollX = mTotalWidth - getWidth(); // 最大滚动坐标(总宽度 - 控件宽度)
scrollX = Math.max(0, Math.min(scrollX, maxScrollX));
// 强制重新布局和绘制(确保子项位置正确)
requestLayout();
invalidateViews();
// 平滑滚动到目标坐标
smoothScrollTo(scrollX, 0);
// 打印滚动日志(调试用)
LogUtils.d(TAG, String.format(
"滚动到子项索引: %d, 目标滚动X: %d, 总滚动范围: %d",
position, scrollX, computeHorizontalScrollRange()
));
}
/**
* 重置滚动到起始位置(最左侧)
* 强制重新布局后,平滑滚动到 x=0 坐标
*/
public void resetScrollToStart() {
// 强制重新布局和绘制(确保滚动位置准确)
requestLayout();
invalidateViews();
// 平滑滚动到最左侧x=0y=0
smoothScrollTo(0, 0);
}
} }

View File

@@ -1,5 +1,10 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/03/25 20:34:47
* @Describe 应用日志窗口
*/
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@@ -7,59 +12,35 @@ import android.os.Bundle;
import cc.winboll.studio.libappbase.LogView; import cc.winboll.studio.libappbase.LogView;
import cc.winboll.studio.libappbase.R; import cc.winboll.studio.libappbase.R;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:29
* @Describe 应用日志展示 Activity
* 用于单独启动窗口展示应用运行日志,依赖 LogView 控件实现日志加载与显示
*/
public class LogActivity extends Activity { public class LogActivity extends Activity {
/** 日志标签,用于当前 Activity 的日志输出标识 */
public static final String TAG = "LogActivity"; public static final String TAG = "LogActivity";
/** 日志展示控件(用于加载和显示应用日志) */ LogView mLogView;
private LogView mLogView;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// 设置布局文件(包含 LogView 控件)
setContentView(R.layout.activity_log); setContentView(R.layout.activity_log);
//ToastUtils.show("LogActivity onCreate");
// 绑定布局中的 LogView 控件
mLogView = findViewById(R.id.logview); mLogView = findViewById(R.id.logview);
// 启动 LogView 日志加载(如实时刷新日志内容)
mLogView.start(); mLogView.start();
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// 恢复 Activity 时重新启动 LogView确保日志持续更新
mLogView.start(); mLogView.start();
} }
/** public static void startLogActivity(Context context) {
* 启动日志 Activity 的静态方法(外部调用入口) Intent intent = new Intent(context, LogActivity.class);
* 配置 Intent 标志,以多任务/分屏模式启动,避免与主应用任务栈冲突 // 打开多任务窗口
* @param context 上下文Activity/Fragment用于启动 Activity
*/
public static void startLogActivity(Context context) {
// 创建启动当前 Activity 的 Intent
Intent intent = new Intent(context, LogActivity.class);
// 添加 Intent 标志:支持分屏/多窗口模式API 24+
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT); intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
// 添加 Intent 标志:创建新任务栈(避免并入调用者任务栈)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 添加 Intent 标志:标记为新文档(多任务窗口中独立显示)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
// 添加 Intent 标志:允许创建多个任务实例(支持多次启动独立窗口)
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// 启动 Activity
context.startActivity(intent); context.startActivity(intent);
} }
} }

View File

@@ -1,6 +1,13 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2024/08/12 13:44:06
* @Describe LogUtils
* @Describe 应用日志类
*/
import android.content.Context; import android.content.Context;
import cc.winboll.studio.libappbase.GlobalApplication;
import dalvik.system.DexFile; import dalvik.system.DexFile;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
@@ -21,617 +28,353 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:36
* @Describe WinBoLl 应用日志管理工具类(单例逻辑)
* 核心功能日志分级控制、日志文件读写、TAG 过滤配置、应用内所有 TAG 自动扫描
* 支持 Debug/Release 模式区分存储路径,日志持久化与清理
* 适配 Java 7 语法,移除 Lambda、Stream 等 Java 8+ 特性
*/
public class LogUtils { public class LogUtils {
/** 当前工具类的日志 TAG */
public static final String TAG = "LogUtils"; public static final String TAG = "LogUtils";
/**
* 日志级别枚举(从低到高:关闭→错误→警告→信息→调试→详细)
* 级别越高,输出的日志越详细
*/
public static enum LOG_LEVEL { Off, Error, Warn, Info, Debug, Verbose } public static enum LOG_LEVEL { Off, Error, Warn, Info, Debug, Verbose }
/** 是否初始化完成标志volatile 保证多线程可见性) */ static volatile boolean _IsInited = false;
private static volatile boolean sIsInited = false; static Context _mContext;
/** 全局上下文(用于获取存储路径、包信息) */ // 日志显示时间格式
private static Context sContext; static SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("[yyyyMMdd_HHmmss_SSS]", Locale.getDefault());
/** 日志时间格式化工具(格式:[yyyyMMdd_HHmmss_SSS],精确到毫秒) */ // 应用日志文件夹
private static SimpleDateFormat sSimpleDateFormat = new SimpleDateFormat("[yyyyMMdd_HHmmss_SSS]", Locale.getDefault()); static File _mfLogCacheDir;
/** 日志缓存文件夹Debug 模式下存储在外部缓存Release 存储在内部缓存) */ static File _mfLogDataDir;
private static File sLogCacheDir; // 应用日志文件
/** 日志配置文件夹(存储 TAG 配置文件) */ static File _mfLogCatchFile;
private static File sLogDataDir; static File _mfLogUtilsBeanFile;
/** 日志存储文件(所有日志写入此文件) */ static LogUtilsBean _mLogUtilsBean;
private static File sLogFile; public static Map<String, Boolean> mapTAGList = new HashMap<String, Boolean>();
/** 日志配置文件存储日志级别、TAG 启用状态等配置) */
private static File sLogConfigFile;
/** 日志配置实体类(封装日志级别等配置) */
private static LogUtilsBean sLogConfigBean;
/** TAG 过滤映射表keyTAG 名称value是否启用该 TAG 的日志输出) */
public static Map<String, Boolean> sTagEnableMap = new HashMap<String, Boolean>();
/** //
* 初始化日志工具默认日志级别Off不输出日志 // 初始化函数
* @param context 全局上下文(建议传入 Application 实例) //
*/
public static void init(Context context) { public static void init(Context context) {
sContext = context; _mContext = context;
init(context, LOG_LEVEL.Off); init(context, LOG_LEVEL.Off);
} }
/** //
* 初始化日志工具(指定日志级别) // 初始化函数
* 1. 根据 Debug/Release 模式初始化日志存储路径; //
* 2. 加载日志配置文件;
* 3. 扫描应用内所有类的 TAG 并初始化过滤映射表;
* 4. 标记初始化完成。
* @param context 全局上下文
* @param logLevel 初始日志级别
*/
public static void init(Context context, LOG_LEVEL logLevel) { public static void init(Context context, LOG_LEVEL logLevel) {
sContext = context; if (GlobalApplication.isDebuging()) {
// 根据 Debug 模式选择存储路径(外部/内部存储) // 初始化日志缓存文件路径
if (GlobalApplication.isDebugging()) { _mfLogCacheDir = new File(context.getApplicationContext().getExternalCacheDir(), TAG);
// Debug 模式:存储在外部缓存目录(可通过文件管理器查看) if (!_mfLogCacheDir.exists()) {
sLogCacheDir = new File(context.getApplicationContext().getExternalCacheDir(), TAG); _mfLogCacheDir.mkdirs();
sLogDataDir = context.getApplicationContext().getExternalFilesDir(TAG);
} else {
// Release 模式:存储在内部缓存目录(仅应用自身可访问)
sLogCacheDir = new File(context.getApplicationContext().getCacheDir(), TAG);
sLogDataDir = new File(context.getApplicationContext().getFilesDir(), TAG);
}
// 创建日志文件夹(不存在则创建)
createDirIfNotExists(sLogCacheDir);
createDirIfNotExists(sLogDataDir);
// 初始化日志文件和配置文件路径
sLogFile = new File(sLogCacheDir, "log.txt");
sLogConfigFile = new File(sLogDataDir, TAG + ".json");
// 加载日志配置(从文件读取,读取失败则创建默认配置)
sLogConfigBean = LogUtilsBean.loadBeanFromFile(sLogConfigFile.getPath(), LogUtilsBean.class);
if (sLogConfigBean == null) {
sLogConfigBean = new LogUtilsBean();
sLogConfigBean.setLogLevel(logLevel);
// 保存默认配置到文件
sLogConfigBean.saveBeanToFile(sLogConfigFile.getPath(), sLogConfigBean);
}
// 扫描应用内所有类的 TAG 并添加到过滤映射表
scanAllClassTags();
// 加载已保存的 TAG 启用状态配置
loadTagEnableSettings();
// 标记初始化完成
sIsInited = true;
// 打印初始化日志(调试用)
d(TAG, String.format("TAG 过滤映射表初始化完成:%s", sTagEnableMap.toString()));
}
/**
* 获取 TAG 过滤映射表(外部可通过此方法获取所有 TAG 及其启用状态)
* @return TAG 名称与启用状态的映射
*/
public static Map<String, Boolean> getTagEnableMap() {
return sTagEnableMap;
}
/**
* 加载已保存的 TAG 启用状态配置
* 从 LogUtilsClassTAGBean 列表中读取每个 TAG 的启用状态,更新到映射表
*/
private static void loadTagEnableSettings() {
ArrayList<LogUtilsClassTAGBean> tagSettingList = new ArrayList<LogUtilsClassTAGBean>();
// 从文件加载 TAG 配置列表
LogUtilsClassTAGBean.loadBeanList(sContext, tagSettingList, LogUtilsClassTAGBean.class);
// 遍历配置列表,更新 TAG 启用状态Java 7 增强 for 循环)
for (LogUtilsClassTAGBean tagSetting : tagSettingList) {
String tag = tagSetting.getTag();
boolean isEnable = tagSetting.getEnable();
// 仅更新已存在的 TAG避免无效配置
if (sTagEnableMap.containsKey(tag)) {
sTagEnableMap.put(tag, isEnable);
} }
_mfLogCatchFile = new File(_mfLogCacheDir, "log.txt");
// 初始化日志配置文件路径
_mfLogDataDir = context.getApplicationContext().getExternalFilesDir(TAG);
if (!_mfLogDataDir.exists()) {
_mfLogDataDir.mkdirs();
}
_mfLogUtilsBeanFile = new File(_mfLogDataDir, TAG + ".json");
} else {
// 初始化日志缓存文件路径
_mfLogCacheDir = new File(context.getApplicationContext().getCacheDir(), TAG);
if (!_mfLogCacheDir.exists()) {
_mfLogCacheDir.mkdirs();
}
_mfLogCatchFile = new File(_mfLogCacheDir, "log.txt");
// 初始化日志配置文件路径
_mfLogDataDir = new File(context.getApplicationContext().getFilesDir(), TAG);
if (!_mfLogDataDir.exists()) {
_mfLogDataDir.mkdirs();
}
_mfLogUtilsBeanFile = new File(_mfLogDataDir, TAG + ".json");
} }
// Toast.makeText(context,
// "_mfLogUtilsBeanFile : " + _mfLogUtilsBeanFile
// + "\n_mfLogCatchFile : " + _mfLogCatchFile,
// Toast.LENGTH_SHORT).show();
//
_mLogUtilsBean = LogUtilsBean.loadBeanFromFile(_mfLogUtilsBeanFile.getPath(), LogUtilsBean.class);
if (_mLogUtilsBean == null) {
_mLogUtilsBean = new LogUtilsBean();
_mLogUtilsBean.saveBeanToFile(_mfLogUtilsBeanFile.getPath(), _mLogUtilsBean);
}
// 加载当前应用下的所有类的 TAG
addClassTAGList();
loadTAGBeanSettings();
_IsInited = true;
LogUtils.d(TAG, String.format("mapTAGList : %s", mapTAGList.toString()));
} }
/** public static Map<String, Boolean> getMapTAGList() {
* 保存当前 TAG 启用状态配置到文件 return mapTAGList;
* 将映射表中的 TAG 及其启用状态转换为 LogUtilsClassTAGBean 列表,持久化到文件
*/
private static void saveTagEnableSettings() {
ArrayList<LogUtilsClassTAGBean> tagSettingList = new ArrayList<LogUtilsClassTAGBean>();
// 遍历映射表构建配置列表Java 7 迭代器遍历)
Iterator<Map.Entry<String, Boolean>> iterator = sTagEnableMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Boolean> entry = iterator.next();
tagSettingList.add(new LogUtilsClassTAGBean(entry.getKey(), entry.getValue()));
}
// 保存配置列表到文件
LogUtilsClassTAGBean.saveBeanList(sContext, tagSettingList, LogUtilsClassTAGBean.class);
} }
/** static void loadTAGBeanSettings() {
* 扫描应用内所有类的 TAG 并添加到过滤映射表 ArrayList<LogUtilsClassTAGBean> list = new ArrayList<LogUtilsClassTAGBean>();
* 1. 通过 DexFile 读取 APK 中所有类; LogUtilsClassTAGBean.loadBeanList(_mContext, list, LogUtilsClassTAGBean.class);
* 2. 过滤指定包名前缀cc.winboll.studio的类 for (int i = 0; i < list.size(); i++) {
* 3. 反射获取类中 public static final String TAG 字段的值; LogUtilsClassTAGBean beanSetting = list.get(i);
* 4. 将 TAG 加入映射表默认禁用false for (Map.Entry<String, Boolean> entry : mapTAGList.entrySet()) {
*/ if (entry.getKey().equals(beanSetting.getTag())) {
private static void scanAllClassTags() { entry.setValue(beanSetting.getEnable());
try {
// 应用 APK 路径(通过上下文获取)
String apkPath = sContext.getPackageCodePath();
d(TAG, String.format("APK 路径:%s", apkPath));
// 读取 APK 中的所有类
DexFile dexFile = new DexFile(apkPath);
Enumeration<String> classNames = dexFile.entries();
int totalClassCount = 0; // 总类数(调试用)
List<String> targetClassNames = new ArrayList<String>(); // 目标包名下的类名列表
String targetPackagePrefix = "cc.winboll.studio"; // 目标包名前缀
// 过滤目标包名下的类Java 7 枚举遍历)
while (classNames.hasMoreElements()) {
totalClassCount++;
String className = classNames.nextElement();
if (className.startsWith(targetPackagePrefix)) {
targetClassNames.add(className);
} }
} }
// 打印扫描统计(调试用) }
d(TAG, String.format("APK 总类数:%d目标包下类数%d", totalClassCount, targetClassNames.size())); }
// 反射获取每个类的 TAG 字段Java 7 增强 for 循环) static void saveTAGBeanSettings() {
for (String className : targetClassNames) { ArrayList<LogUtilsClassTAGBean> list = new ArrayList<LogUtilsClassTAGBean>();
for (Map.Entry<String, Boolean> entry : mapTAGList.entrySet()) {
list.add(new LogUtilsClassTAGBean(entry.getKey(), entry.getValue()));
}
LogUtilsClassTAGBean.saveBeanList(_mContext, list, LogUtilsClassTAGBean.class);
}
static void addClassTAGList() {
//ClassLoader classLoader = getClass().getClassLoader();
try {
//String packageName = context.getPackageName();
String packageNamePrefix = "cc.winboll.studio";
List<String> classNames = new ArrayList<>();
String apkPath = _mContext.getPackageCodePath();
//Log.d("APK_PATH", "The APK path is: " + apkPath);
LogUtils.d(TAG, String.format("apkPath : %s", apkPath));
//String apkPath = "/data/app/" + packageName + "-";
//DexFile dexfile = new DexFile(apkPath + "1/base.apk");
DexFile dexfile = new DexFile(apkPath);
int countTemp = 0;
Enumeration<String> entries = dexfile.entries();
while (entries.hasMoreElements()) {
countTemp++;
String className = entries.nextElement();
if (className.startsWith(packageNamePrefix)) {
classNames.add(className);
}
}
LogUtils.d(TAG, String.format("countTemp : %d\nClassNames size : %d", countTemp, classNames.size()));
for (String className : classNames) {
try { try {
Class<?> clazz = Class.forName(className); Class<?> clazz = Class.forName(className);
// 获取类中所有声明的字段
Field[] fields = clazz.getDeclaredFields(); Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) { for (Field field : fields) {
// 过滤条件public static String 类型,且字段名是 "TAG" if (Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers()) && field.getType() == String.class && "TAG".equals(field.getName())) {
if (Modifier.isStatic(field.getModifiers())
&& Modifier.isPublic(field.getModifiers())
&& field.getType() == String.class
&& "TAG".equals(field.getName())) {
// 获取 TAG 字段的值(静态字段,传入 null 即可)
String tagValue = (String) field.get(null); String tagValue = (String) field.get(null);
// 添加到映射表,默认禁用 //Log.d("TAG_INFO", "Class: " + className + ", TAG value: " + tagValue);
sTagEnableMap.put(tagValue, false); //LogUtils.d(TAG, String.format("Tag Value : %s", tagValue));
//mapTAGList.put(tagValue, true);
mapTAGList.put(tagValue, false);
} }
} }
} catch (NoClassDefFoundError e) { } catch (NoClassDefFoundError | ClassNotFoundException | IllegalAccessException e) {
// 捕获反射异常,避免单个类扫描失败影响整体 LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
d(TAG, e.getMessage(), Thread.currentThread().getStackTrace()); //LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
} catch (ClassNotFoundException e) { //Toast.makeText(context, TAG + " : " + e.getMessage(), Toast.LENGTH_SHORT).show();
d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
} catch (IllegalAccessException e) {
d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
} }
} }
} catch (IOException e) { } catch (IOException e) {
// 捕获 APK 读取异常 LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
d(TAG, e, Thread.currentThread().getStackTrace()); //Toast.makeText(context, TAG + " : " + e.getMessage(), Toast.LENGTH_SHORT).show();
} }
} }
/** public static void setTAGListEnable(String tag, boolean isEnable) {
* 设置单个 TAG 的启用状态 Iterator<Map.Entry<String, Boolean>> iterator = mapTAGList.entrySet().iterator();
* @param tag TAG 名称
* @param isEnable 是否启用true输出该 TAG 的日志false不输出
*/
public static void setTagEnable(String tag, boolean isEnable) {
// 遍历映射表,更新目标 TAG 的状态Java 7 迭代器遍历)
Iterator<Map.Entry<String, Boolean>> iterator = sTagEnableMap.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry<String, Boolean> entry = iterator.next(); Map.Entry<String, Boolean> entry = iterator.next();
if (tag.equals(entry.getKey())) { if (tag.equals(entry.getKey())) {
entry.setValue(isEnable); entry.setValue(isEnable);
//System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
break; break;
} }
} }
// 保存配置到文件(持久化) saveTAGBeanSettings();
saveTagEnableSettings(); LogUtils.d(TAG, String.format("mapTAGList : %s", mapTAGList.toString()));
d(TAG, String.format("TAG 配置更新:%s", sTagEnableMap.toString()));
} }
/** public static void setALlTAGListEnable(boolean isEnable) {
* 设置所有 TAG 的启用状态(批量控制) Iterator<Map.Entry<String, Boolean>> iterator = mapTAGList.entrySet().iterator();
* @param isEnable 是否启用true所有 TAG 均输出日志false所有 TAG 均不输出)
*/
public static void setAllTagsEnable(boolean isEnable) {
// 遍历映射表,批量更新所有 TAG 的状态Java 7 迭代器遍历)
Iterator<Map.Entry<String, Boolean>> iterator = sTagEnableMap.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry<String, Boolean> entry = iterator.next(); Map.Entry<String, Boolean> entry = iterator.next();
entry.setValue(isEnable); entry.setValue(isEnable);
//System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
} }
// 保存配置到文件(持久化) saveTAGBeanSettings();
saveTagEnableSettings(); LogUtils.d(TAG, String.format("mapTAGList : %s", mapTAGList.toString()));
d(TAG, String.format("所有 TAG 配置更新:%s", sTagEnableMap.toString()));
} }
/**
* 设置全局日志级别(控制日志输出的详细程度)
* @param logLevel 目标日志级别
*/
public static void setLogLevel(LOG_LEVEL logLevel) { public static void setLogLevel(LOG_LEVEL logLevel) {
if (sLogConfigBean != null) { LogUtils._mLogUtilsBean.setLogLevel(logLevel);
sLogConfigBean.setLogLevel(logLevel); _mLogUtilsBean.saveBeanToFile(_mfLogUtilsBeanFile.getPath(), _mLogUtilsBean);
// 保存配置到文件(持久化)
sLogConfigBean.saveBeanToFile(sLogConfigFile.getPath(), sLogConfigBean);
}
} }
/**
* 获取当前全局日志级别
* @return 当前日志级别
*/
public static LOG_LEVEL getLogLevel() { public static LOG_LEVEL getLogLevel() {
return sLogConfigBean != null ? sLogConfigBean.getLogLevel() : LOG_LEVEL.Off; return LogUtils._mLogUtilsBean.getLogLevel();
} }
/** static boolean isLoggable(String tag, LOG_LEVEL logLevel) {
* 判断当前日志是否可输出校验初始化状态、TAG 启用状态、日志级别) if (!_IsInited) {
* @param tag 日志 TAG
* @param logLevel 日志级别
* @return true可输出false不可输出
*/
private static boolean isLoggable(String tag, LOG_LEVEL logLevel) {
// 未初始化:不输出
if (!sIsInited) {
return false; return false;
} }
// TAG 未配置或未启用:不输出 if (mapTAGList.get(tag) == null
if (sTagEnableMap.get(tag) == null || !sTagEnableMap.get(tag)) { || !mapTAGList.get(tag)) {
return false; return false;
} }
// 日志级别未达到:不输出 if (!isInTheLevel(logLevel)) {
if (!isLevelMatched(logLevel)) {
return false; return false;
} }
return true; return true;
} }
/** static boolean isInTheLevel(LOG_LEVEL logLevel) {
* 判断日志级别是否匹配(当前全局级别 >= 目标级别时可输出) return (LogUtils._mLogUtilsBean.getLogLevel().ordinal() == logLevel.ordinal()
* 例:全局级别为 Debug4则 Error1、Warn2、Info3、Debug4均可输出 || LogUtils._mLogUtilsBean.getLogLevel().ordinal() > logLevel.ordinal());
* @param logLevel 目标日志级别
* @return true级别匹配false不匹配
*/
private static boolean isLevelMatched(LOG_LEVEL logLevel) {
if (sLogConfigBean == null) {
return false;
}
// 枚举的 ordinal() 方法返回索引Off=0Error=1...Verbose=5
return sLogConfigBean.getLogLevel().ordinal() >= logLevel.ordinal();
} }
/** //
* 获取日志缓存文件夹路径(外部可通过此方法获取日志存储目录) // 获取应用日志文件夹
* @return 日志缓存文件夹 //
*/
public static File getLogCacheDir() { public static File getLogCacheDir() {
return sLogCacheDir; return _mfLogCacheDir;
} }
/** //
* 输出 Error 级别日志 // 调试日志写入函数
* @param tag TAG 名称 //
* @param message 日志内容 public static void e(String szTAG, String szMessage) {
*/ if (isLoggable(szTAG, LogUtils.LOG_LEVEL.Error)) {
public static void e(String tag, String message) { saveLog(szTAG, LogUtils.LOG_LEVEL.Error, szMessage);
if (isLoggable(tag, LOG_LEVEL.Error)) {
saveLog(tag, LOG_LEVEL.Error, message);
} }
} }
/** //
* 输出 Error 级别日志(带异常信息和调用栈) // 调试日志写入函数
* 错误级别专用,包含完整异常详情,便于错误定位和排查 //
* @param tag TAG 名称 public static void w(String szTAG, String szMessage) {
* @param message 日志内容 if (isLoggable(szTAG, LogUtils.LOG_LEVEL.Warn)) {
* @param e 异常对象(存储异常信息和调用栈) saveLog(szTAG, LogUtils.LOG_LEVEL.Warn, szMessage);
*/
public static void e(String tag, String message, Exception e) {
if (isLoggable(tag, LOG_LEVEL.Error)) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StringBuilder sb = new StringBuilder(message);
// 拼接异常信息(类型 + 消息)
sb.append(" \nException: ")
.append(e.getClass().getSimpleName())
.append(" : ")
.append(e.getMessage() != null ? e.getMessage() : "无异常消息");
// 拼接调用栈信息stackTrace[2] 为实际调用处)
sb.append(" \nAt ")
.append(stackTrace[2].getMethodName())
.append(" (")
.append(stackTrace[2].getFileName())
.append(":")
.append(stackTrace[2].getLineNumber())
.append(")");
saveLog(tag, LOG_LEVEL.Error, sb.toString());
} }
} }
/** //
* 输出 Warn 级别日志 // 调试日志写入函数
* @param tag TAG 名称 //
* @param message 日志内容 public static void i(String szTAG, String szMessage) {
*/ if (isLoggable(szTAG, LogUtils.LOG_LEVEL.Info)) {
public static void w(String tag, String message) { saveLog(szTAG, LogUtils.LOG_LEVEL.Info, szMessage);
if (isLoggable(tag, LOG_LEVEL.Warn)) {
saveLog(tag, LOG_LEVEL.Warn, message);
} }
} }
/** //
* 输出 Warn 级别日志(带异常信息和调用栈) // 调试日志写入函数
* 包含日志内容、异常详情、调用位置,便于警告场景下的问题定位 //
* @param tag TAG 名称 public static void d(String szTAG, String szMessage) {
* @param message 日志内容 if (isLoggable(szTAG, LogUtils.LOG_LEVEL.Debug)) {
* @param e 异常对象(存储异常信息和调用栈) saveLog(szTAG, LogUtils.LOG_LEVEL.Debug, szMessage);
*/
public static void w(String tag, String message, Exception e) {
if (isLoggable(tag, LOG_LEVEL.Warn)) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StringBuilder sb = new StringBuilder(message);
// 拼接异常信息(类型 + 消息)
sb.append(" \nException: ")
.append(e.getClass().getSimpleName())
.append(" : ")
.append(e.getMessage() != null ? e.getMessage() : "无异常消息");
// 拼接调用栈信息stackTrace[2] 为实际调用处)
sb.append(" \nAt ")
.append(stackTrace[2].getMethodName())
.append(" (")
.append(stackTrace[2].getFileName())
.append(":")
.append(stackTrace[2].getLineNumber())
.append(")");
saveLog(tag, LOG_LEVEL.Warn, sb.toString());
} }
} }
/** //
* 输出 Info 级别日志 // 调试日志写入函数
* @param tag TAG 名称 // 包含线程调试堆栈信息
* @param message 日志内容 //
*/ public static void d(String szTAG, String szMessage, StackTraceElement[] listStackTrace) {
public static void i(String tag, String message) { if (isLoggable(szTAG, LogUtils.LOG_LEVEL.Debug)) {
if (isLoggable(tag, LOG_LEVEL.Info)) { StringBuilder sbMessage = new StringBuilder(szMessage);
saveLog(tag, LOG_LEVEL.Info, message); sbMessage.append(" \nAt ");
sbMessage.append(listStackTrace[2].getMethodName());
sbMessage.append(" (");
sbMessage.append(listStackTrace[2].getFileName());
sbMessage.append(":");
sbMessage.append(listStackTrace[2].getLineNumber());
sbMessage.append(")");
saveLog(szTAG, LogUtils.LOG_LEVEL.Debug, sbMessage.toString());
} }
} }
/** //
* 输出 Debug 级别日志(基础版) // 调试日志写入函数
* @param tag TAG 名称 // 包含异常信息和线程调试堆栈信息
* @param message 日志内容 //
*/ public static void d(String szTAG, Exception e, StackTraceElement[] listStackTrace) {
public static void d(String tag, String message) { if (isLoggable(szTAG, LogUtils.LOG_LEVEL.Debug)) {
if (isLoggable(tag, LOG_LEVEL.Debug)) { StringBuilder sbMessage = new StringBuilder(e.getClass().toGenericString());
saveLog(tag, LOG_LEVEL.Debug, message); sbMessage.append(" : ");
sbMessage.append(e.getMessage());
sbMessage.append(" \nAt ");
sbMessage.append(listStackTrace[2].getMethodName());
sbMessage.append(" (");
sbMessage.append(listStackTrace[2].getFileName());
sbMessage.append(":");
sbMessage.append(listStackTrace[2].getLineNumber());
sbMessage.append(")");
saveLog(szTAG, LogUtils.LOG_LEVEL.Debug, sbMessage.toString());
} }
} }
/** //
* 输出 Debug 级别日志(带调用栈信息) // 调试日志写入函数
* 包含调用方法名、文件名、行号,便于调试定位 //
* @param tag TAG 名称 public static void v(String szTAG, String szMessage) {
* @param message 日志内容 if (isLoggable(szTAG, LogUtils.LOG_LEVEL.Verbose)) {
* @param stackTrace 线程调用栈(通常传入 Thread.currentThread().getStackTrace() saveLog(szTAG, LogUtils.LOG_LEVEL.Verbose, szMessage);
*/
public static void d(String tag, String message, StackTraceElement[] stackTrace) {
if (isLoggable(tag, LOG_LEVEL.Debug)) {
StringBuilder sb = new StringBuilder(message);
// 拼接调用栈信息stackTrace[2] 为实际调用处)
sb.append(" \nAt ")
.append(stackTrace[2].getMethodName())
.append(" (")
.append(stackTrace[2].getFileName())
.append(":")
.append(stackTrace[2].getLineNumber())
.append(")");
saveLog(tag, LOG_LEVEL.Debug, sb.toString());
} }
} }
/** //
* 输出 Debug 级别日志(带异常信息和调用栈) // 日志文件保存函数
* 包含异常类型、异常信息、调用位置,便于异常定位 //
* @param tag TAG 名称 static void saveLog(String szTAG, LogUtils.LOG_LEVEL logLevel, String szMessage) {
* @param e 异常对象
* @param stackTrace 线程调用栈
*/
public static void d(String tag, Exception e, StackTraceElement[] stackTrace) {
if (isLoggable(tag, LOG_LEVEL.Debug)) {
StringBuilder sb = new StringBuilder();
// 拼接异常信息
sb.append(e.getClass().getSimpleName())
.append(" : ")
.append(e.getMessage() != null ? e.getMessage() : "无异常消息")
// 拼接调用栈信息
.append(" \nAt ")
.append(stackTrace[2].getMethodName())
.append(" (")
.append(stackTrace[2].getFileName())
.append(":")
.append(stackTrace[2].getLineNumber())
.append(")");
saveLog(tag, LOG_LEVEL.Debug, sb.toString());
}
}
/**
* 输出 Debug 级别日志(带日志内容+异常对象,简化调用)
* 无需手动传入调用栈,内部自动获取,适配常见调试场景
* @param tag TAG 名称
* @param message 日志内容
* @param e 异常对象(存储异常信息和调用栈)
*/
public static void d(String tag, String message, Exception e) {
if (isLoggable(tag, LOG_LEVEL.Debug)) {
// 自动获取当前线程调用栈,简化外部调用
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StringBuilder sb = new StringBuilder(message);
// 拼接异常信息(类型 + 消息)
sb.append(" \nException: ")
.append(e.getClass().getSimpleName())
.append(" : ")
.append(e.getMessage() != null ? e.getMessage() : "无异常消息");
// 拼接调用栈信息stackTrace[2] 为实际调用处)
sb.append(" \nAt ")
.append(stackTrace[2].getMethodName())
.append(" (")
.append(stackTrace[2].getFileName())
.append(":")
.append(stackTrace[2].getLineNumber())
.append(")");
saveLog(tag, LOG_LEVEL.Debug, sb.toString());
}
}
/**
* 输出 Verbose 级别日志(最详细级别)
* @param tag TAG 名称
* @param message 日志内容
*/
public static void v(String tag, String message) {
if (isLoggable(tag, LOG_LEVEL.Verbose)) {
saveLog(tag, LOG_LEVEL.Verbose, message);
}
}
/**
* 核心日志保存方法(将日志写入文件)
* 日志格式:[级别] [时间戳] [TAG]
* 日志内容
* @param tag TAG 名称
* @param logLevel 日志级别
* @param message 日志内容
*/
private static void saveLog(String tag, LOG_LEVEL logLevel, String message) {
BufferedWriter writer = null;
try { try {
// 以追加模式打开日志文件UTF-8 编码 BufferedWriter out = null;
writer = new BufferedWriter( out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(_mfLogCatchFile, true), "UTF-8"));
new OutputStreamWriter( out.write("[" + logLevel + "] " + mSimpleDateFormat.format(System.currentTimeMillis()) + " [" + szTAG + "]\n" + szMessage + "\n");
new FileOutputStream(sLogFile, true), out.close();
"UTF-8"
)
);
// 拼接日志内容(级别 + 时间 + TAG + 消息)
String logContent = String.format(
"[%s] %s [%s]\n%s\n",
logLevel.name(), // 日志级别(如 Debug
sSimpleDateFormat.format(System.currentTimeMillis()), // 时间戳
tag, // TAG 名称
message // 日志内容
);
// 写入文件
writer.write(logContent);
} catch (IOException e) { } catch (IOException e) {
// 日志写入失败时,输出内部调试日志 LogUtils.d(TAG, "IOException : " + e.getMessage());
d(TAG, "日志写入失败:" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
} finally {
// 关闭流避免资源泄漏Java 7 手动关闭,不使用 try-with-resources
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
} }
/** //
* 加载历史日志(读取日志文件所有内容) // 历史日志加载函数
* @return 历史日志字符串(空字符串表示文件不存在或读取失败) //
*/
public static String loadLog() { public static String loadLog() {
// 日志文件不存在,返回空 if (_mfLogCatchFile.exists()) {
if (sLogFile == null || !sLogFile.exists()) { StringBuffer sb = new StringBuffer();
return ""; try {
} BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(new FileInputStream(_mfLogCatchFile), "UTF-8"));
StringBuilder logContent = new StringBuilder(); String line = "";
BufferedReader reader = null; while ((line = in.readLine()) != null) {
try { sb.append(line);
// 以 UTF-8 编码读取日志文件 sb.append("\n");
reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(sLogFile),
"UTF-8"
)
);
String line;
// 逐行读取并拼接Java 7 普通 while 循环)
while ((line = reader.readLine()) != null) {
logContent.append(line).append("\n");
}
} catch (IOException e) {
// 读取失败时,输出内部调试日志
d(TAG, "日志读取失败:" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
} finally {
// 关闭流,避免资源泄漏
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
} }
} } catch (IOException e) {
LogUtils.d(TAG, "IOException : " + e.getMessage());
}
return sb.toString();
} }
return logContent.toString(); return "";
} }
/** //
* 清理历史日志(清空日志文件内容) // 清理日志函数
*/ //
public static void cleanLog() { public static void cleanLog() {
if (sLogFile == null || !sLogFile.exists()) { if (_mfLogCatchFile.exists()) {
return; try {
} UTF8FileUtils.writeStringToFile(_mfLogCatchFile.getPath(), "");
//LogUtils.d(TAG, "cleanLog");
try { } catch (IOException e) {
// 写入空字符串到文件实现清空Java 7 手动处理流) LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
BufferedWriter writer = new BufferedWriter( }
new OutputStreamWriter(
new FileOutputStream(sLogFile),
"UTF-8"
)
);
writer.write("");
writer.close();
} catch (IOException e) {
// 清空失败时,输出内部调试日志(带调用栈)
d(TAG, e, Thread.currentThread().getStackTrace());
}
}
/**
* 辅助方法:创建文件夹(不存在则创建)
* @param dir 目标文件夹
*/
private static void createDirIfNotExists(File dir) {
if (dir != null && !dir.exists()) {
dir.mkdirs();
} }
} }
} }

View File

@@ -1,131 +1,70 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
import android.util.JsonReader;
import android.util.JsonWriter;
import java.io.IOException;
/** /**
* @Author ZhanGSKen<zhangsken@qq.com> * @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2024/08/23 15:39:07 * @Date 2024/08/23 15:39:07
* @Describe LogUtils 配置数据模型(继承 BaseBean实现 JSON 序列化/反序列化) * @Describe LogUtils 数据配置类。
* 封装 LogUtils 的核心配置参数(当前仅日志级别),用于配置的持久化存储与读取
*/ */
import android.util.JsonReader;
import android.util.JsonWriter;
import java.io.IOException;
public class LogUtilsBean extends BaseBean { public class LogUtilsBean extends BaseBean {
/** 当前类的日志 TAG用于调试输出 */
public static final String TAG = "LogUtilsBean"; public static final String TAG = "LogUtilsBean";
/** LogUtils.LOG_LEVEL logLevel;
* 全局日志级别默认值Off即不输出任何日志
* 关联 LogUtils.LOG_LEVEL 枚举,存储日志输出的级别阈值
*/
private LogUtils.LOG_LEVEL logLevel;
/**
* 无参构造方法(默认初始化日志级别为 Off
* 用于 JSON 反序列化时的实例创建
*/
public LogUtilsBean() { public LogUtilsBean() {
this.logLevel = LogUtils.LOG_LEVEL.Off; this.logLevel = LogUtils.LOG_LEVEL.Off;
} }
/**
* 有参构造方法(指定初始日志级别)
* @param logLevel 初始日志级别(如 LogUtils.LOG_LEVEL.Debug
*/
public LogUtilsBean(LogUtils.LOG_LEVEL logLevel) { public LogUtilsBean(LogUtils.LOG_LEVEL logLevel) {
this.logLevel = logLevel; this.logLevel = logLevel;
} }
/**
* 设置日志级别(更新配置时使用)
* @param logLevel 目标日志级别
*/
public void setLogLevel(LogUtils.LOG_LEVEL logLevel) { public void setLogLevel(LogUtils.LOG_LEVEL logLevel) {
this.logLevel = logLevel; this.logLevel = logLevel;
} }
/**
* 获取当前日志级别(读取配置时使用)
* @return 当前配置的日志级别
*/
public LogUtils.LOG_LEVEL getLogLevel() { public LogUtils.LOG_LEVEL getLogLevel() {
return logLevel; return logLevel;
} }
/**
* 重写父类方法:获取当前类的全限定名(用于 BaseBean 反射识别)
* @return 类全限定名(如 "cc.winboll.studio.libappbase.LogUtilsBean"
*/
@Override @Override
public String getName() { public String getName() {
return LogUtilsBean.class.getName(); return LogUtilsBean.class.getName();
} }
/**
* 重写父类方法:将当前配置对象序列化为 JSON持久化存储时调用
* 序列化字段logLevel存储枚举的 ordinal 值,确保反序列化一致性)
* @param jsonWriter JSON 写入器(用于输出 JSON 数据)
* @throws IOException JSON 写入异常(如流关闭、格式错误)
*/
@Override @Override
public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException { public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException {
// 调用父类序列化逻辑(若 BaseBean 有公共字段,需优先处理)
super.writeThisToJsonWriter(jsonWriter); super.writeThisToJsonWriter(jsonWriter);
// 序列化日志级别:存储枚举的索引值(如 Off=0、Error=1...),比存储名称更高效 LogUtilsBean bean = this;
jsonWriter.name("logLevel").value(this.getLogLevel().ordinal()); jsonWriter.name("logLevel").value(bean.getLogLevel().ordinal());
} }
/**
* 重写父类方法:从 JSON 字段初始化当前对象(读取配置时调用)
* 解析字段logLevel通过索引值恢复 LogUtils.LOG_LEVEL 枚举)
* @param jsonReader JSON 读取器(用于读取 JSON 数据)
* @param name JSON 字段名(当前解析的字段)
* @return true字段解析成功false字段不匹配需父类处理或跳过
* @throws IOException JSON 读取异常(如字段类型不匹配、流中断)
*/
@Override @Override
public boolean initObjectsFromJsonReader(JsonReader jsonReader, String name) throws IOException { public boolean initObjectsFromJsonReader(JsonReader jsonReader, String name) throws IOException {
// 先让父类处理公共字段,处理成功则直接返回 if (super.initObjectsFromJsonReader(jsonReader, name)) { return true; } else {
if (super.initObjectsFromJsonReader(jsonReader, name)) { if (name.equals("logLevel")) {
return true; setLogLevel(LogUtils.LOG_LEVEL.values()[jsonReader.nextInt()]);
} else {
return false;
}
} }
// 解析当前类专属字段
if ("logLevel".equals(name)) {
// 通过枚举索引值恢复枚举实例(确保与序列化时的 ordinal 对应)
int levelOrdinal = jsonReader.nextInt();
this.setLogLevel(LogUtils.LOG_LEVEL.values()[levelOrdinal]);
} else {
// 字段不匹配,返回 false 表示需要跳过该字段
return false;
}
// 字段解析成功
return true; return true;
} }
/**
* 重写父类方法:从 JSON 读取器完整解析配置对象(入口方法)
* 负责 JSON 对象的开始/结束解析,遍历所有字段并调用 initObjectsFromJsonReader 处理
* @param jsonReader JSON 读取器(传入待解析的 JSON 流)
* @return 解析后的当前 LogUtilsBean 实例(支持链式调用)
* @throws IOException JSON 解析异常(如格式错误、字段缺失)
*/
@Override @Override
public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException { public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException {
// 开始解析 JSON 对象(必须与 writeThisToJsonWriter 中的结构对应)
jsonReader.beginObject(); jsonReader.beginObject();
// 遍历 JSON 中的所有字段
while (jsonReader.hasNext()) { while (jsonReader.hasNext()) {
String fieldName = jsonReader.nextName(); String name = jsonReader.nextName();
// 解析字段,若字段不匹配则跳过该值(避免解析失败) if (!initObjectsFromJsonReader(jsonReader, name)) {
if (!this.initObjectsFromJsonReader(jsonReader, fieldName)) {
jsonReader.skipValue(); jsonReader.skipValue();
} }
} }
// 结束 JSON 对象解析(必须调用,否则会导致流异常) // 结束 JSON 对象
jsonReader.endObject(); jsonReader.endObject();
// 返回当前实例,支持链式调用(如 new LogUtilsBean().readBeanFromJsonReader(reader)
return this; return this;
} }
} }

View File

@@ -1,161 +1,87 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
import android.util.JsonReader;
import android.util.JsonWriter;
import java.io.IOException;
/** /**
* @Author ZhanGSKen<zhangsken@qq.com> * @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/01/04 14:17:02 * @Date 2025/01/04 14:17:02
* @Describe 日志 TAG 过滤配置模型(继承 BaseBean实现 JSON 序列化/反序列化) * @Describe 日志类class TAG 标签数据类
* 封装单个日志 TAG 的名称及其启用状态,用于 LogUtils 的 TAG 过滤规则持久化存储与读取
*/ */
import android.util.JsonReader;
import android.util.JsonWriter;
import java.io.IOException;
public class LogUtilsClassTAGBean extends BaseBean { public class LogUtilsClassTAGBean extends BaseBean {
/** 当前类的日志 TAG用于调试输出 */
public static final String TAG = "LogUtilsClassTAGBean"; public static final String TAG = "LogUtilsClassTAGBean";
/** // 标签名
* 日志 TAG 名称(如 "LogViewThread"、"ToastUtils" String tag;
* 与 LogUtils 中扫描的应用内 TAG 一一对应 // 是否启用
*/ Boolean enable;
private String tag;
/**
* TAG 启用状态(控制该 TAG 的日志是否输出)
* true启用输出该 TAG 的日志false禁用不输出该 TAG 的日志)
*/
private Boolean enable;
/**
* 无参构造方法默认初始化TAG 为当前类 TAG启用状态为 true
* 用于 JSON 反序列化时的实例创建,或默认配置生成
*/
public LogUtilsClassTAGBean() { public LogUtilsClassTAGBean() {
this.tag = TAG; // 默认 TAG 为当前类的 TAG this.tag = TAG;
this.enable = true; // 默认启用该 TAG 的日志输出 this.enable = true;
} }
/**
* 有参构造方法(指定 TAG 名称和启用状态)
* 用于主动创建 TAG 过滤配置实例
* @param tag 日志 TAG 名称
* @param enable TAG 启用状态true/false
*/
public LogUtilsClassTAGBean(String tag, Boolean enable) { public LogUtilsClassTAGBean(String tag, Boolean enable) {
this.tag = tag; this.tag = tag;
this.enable = enable; this.enable = enable;
} }
/**
* 设置日志 TAG 名称
* @param tag 目标 TAG 名称
*/
public void setTag(String tag) { public void setTag(String tag) {
this.tag = tag; this.tag = tag;
} }
/**
* 获取日志 TAG 名称
* @return 当前配置的 TAG 名称
*/
public String getTag() { public String getTag() {
return tag; return tag;
} }
/**
* 设置 TAG 启用状态
* @param enable 目标启用状态true启用false禁用
*/
public void setEnable(Boolean enable) { public void setEnable(Boolean enable) {
this.enable = enable; this.enable = enable;
} }
/**
* 获取 TAG 启用状态
* @return 当前 TAG 的启用状态
*/
public Boolean getEnable() { public Boolean getEnable() {
return enable; return enable;
} }
/**
* 重写父类方法:获取当前类的全限定名(用于 BaseBean 反射识别)
* @return 类全限定名(如 "cc.winboll.studio.libappbase.LogUtilsClassTAGBean"
*/
@Override @Override
public String getName() { public String getName() {
return LogUtilsClassTAGBean.class.getName(); return LogUtilsClassTAGBean.class.getName();
} }
/**
* 重写父类方法:将当前 TAG 配置对象序列化为 JSON持久化存储时调用
* 序列化字段tagTAG 名称、enable启用状态
* @param jsonWriter JSON 写入器(用于输出 JSON 数据)
* @throws IOException JSON 写入异常(如流关闭、格式错误)
*/
@Override @Override
public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException { public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException {
// 调用父类序列化逻辑(若 BaseBean 有公共字段,需优先处理)
super.writeThisToJsonWriter(jsonWriter); super.writeThisToJsonWriter(jsonWriter);
// 序列化 TAG 名称 LogUtilsClassTAGBean bean = this;
jsonWriter.name("tag").value(this.getTag()); jsonWriter.name("tag").value(bean.getTag());
// 序列化启用状态 jsonWriter.name("enable").value(bean.getEnable());
jsonWriter.name("enable").value(this.getEnable());
} }
/**
* 重写父类方法:从 JSON 字段初始化当前对象(读取配置时调用)
* 解析字段tagTAG 名称、enable启用状态
* @param jsonReader JSON 读取器(用于读取 JSON 数据)
* @param name JSON 字段名(当前解析的字段)
* @return true字段解析成功false字段不匹配需父类处理或跳过
* @throws IOException JSON 读取异常(如字段类型不匹配、流中断)
*/
@Override @Override
public boolean initObjectsFromJsonReader(JsonReader jsonReader, String name) throws IOException { public boolean initObjectsFromJsonReader(JsonReader jsonReader, String name) throws IOException {
// 先让父类处理公共字段,处理成功则直接返回 if (super.initObjectsFromJsonReader(jsonReader, name)) { return true; } else {
if (super.initObjectsFromJsonReader(jsonReader, name)) { if (name.equals("tag")) {
return true; setTag(jsonReader.nextString());
} else if (name.equals("enable")) {
setEnable(jsonReader.nextBoolean());
} else {
return false;
}
} }
// 解析当前类专属字段
if ("tag".equals(name)) {
// 读取 TAG 名称并设置
this.setTag(jsonReader.nextString());
} else if ("enable".equals(name)) {
// 读取启用状态并设置
this.setEnable(jsonReader.nextBoolean());
} else {
// 字段不匹配,返回 false 表示需要跳过该字段
return false;
}
// 字段解析成功
return true; return true;
} }
/**
* 重写父类方法:从 JSON 读取器完整解析配置对象(入口方法)
* 负责 JSON 对象的开始/结束解析,遍历所有字段并调用 initObjectsFromJsonReader 处理
* @param jsonReader JSON 读取器(传入待解析的 JSON 流)
* @return 解析后的当前 LogUtilsClassTAGBean 实例(支持链式调用)
* @throws IOException JSON 解析异常(如格式错误、字段缺失)
*/
@Override @Override
public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException { public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException {
// 开始解析 JSON 对象(必须与 writeThisToJsonWriter 中的结构对应)
jsonReader.beginObject(); jsonReader.beginObject();
// 遍历 JSON 中的所有字段
while (jsonReader.hasNext()) { while (jsonReader.hasNext()) {
String fieldName = jsonReader.nextName(); String name = jsonReader.nextName();
// 解析字段,若字段不匹配则跳过该值(避免解析失败) if (!initObjectsFromJsonReader(jsonReader, name)) {
if (!this.initObjectsFromJsonReader(jsonReader, fieldName)) {
jsonReader.skipValue(); jsonReader.skipValue();
} }
} }
// 结束 JSON 对象解析(必须调用,否则会导致流异常) // 结束 JSON 对象
jsonReader.endObject(); jsonReader.endObject();
// 返回当前实例,支持链式调用(如 new LogUtilsClassTAGBean().readBeanFromJsonReader(reader)
return this; return this;
} }
} }

View File

@@ -1,5 +1,10 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2024/08/12 14:36:18
* @Describe 日志视图类,继承 RelativeLayout 类。
*/
import android.content.ClipData; import android.content.ClipData;
import android.content.ClipboardManager; import android.content.ClipboardManager;
import android.content.Context; import android.content.Context;
@@ -21,6 +26,8 @@ import android.widget.RelativeLayout;
import android.widget.ScrollView; import android.widget.ScrollView;
import android.widget.Spinner; import android.widget.Spinner;
import android.widget.TextView; import android.widget.TextView;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.R;
import java.text.Collator; import java.text.Collator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -28,49 +35,27 @@ import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2024/08/12 14:36:18
* @Describe 日志可视化自定义 View继承 RelativeLayout
* 核心功能日志展示、日志级别筛选、TAG 过滤(启用/禁用、TAG 搜索定位、日志清理/复制、视图交互控制
* 依赖 LogUtils 进行日志读写,通过 LogViewThread 监听日志文件变化并自动刷新
*/
public class LogView extends RelativeLayout { public class LogView extends RelativeLayout {
/** 当前 View 的日志 TAG用于调试输出 */
public static final String TAG = "LogView"; public static final String TAG = "LogView";
/** 日志处理中标志避免并发刷新volatile 保证多线程可见性) */ public volatile boolean mIsHandling;
private volatile boolean mIsHandling; public volatile boolean mIsAddNewLog;
/** 新日志添加标志标记有未处理的新日志volatile 保证多线程可见性) */
private volatile boolean mIsAddNewLog;
/** 上下文对象(用于布局加载、系统服务获取) */ Context mContext;
private Context mContext; ScrollView mScrollView;
/** 日志滚动视图(包裹日志文本,支持垂直滚动) */ TextView mTextView;
private ScrollView mLogScrollView; EditText metTagSearch;
/** 日志文本展示控件(显示所有日志内容) */ CheckBox mSelectableCheckBox;
private TextView mLogTextView; CheckBox mSelectAllTAGCheckBox;
/** TAG 搜索输入框(用于搜索并定位目标 TAG */ TAGListAdapter mTAGListAdapter;
private EditText mTagSearchEt; LogViewThread mLogViewThread;
/** 文本选择开关(控制是否允许选中日志文本) */ LogViewHandler mLogViewHandler;
private CheckBox mTextSelectableCb; Spinner mLogLevelSpinner;
/** 全选 TAG 开关(控制所有 TAG 的启用/禁用) */ ArrayAdapter<CharSequence> mLogLevelSpinnerAdapter;
private CheckBox mSelectAllTagCb; // 标签列表
/** TAG 列表适配器(绑定 TAG 数据与视图,处理勾选状态) */ HorizontalListView mListViewTags;
private TAGListAdapter mTagListAdapter;
/** 日志监听线程(监听日志文件变化,触发视图刷新) */
private LogViewThread mLogViewThread;
/** 日志视图 Handler主线程更新 UI避免跨线程操作 */
private LogViewHandler mLogViewHandler;
/** 日志级别选择下拉框(用于切换全局日志输出级别) */
private Spinner mLogLevelSpinner;
/** 日志级别适配器(绑定 LogUtils.LOG_LEVEL 枚举与 Spinner */
private ArrayAdapter<CharSequence> mLogLevelAdapter;
/** TAG 水平列表视图(横向展示所有 TAG支持滚动 */
private HorizontalListView mTagHorizontalListView;
// ====================== 构造方法(初始化视图) ======================
public LogView(Context context) { public LogView(Context context) {
super(context); super(context);
initView(context); initView(context);
@@ -91,307 +76,258 @@ public class LogView extends RelativeLayout {
initView(context); initView(context);
} }
/**
* 启动日志监听与展示
* 1. 初始化并启动 LogViewThread监听日志文件变化
* 2. 初始加载并展示日志内容。
*/
public void start() { public void start() {
mLogViewThread = new LogViewThread(this); mLogViewThread = new LogViewThread(LogView.this);
mLogViewThread.start(); mLogViewThread.start();
showAndScrollLogView(); // 初始显示日志并滚动到底部 // 显示日志
showAndScrollLogView();
} }
/** public void scrollLogUp() {
* 滚动日志到底部(确保最新日志可见) mScrollView.post(new Runnable() {
* 运行在主线程,通过 post 提交 Runnable 避免 UI 线程阻塞 @Override
*/ public void run() {
private void scrollLogToBottom() { mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
mLogScrollView.post(new Runnable() { // 日志显示结束
@Override mLogViewHandler.setIsHandling(false);
public void run() { // 检查是否添加了新日志
// 滚动到 ScrollView 底部FOCUS_DOWN 表示聚焦到底部) if (mLogViewHandler.isAddNewLog()) {
mLogScrollView.fullScroll(ScrollView.FOCUS_DOWN); // 有新日志添加,先更改新日志标志
// 标记日志处理完成 mLogViewHandler.setIsAddNewLog(false);
mLogViewHandler.setIsHandling(false); // 再次发送显示日志的显示
// 检查是否有未处理的新日志,有则再次触发刷新 Message message = mLogViewHandler.obtainMessage(LogViewHandler.MSG_LOGVIEW_UPDATE);
if (mLogViewHandler.isAddNewLog()) { mLogViewHandler.sendMessage(message);
mLogViewHandler.setIsAddNewLog(false); }
Message refreshMsg = mLogViewHandler.obtainMessage(LogViewHandler.MSG_LOG_REFRESH); }
mLogViewHandler.sendMessage(refreshMsg); });
}
}
});
} }
/** void initView(Context context) {
* 初始化视图组件(加载布局、绑定控件、设置监听)
* @param context 上下文对象
*/
private void initView(Context context) {
mContext = context; mContext = context;
mLogViewHandler = new LogViewHandler(); // 初始化主线程 Handler mLogViewHandler = new LogViewHandler();
// 加载视图布局
addView(inflate(mContext, cc.winboll.studio.libappbase.R.layout.view_log, null));
// 初始化日志子控件视图
//
mScrollView = findViewById(cc.winboll.studio.libappbase.R.id.viewlogScrollViewLog);
mTextView = findViewById(cc.winboll.studio.libappbase.R.id.viewlogTextViewLog);
metTagSearch = findViewById(cc.winboll.studio.libappbase.R.id.tagsearch_et);
// 获取Log Level spinner实例
mLogLevelSpinner = findViewById(cc.winboll.studio.libappbase.R.id.viewlogSpinner1);
// 加载日志视图布局R.layout.view_log 为自定义布局文件) metTagSearch.addTextChangedListener(new TextWatcher() {
View rootView = LayoutInflater.from(context).inflate(R.layout.view_log, this, true);
// 绑定布局控件(通过 ID 找到对应组件)
bindViews(rootView);
// 设置 TAG 搜索输入框监听(实时搜索并定位 TAG @Override
setupTagSearchListener(); public void afterTextChanged(Editable editable) {
// 设置功能按钮监听(清理日志、复制日志) }
setupFunctionButtonListeners(rootView);
// 设置文本选择开关监听(控制日志文本是否可选中) @Override
setupTextSelectableListener(); public void beforeTextChanged(CharSequence charSequence, int p, int p1, int p2) {
// 初始化日志级别下拉框(绑定级别数据,设置默认值) }
initLogLevelSpinner();
// 初始化 TAG 列表(加载所有 TAG设置全选状态 @Override
initTagListView(); public void onTextChanged(CharSequence s, int start, int before, int count) {
// 设置默认交互模式(默认禁止子视图获取焦点,避免误触) LogUtils.d(TAG, s.toString());
if (s.length() > 0) {
scrollToTag(s.toString());
} else {
HorizontalScrollView hsRoot = findViewById(R.id.viewlogHorizontalScrollView1);
hsRoot.smoothScrollTo(0, 0);
mListViewTags.resetScrollToStart();
}
// mListViewTags.postDelayed(new Runnable() {
// @Override
// public void run() {
// mListViewTags.scrollToItem(5);
// }
// }, 100);
}
// 其他方法留空或按需实现
});
(findViewById(cc.winboll.studio.libappbase.R.id.viewlogButtonClean)).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
LogUtils.cleanLog();
LogUtils.d(TAG, "Log is cleaned.");
}
});
(findViewById(cc.winboll.studio.libappbase.R.id.viewlogButtonCopy)).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setPrimaryClip(ClipData.newPlainText(mContext.getPackageName(), LogUtils.loadLog()));
LogUtils.d(TAG, "Log is copied.");
}
});
mSelectableCheckBox = findViewById(cc.winboll.studio.libappbase.R.id.viewlogCheckBoxSelectable);
mSelectableCheckBox.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (mSelectableCheckBox.isChecked()) {
setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
} else {
setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
}
}
});
// 设置日志级别列表
ArrayList<String> adapterItems = new ArrayList<>();
for (LogUtils.LOG_LEVEL e : LogUtils.LOG_LEVEL.values()) {
adapterItems.add(e.name());
}
// 假设你有一个字符串数组作为选项列表
//String[] options = {"Option 1", "Option 2", "Option 3"};
// 创建一个ArrayAdapter来绑定数据到spinner
mLogLevelSpinnerAdapter = ArrayAdapter.createFromResource(
context, cc.winboll.studio.libappbase.R.array.enum_loglevel_array, android.R.layout.simple_spinner_item);
mLogLevelSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// 设置适配器并将它应用到spinner上
mLogLevelSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 设置下拉视图样式
mLogLevelSpinner.setAdapter(mLogLevelSpinnerAdapter);
// 为Spinner添加监听器
mLogLevelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//String selectedOption = mLogLevelSpinnerAdapter.getItem(position);
// 处理选中的选项...
LogUtils.setLogLevel(LogUtils.LOG_LEVEL.values()[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// 如果没有选择,则执行此操作...
}
});
// 获取默认值的索引
int defaultValueIndex = LogUtils.getLogLevel().ordinal();
if (defaultValueIndex != -1) {
// 如果找到了默认值,设置默认选项
mLogLevelSpinner.setSelection(defaultValueIndex);
}
// 加载标签列表
Map<String, Boolean> mapTAGList = LogUtils.getMapTAGList();
boolean isAllSelect = true;
for (Map.Entry<String, Boolean> entry : mapTAGList.entrySet()) {
if (entry.getValue() == false) {
isAllSelect = false;
break;
}
}
CheckBox cbALLTAG = findViewById(cc.winboll.studio.libappbase.R.id.viewlogCheckBox1);
cbALLTAG.setChecked(isAllSelect);
// 加载标签表
mListViewTags = findViewById(cc.winboll.studio.libappbase.R.id.tags_listview);
mListViewTags.setVerticalOffset(10);
mTAGListAdapter = new TAGListAdapter(mContext, mapTAGList);
mListViewTags.setAdapter(mTAGListAdapter);
// 可以添加点击监听器来处理勾选框状态变化后的逻辑,比如获取当前勾选情况等
mTAGListAdapter.notifyDataSetChanged();
mSelectAllTAGCheckBox = findViewById(cc.winboll.studio.libappbase.R.id.viewlogCheckBox1);
mSelectAllTAGCheckBox.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
LogUtils.setALlTAGListEnable(mSelectAllTAGCheckBox.isChecked());
//LogUtils.setALlTAGListEnable(false);
//mTAGListAdapter.notifyDataSetChanged();
mTAGListAdapter.reload();
//ToastUtils.show(String.format("onClick\nmSelectAllTAGCheckBox.isChecked() : %s", mSelectAllTAGCheckBox.isChecked()));
}
});
// 设置滚动时不聚焦日志
setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
} }
/**
* 绑定布局控件(通过 ID 查找并初始化所有子组件)
* @param rootView 根布局视图
*/
private void bindViews(View rootView) {
mLogScrollView = rootView.findViewById(R.id.viewlogScrollViewLog);
mLogTextView = rootView.findViewById(R.id.viewlogTextViewLog);
mTagSearchEt = rootView.findViewById(R.id.tagsearch_et);
mLogLevelSpinner = rootView.findViewById(R.id.viewlogSpinner1);
mTextSelectableCb = rootView.findViewById(R.id.viewlogCheckBoxSelectable);
mSelectAllTagCb = rootView.findViewById(R.id.viewlogCheckBox1);
mTagHorizontalListView = rootView.findViewById(R.id.tags_listview);
}
/**
* 设置 TAG 搜索输入框监听(文本变化时触发 TAG 定位)
*/
private void setupTagSearchListener() {
mTagSearchEt.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) {
String searchText = s.toString().trim();
LogUtils.d(TAG, "TAG 搜索内容:" + searchText);
if (!searchText.isEmpty()) {
// 搜索文本非空,定位匹配的 TAG
scrollToTargetTag(searchText);
} else {
// 搜索文本为空,重置滚动位置
HorizontalScrollView parentHs = findViewById(R.id.viewlogHorizontalScrollView1);
parentHs.smoothScrollTo(0, 0);
mTagHorizontalListView.resetScrollToStart();
}
}
@Override
public void afterTextChanged(Editable s) {}
});
}
/**
* 设置功能按钮监听(清理日志、复制日志)
*/
private void setupFunctionButtonListeners(View rootView) {
// 清理日志按钮(点击清空所有历史日志)
rootView.findViewById(R.id.viewlogButtonClean).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.cleanLog();
LogUtils.d(TAG, "日志已清理");
}
});
// 复制日志按钮(点击复制所有日志到剪贴板)
rootView.findViewById(R.id.viewlogButtonCopy).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
// 将日志内容复制到剪贴板(标签为应用包名)
clipboard.setPrimaryClip(ClipData.newPlainText(mContext.getPackageName(), LogUtils.loadLog()));
LogUtils.d(TAG, "日志已复制到剪贴板");
}
});
}
/**
* 设置文本选择开关监听(控制日志文本是否可选中复制)
*/
private void setupTextSelectableListener() {
mTextSelectableCb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mTextSelectableCb.isChecked()) {
// 允许文本选择:子视图优先获取焦点
setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
} else {
// 禁止文本选择:阻止子视图获取焦点
setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
}
}
});
}
/**
* 初始化日志级别下拉框Spinner
* 1. 绑定 LogUtils.LOG_LEVEL 枚举数据;
* 2. 设置默认选中当前全局日志级别;
* 3. 监听级别变化,更新 LogUtils 全局配置。
*/
private void initLogLevelSpinner() {
// 从资源文件加载日志级别数组R.array.enum_loglevel_array 与 LOG_LEVEL 枚举对应)
mLogLevelAdapter = ArrayAdapter.createFromResource(
mContext, R.array.enum_loglevel_array, android.R.layout.simple_spinner_item);
// 设置下拉列表样式
mLogLevelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mLogLevelSpinner.setAdapter(mLogLevelAdapter);
// 监听下拉框选择变化
mLogLevelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// 根据选择的位置设置全局日志级别position 与 LOG_LEVEL 枚举索引对应)
LogUtils.setLogLevel(LogUtils.LOG_LEVEL.values()[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
// 设置默认选中当前日志级别
int defaultLevelIndex = LogUtils.getLogLevel().ordinal();
if (defaultLevelIndex >= 0) {
mLogLevelSpinner.setSelection(defaultLevelIndex);
}
}
/**
* 初始化 TAG 水平列表
* 1. 加载 LogUtils 中的所有 TAG 及其启用状态;
* 2. 初始化 TAG 列表适配器;
* 3. 设置全选 TAG 开关监听。
*/
private void initTagListView() {
// 获取 LogUtils 中的 TAG 启用状态映射表
Map<String, Boolean> tagEnableMap = LogUtils.getTagEnableMap();
// 判断是否所有 TAG 都已启用(初始化全选开关状态)
boolean isAllTagEnabled = isAllTagsEnabled(tagEnableMap);
mSelectAllTagCb.setChecked(isAllTagEnabled);
// 初始化 TAG 水平列表(设置垂直偏移,绑定适配器)
mTagHorizontalListView.setVerticalOffset(10);
mTagListAdapter = new TAGListAdapter(mContext, tagEnableMap);
mTagHorizontalListView.setAdapter(mTagListAdapter);
mTagListAdapter.notifyDataSetChanged(); // 刷新列表数据
// 全选 TAG 开关监听(点击时启用/禁用所有 TAG
mSelectAllTagCb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isSelectAll = mSelectAllTagCb.isChecked();
LogUtils.setAllTagsEnable(isSelectAll); // 批量更新所有 TAG 状态
mTagListAdapter.reload(); // 重新加载 TAG 数据并刷新视图
}
});
}
/**
* 判断是否所有 TAG 都已启用
* @param tagEnableMap TAG 启用状态映射表
* @return true所有 TAG 均启用false存在未启用的 TAG
*/
private boolean isAllTagsEnabled(Map<String, Boolean> tagEnableMap) {
for (Map.Entry<String, Boolean> entry : tagEnableMap.entrySet()) {
if (!entry.getValue()) {
return false;
}
}
return true;
}
/**
* 更新日志视图(由 LogViewThread 触发,通知有新日志)
* 避免并发刷新:正在处理时标记新日志,处理完成后再次刷新
*/
public void updateLogView() { public void updateLogView() {
if (mLogViewHandler.isHandling()) { if (mLogViewHandler.isHandling() == true) {
// 正在处理日志刷新,标记有新日志待处理 // 正在处理日志显示,
// 就先设置一个新日志标志位
// 以便日志显示完后,再次显示新日志内容
mLogViewHandler.setIsAddNewLog(true); mLogViewHandler.setIsAddNewLog(true);
} else { } else {
// 发送刷新消息到主线程 //LogUtils.d(TAG, "LogListener showLog(String path)");
Message refreshMsg = mLogViewHandler.obtainMessage(LogViewHandler.MSG_LOG_REFRESH); Message message = mLogViewHandler.obtainMessage(LogViewHandler.MSG_LOGVIEW_UPDATE);
mLogViewHandler.sendMessage(refreshMsg); mLogViewHandler.sendMessage(message);
mLogViewHandler.setIsAddNewLog(false); mLogViewHandler.setIsAddNewLog(false);
} }
} }
/** void showAndScrollLogView() {
* 显示日志并滚动到底部 mTextView.setText(LogUtils.loadLog());
* 1. 从 LogUtils 加载所有历史日志; scrollLogUp();
* 2. 设置到文本控件并滚动到底部。
*/
private void showAndScrollLogView() {
mLogTextView.setText(LogUtils.loadLog()); // 加载并显示日志
scrollLogToBottom(); // 滚动到底部,显示最新日志
} }
/** public void scrollToTag(final String prefix) {
* 滚动到目标 TAG根据搜索文本定位匹配的 TAG 并滚动显示) if (mTAGListAdapter == null || prefix == null || prefix.length() == 0) {
* @param prefix 搜索文本TAG 前缀) LogUtils.d(TAG, "参数为空,无法滚动");
*/
private void scrollToTargetTag(final String prefix) {
if (mTagListAdapter == null || prefix == null || prefix.isEmpty()) {
LogUtils.d(TAG, "TAG 搜索参数为空,无法定位");
return; return;
} }
final List<TAGItemModel> tagItemList = mTagListAdapter.getItemList(); final List<TAGItemModel> itemList = mTAGListAdapter.getItemList();
mTagHorizontalListView.post(new Runnable() {
@Override
public void run() {
int targetPosition = -1;
// 遍历 TAG 列表,查找前缀匹配的 TAG忽略大小写
for (int i = 0; i < tagItemList.size(); i++) {
String tag = tagItemList.get(i).getTag();
if (tag != null && tag.toLowerCase().startsWith(prefix.toLowerCase())) {
targetPosition = i;
break;
}
}
if (targetPosition != -1) { mListViewTags.post(new Runnable() {
final int targetPositionFinal = targetPosition; @Override
// 延迟滚动(确保布局完成,避免滚动失效) public void run() {
mTagHorizontalListView.postDelayed(new Runnable() { // 查找匹配的标签位置
@Override int targetPosition = -1;
public void run() {
LogUtils.d(TAG, "定位到 TAG 位置:" + targetPositionFinal); for (int i = 0; i < itemList.size(); i++) {
mTagHorizontalListView.scrollToItem(targetPositionFinal); String tag = itemList.get(i).getTag();
} if (tag != null && tag.toLowerCase().startsWith(prefix.toLowerCase())) {
}, 100); targetPosition = i;
} else {
LogUtils.d(TAG, "未找到匹配前缀的 TAG" + prefix); break;
} }
} }
});
if (targetPosition != -1) {
// 优化滚动逻辑
//mListViewTags.setSelection(targetPosition);
//mListViewTags.invalidateViews(); // 强制刷新所有可见项
// 单独刷新目标视图
// View targetView = mListViewTags.getChildAt(targetPosition);
// if (targetView != null) {
// targetView.requestLayout();
// targetView.requestFocus();
// }
final int scrollPosition = targetPosition;
// 延迟滚动确保布局完成
mListViewTags.postDelayed(new Runnable() {
@Override
public void run() {
LogUtils.d(TAG, String.format("scrollPosition %d", scrollPosition));
mListViewTags.scrollToItem(scrollPosition);
}
}, 100);
} else {
LogUtils.d(TAG, "未找到匹配的标签前缀:" + prefix);
}
}
});
} }
// ====================== 内部类:日志视图 Handler主线程更新 UI ======================
/**
* 日志视图 Handler运行在主线程处理日志刷新消息 class LogViewHandler extends Handler {
* 避免跨线程操作 UI通过标志位控制并发刷新
*/ final static int MSG_LOGVIEW_UPDATE = 0;
private class LogViewHandler extends Handler { volatile boolean isHandling;
/** 日志刷新消息标识 */ volatile boolean isAddNewLog;
private static final int MSG_LOG_REFRESH = 0;
/** 日志处理中标志(与外部 mIsHandling 同步) */
private volatile boolean isHandling;
/** 新日志添加标志(与外部 mIsAddNewLog 同步) */
private volatile boolean isAddNewLog;
public LogViewHandler() { public LogViewHandler() {
setIsHandling(false); setIsHandling(false);
@@ -414,32 +350,24 @@ public class LogView extends RelativeLayout {
return isAddNewLog; return isAddNewLog;
} }
@Override
public void handleMessage(Message msg) { public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) { switch (msg.what) {
case MSG_LOG_REFRESH: case MSG_LOGVIEW_UPDATE:{
// 未处理日志刷新时,标记为处理中并触发显示 if (isHandling() == false) {
if (!isHandling()) { setIsHandling(true);
setIsHandling(true); showAndScrollLogView();
showAndScrollLogView(); }
break;
} }
break;
default: default:
break; break;
} }
super.handleMessage(msg);
} }
} }
// ====================== 内部类TAG 数据模型(封装 TAG 名称与状态) ====================== public class TAGItemModel {
/**
* TAG 列表项数据模型
* 封装单个 TAG 的名称及其启用状态(用于 Adapter 数据绑定)
*/
private class TAGItemModel {
/** TAG 名称(如 "LogViewThread"、"LogUtils" */
private String tag; private String tag;
/** TAG 启用状态true启用false禁用 */
private boolean isChecked; private boolean isChecked;
public TAGItemModel(String tag, boolean isChecked) { public TAGItemModel(String tag, boolean isChecked) {
@@ -463,17 +391,18 @@ public class LogView extends RelativeLayout {
isChecked = checked; isChecked = checked;
} }
/** // getter/setter...
* 重写 equals 方法(按 TAG 名称判断相等)
* @param o 比较对象
* @return trueTAG 名称相同false不同
*/
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TAGItemModel that = (TAGItemModel) o; TAGItemModel that = (TAGItemModel) o;
// 手动处理空值比较(兼容 Java 7不依赖 Objects.equals // 手动处理空值比较Java 6 不支持 Objects.equals
if (tag == null) { if (tag == null) {
return that.tag == null; return that.tag == null;
} else { } else {
@@ -481,174 +410,106 @@ public class LogView extends RelativeLayout {
} }
} }
/**
* 重写 hashCode 方法(基于 TAG 名称生成哈希值)
* @return 哈希值(空 TAG 返回 0
*/
@Override @Override
public int hashCode() { public int hashCode() {
return tag == null ? 0 : tag.hashCode(); return tag == null ? 0 : tag.hashCode(); // 手动处理空值
} }
} }
// ====================== 内部类TAG 列表适配器(绑定数据与视图) ======================
/** public class TAGListAdapter extends BaseAdapter {
* TAG 水平列表适配器(继承 BaseAdapter
* 负责 TAG 数据与列表项视图的绑定,处理勾选状态变化
*/
private class TAGListAdapter extends BaseAdapter {
/** 上下文对象(用于加载列表项布局) */
private Context context; private Context context;
/** 原始 TAG 启用状态映射表(来自 LogUtils */ private Map<String, Boolean> mapOrigin;
private Map<String, Boolean> originTagMap; private List<TAGItemModel> itemList;
/** TAG 列表项数据(转换为 TAGItemModel 列表,便于排序和绑定) */
private List<TAGItemModel> tagItemList;
/** public TAGListAdapter(Context context, Map<String, Boolean> map) {
* 构造方法(初始化数据并加载到列表)
* @param context 上下文
* @param tagMap TAG 启用状态映射表
*/
public TAGListAdapter(Context context, Map<String, Boolean> tagMap) {
this.context = context; this.context = context;
this.originTagMap = tagMap; mapOrigin = map;
loadTagData(originTagMap); // 加载并转换数据 loadMap(mapOrigin);
} }
/**
* 获取 TAG 列表项数据(供外部定位 TAG 使用)
* @return TAGItemModel 列表
*/
public List<TAGItemModel> getItemList() { public List<TAGItemModel> getItemList() {
return tagItemList; return itemList;
} }
// ====================== BaseAdapter 抽象方法实现 ======================
@Override @Override
public int getCount() { public int getCount() {
return tagItemList == null ? 0 : tagItemList.size(); return itemList.size();
} }
@Override @Override
public Object getItem(int position) { public Object getItem(int p) {
return tagItemList.get(position); return itemList.get(p);
} }
@Override @Override
public long getItemId(int position) { public long getItemId(int p) {
return position; return p;
} }
/** void loadMap(Map<String, Boolean> map) {
* 加载 TAG 数据(将 Map 转换为 List 并排序) itemList = new ArrayList<TAGItemModel>();
* @param tagMap TAG 启用状态映射表 for (Map.Entry<String, Boolean> entry : map.entrySet()) {
*/ itemList.add(new TAGItemModel(entry.getKey(), entry.getValue()));
private void loadTagData(Map<String, Boolean> tagMap) {
tagItemList = new ArrayList<>();
// 遍历 Map转换为 TAGItemModel 并添加到列表
for (Map.Entry<String, Boolean> entry : tagMap.entrySet()) {
tagItemList.add(new TAGItemModel(entry.getKey(), entry.getValue()));
} }
// 按 TAG 名称升序排序(中文排序兼容) // 添加排序功能按照tag进行升序排序
Collections.sort(tagItemList, new TagAscComparator(true)); Collections.sort(itemList, new SortMapEntryByKeyString(true));
//Collections.sort(itemList, new SortMapEntryByKeyString(false));
} }
/**
* 重新加载 TAG 数据(用于全选/反选后刷新列表)
*/
public void reload() { public void reload() {
loadTagData(originTagMap); // 重新加载数据 loadMap(mapOrigin);
notifyDataSetChanged(); // 通知视图刷新 super.notifyDataSetChanged();
} }
/**
* 创建/复用列表项视图(优化性能,避免重复 inflate
* @param position 列表项位置
* @param convertView 复用视图(可为 null
* @param parent 父容器
* @return 列表项视图
*/
@Override @Override
public View getView(int position, View convertView, ViewGroup parent) { public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder; ViewHolder holder;
// 复用视图(减少布局加载开销)
if (convertView == null) { if (convertView == null) {
// 加载列表项布局R.layout.item_logtag 为 TAG 项自定义布局)
convertView = LayoutInflater.from(context).inflate(R.layout.item_logtag, parent, false); convertView = LayoutInflater.from(context).inflate(R.layout.item_logtag, parent, false);
holder = new ViewHolder(); holder = new ViewHolder();
// 绑定列表项控件TAG 文本和勾选框) holder.tvText = convertView.findViewById(R.id.viewlogtagTextView1);
holder.tagTv = convertView.findViewById(R.id.viewlogtagTextView1); holder.cbChecked = convertView.findViewById(R.id.viewlogtagCheckBox1);
holder.tagCb = convertView.findViewById(R.id.viewlogtagCheckBox1); convertView.setTag(holder);
convertView.setTag(holder); // 保存 ViewHolder 到视图
} else { } else {
holder = (ViewHolder) convertView.getTag(); // 复用 ViewHolder holder = (ViewHolder) convertView.getTag();
} }
// 绑定数据到视图 final TAGItemModel item = itemList.get(position);
final TAGItemModel item = tagItemList.get(position); holder.tvText.setText(item.getTag());
holder.tagTv.setText(item.getTag()); // 设置 TAG 名称 holder.cbChecked.setChecked(item.isChecked());
holder.tagCb.setChecked(item.isChecked()); // 设置勾选状态 holder.cbChecked.setOnClickListener(new View.OnClickListener(){
// 勾选框点击监听(更新 TAG 启用状态) @Override
holder.tagCb.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {
@Override LogUtils.setTAGListEnable(item.getTag(), ((CheckBox)v).isChecked());
public void onClick(View v) { }
boolean isChecked = ((CheckBox) v).isChecked(); });
// 调用 LogUtils 更新该 TAG 的启用状态
LogUtils.setTagEnable(item.getTag(), isChecked);
// 同步更新本地模型状态(避免刷新后状态不一致)
item.setChecked(isChecked);
}
});
return convertView; return convertView;
} }
/** public class ViewHolder {
* 列表项 ViewHolder缓存控件提升列表滑动性能 TextView tvText;
*/ CheckBox cbChecked;
private class ViewHolder {
TextView tagTv; // TAG 名称文本控件
CheckBox tagCb; // TAG 启用状态勾选框
} }
} }
// ====================== 内部类TAG 排序比较器(中文兼容) ====================== class SortMapEntryByKeyString implements Comparator<TAGItemModel> {
/** private boolean mIsDesc = true;
* TAG 名称排序比较器(实现 Comparator // isDesc 是否降序排列
* 支持中文排序(基于系统默认中文 Locale可选择升序/降序 public SortMapEntryByKeyString(boolean isDesc) {
*/ mIsDesc = isDesc;
private class TagAscComparator implements Comparator<TAGItemModel> {
/** 排序方向true升序false降序 */
private boolean isAsc;
/** 中文排序器(兼容中文汉字排序) */
private Collator chineseCollator = Collator.getInstance(java.util.Locale.CHINA);
public TagAscComparator(boolean isAsc) {
this.isAsc = isAsc;
} }
Collator cmp = Collator.getInstance(java.util.Locale.CHINA);
/**
* 比较两个 TAGItemModel按 TAG 名称排序)
* @param o1 第一个比较对象
* @param o2 第二个比较对象
* @return 比较结果正数o1 在 o2 后负数o1 在 o2 前0相等
*/
@Override @Override
public int compare(TAGItemModel o1, TAGItemModel o2) { public int compare(TAGItemModel o1, TAGItemModel o2) {
String tag1 = o1.getTag(); if (mIsDesc) {
String tag2 = o2.getTag(); return o1.getTag().compareTo(o2.getTag());
// 处理空值(空 TAG 排在最前)
if (tag1 == null) return -1;
if (tag2 == null) return 1;
// 根据排序方向返回比较结果
if (isAsc) {
return chineseCollator.compare(tag1, tag2); // 升序
} else { } else {
return chineseCollator.compare(tag2, tag1); // 降序 return o2.getTag().compareTo(o1.getTag());
} }
} }
} }
} }

View File

@@ -1,140 +1,80 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
import android.os.FileObserver;
import java.lang.ref.WeakReference;
/** /**
* @Author ZhanGSKen<zhangsken@qq.com> * @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2024/08/12 14:43:50 * @Date 2024/08/12 14:43:50
* @Describe 日志视图线程类 * @Describe 日志视图线程类
* 独立线程监听日志文件目录变化(如写入、删除),触发日志视图更新,避免阻塞主线程
*/ */
import android.os.FileObserver;
import cc.winboll.studio.libappbase.LogUtils;
import java.lang.ref.WeakReference;
public class LogViewThread extends Thread { public class LogViewThread extends Thread {
/** 日志标签(用于调试输出) */
public static final String TAG = "LogViewThread"; public static final String TAG = "LogViewThread";
/** 线程退出标志volatile 保证多线程可见性,控制循环退出) */ // 线程退出标志
private volatile boolean isExit = false; volatile boolean isExist = false;
/** 日志文件目录监听实例(监听文件写入、删除事件) */ // 应用日志文件监听实例
private LogListener mLogListener; LogListener mLogListener;
/** 日志视图弱引用(避免持有 LogView 强引用导致内存泄漏) */ // 日志视图弱引用
private final WeakReference<LogView> mLogViewWeakRef; WeakReference<LogView> mwrLogView;
/** //
* 构造函数 // 构造函数
* @param logView 日志显示视图实例(需通过弱引用持有,避免内存泄漏) // @logView : 日志显示输出视图类
*/
public LogViewThread(LogView logView) { public LogViewThread(LogView logView) {
// 使用弱引用包装 LogView当视图销毁时可被 GC 回收 mwrLogView = new WeakReference<LogView>(logView);
mLogViewWeakRef = new WeakReference<>(logView);
} }
/** public void setIsExist(boolean isExist) {
* 设置线程退出标志(触发线程停止监听并退出) this.isExist = isExist;
* @param exit true退出线程false继续运行默认
*/
public void setExit(boolean exit) {
this.isExit = exit;
} }
/** public boolean isExist() {
* 获取当前线程退出状态 return isExist;
* @return true已标记退出false运行中
*/
public boolean isExit() {
return isExit;
} }
/**
* 线程核心逻辑:初始化文件监听并启动循环,直到收到退出标志
*/
@Override @Override
public void run() { public void run() {
// 获取日志缓存目录路径(从 LogUtils 统一获取,确保路径一致性) String szLogDir = LogUtils.getLogCacheDir().getPath();
String logDirPath = LogUtils.getLogCacheDir().getPath(); mLogListener = new LogListener(szLogDir);
LogUtils.d(TAG, "启动日志文件监听,监听目录:" + logDirPath);
// 初始化日志文件监听器(监听目标目录的文件事件)
mLogListener = new LogListener(logDirPath);
// 开始监听文件事件(非阻塞,内部通过 Native 层实现)
mLogListener.startWatching(); mLogListener.startWatching();
while (isExist() == false) {
// 循环等待退出标志(每 1 秒检查一次,降低 CPU 占用)
while (!isExit()) {
try { try {
Thread.sleep(1000); // 休眠 1 秒,避免忙等 Thread.sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {}
// 线程被中断时,恢复中断标志并退出循环(避免无限阻塞)
Thread.currentThread().interrupt();
LogUtils.d(TAG, "日志监听线程被中断,准备退出。" + e);
break;
}
} }
// 收到退出标志,停止监听并释放资源
mLogListener.stopWatching(); mLogListener.stopWatching();
LogUtils.d(TAG, "日志文件监听已停止,线程退出");
} }
/**
* 日志文件监听内部类(继承 FileObserver监听目录下文件变化
* 仅关注文件写入完成CLOSE_WRITE和文件删除DELETE事件
*/
private class LogListener extends FileObserver {
/** //
* 构造函数 // 日志文件监听类
* @param path 监听的目录路径(此处为日志缓存目录) //
*/ class LogListener extends FileObserver {
public LogListener(String path) { public LogListener(String path) {
// 父类构造:监听指定目录的所有事件(通过位掩码 ALL_EVENTS 指定)
super(path); super(path);
} }
/**
* 文件事件回调(运行在系统私有线程,非主线程)
* @param event 事件类型(通过位掩码表示,需与 ALL_EVENTS 按位与解析)
* @param path 发生事件的文件名(相对监听目录的路径)
*/
@Override @Override
public void onEvent(int event, String path) { public void onEvent(int event, String path) {
// 解析事件类型(排除无关事件,只处理目标事件) int e = event & FileObserver.ALL_EVENTS;
int eventType = event & FileObserver.ALL_EVENTS; switch (e) {
case FileObserver.CLOSE_WRITE:{
switch (eventType) { if (mwrLogView.get() != null) {
// 事件:文件写入完成(如日志写入结束并关闭文件) mwrLogView.get().updateLogView();
case FileObserver.CLOSE_WRITE: }
// 触发日志视图更新(需先判断 LogView 是否未被回收) break;
updateLogView(); }
break; case FileObserver.DELETE:{
if (mwrLogView.get() != null) {
// 事件:文件被删除(如日志清理操作) mwrLogView.get().updateLogView();
case FileObserver.DELETE: }
LogUtils.d(TAG, "日志文件被删除,文件名:" + (path != null ? path : "未知")); break;
// 触发日志视图更新(刷新视图显示空状态) }
updateLogView();
break;
default:
// 忽略其他无关事件(如文件创建、访问等)
break;
}
}
/**
* 触发日志视图更新(通过弱引用获取 LogView避免内存泄漏
*/
private void updateLogView() {
// 从弱引用中获取 LogView 实例若视图已销毁get() 返回 null
LogView logView = mLogViewWeakRef.get();
if (logView != null) {
// 调用 LogView 的更新方法(需确保 updateLogView 内部处理主线程切换)
logView.updateLogView();
} else {
LogUtils.w(TAG, "LogView 已被回收,无法更新日志视图");
} }
} }
} }
} }

View File

@@ -1,257 +1,34 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2025/03/12 12:02:31
*/
import android.content.Context; import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast; import android.widget.Toast;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:51
* @Describe 吐司工具类(单例模式)
* 简化 Android 吐司的创建与展示,通过独立线程 + Handler 处理消息,最终切换到主线程显示吐司,避免内存泄漏
*/
public class ToastUtils { public class ToastUtils {
/** 工具类日志 TAG用于调试输出 */
public static final String TAG = "ToastUtils"; public static final String TAG = "ToastUtils";
/** 消息标识:显示短时长吐司 */
private static final int MSG_SHOW_SHORT_TOAST = 1001;
/** 单例实例volatile 保证多线程下可见性,避免指令重排) */ volatile static ToastUtils _ToastUtils;
private static volatile ToastUtils sInstance; Context mContext;
/** 全局上下文volatile 保证多线程可见性,避免空指针) */
private volatile Context mContext;
/** 独立线程的 Handlervolatile 保证可见性) */
private volatile Handler mWorkerHandler;
/** 主线程 Handlervolatile 保证可见性) */
private volatile Handler mMainHandler;
/** 消息处理独立线程 */
private Thread mWorkerThread;
/** 资源释放标记volatile 避免多线程误操作) */
private volatile boolean isReleased = false;
/** ToastUtils() {
* 私有构造方法(禁止外部直接创建实例,确保单例)
* 1. 初始化主线程 Handler
* 2. 创建并启动独立消息处理线程。
*/
private ToastUtils() {
initMainHandler(); // 优先初始化主线程 Handler
startWorkerThread(); // 启动独立消息处理线程
} }
/** synchronized static ToastUtils getInstance() {
* 初始化主线程 Handler if (_ToastUtils == null) {
*/ _ToastUtils = new ToastUtils();
private void initMainHandler() {
if (Looper.getMainLooper() == null) {
LogUtils.e(TAG, "主线程 Looper 为空,无法初始化 mMainHandler");
throw new IllegalStateException("主线程 Looper 未初始化,无法创建 ToastUtils");
} }
mMainHandler = new Handler(Looper.getMainLooper()); return _ToastUtils;
LogUtils.d(TAG, "主线程 Handler 初始化完成线程ID" + Looper.getMainLooper().getThread().getId());
} }
/**
* 启动独立消息处理线程
*/
private void startWorkerThread() {
mWorkerThread = new Thread(new Runnable() {
@Override
public void run() {
LogUtils.d(TAG, "消息处理线程启动线程ID" + Thread.currentThread().getId());
Looper.prepare();
mWorkerHandler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 若已释放,直接返回,不处理消息
if (isReleased) {
LogUtils.w(TAG, "资源已释放,忽略消息处理");
return;
}
LogUtils.d(TAG, "WorkerHandler 接收消息当前线程ID" + Thread.currentThread().getId());
if (msg.what == MSG_SHOW_SHORT_TOAST && msg.obj != null) {
String message = (String) msg.obj;
postToMainThreadShowToast(message);
}
}
};
Looper.loop();
LogUtils.d(TAG, "消息处理线程退出");
}
}, "ToastWorkerThread");
mWorkerThread.start();
}
/**
* 获取单例实例(双重检查锁定)
* @return ToastUtils 单例对象
*/
private static ToastUtils getInstance() {
if (sInstance == null) {
synchronized (ToastUtils.class) {
if (sInstance == null) {
sInstance = new ToastUtils();
}
}
}
return sInstance;
}
/**
* 初始化工具类(必须在 Application 启动时调用)
* @param context 全局上下文(推荐 Application 上下文)
*/
public static void init(Context context) { public static void init(Context context) {
if (context == null) { getInstance().mContext = context;
throw new IllegalArgumentException("初始化上下文不能为 null");
}
ToastUtils instance = getInstance();
// 若已释放,重置释放标记
if (instance.isReleased) {
instance.isReleased = false;
instance.startWorkerThread(); // 重新启动线程
}
instance.mContext = context.getApplicationContext();
LogUtils.d(TAG, "ToastUtils 初始化完成,上下文已设置");
} }
/**
* 外部接口:显示短时长吐司
* @param message 吐司内容
*/
public static void show(String message) { public static void show(String message) {
LogUtils.d(TAG, "外部调用 show()当前线程ID" + Thread.currentThread().getId()); Toast.makeText(getInstance().mContext, message, Toast.LENGTH_SHORT).show();
if (message == null || message.isEmpty()) {
return;
}
ToastUtils instance = getInstance();
// 校验资源是否已释放
if (instance.isReleased) {
LogUtils.w(TAG, "ToastUtils 已释放,无法显示吐司:" + message);
return;
}
// 校验上下文是否初始化
if (instance.mContext == null) {
LogUtils.e(TAG, "ToastUtils 未初始化!请先调用 init(Context) 方法");
// 不抛出异常,避免崩溃,改为日志提示
return;
}
instance.sendToastMessage(message);
}
/**
* 发送吐司消息到 WorkerHandler
* @param message 吐司内容
*/
private void sendToastMessage(String message) {
LogUtils.d(TAG, "发送消息到 WorkerHandler");
// 校验 WorkerHandler 是否就绪
if (mWorkerHandler == null) {
LogUtils.w(TAG, "WorkerHandler 未就绪,直接主线程显示");
postToMainThreadShowToast(message);
return;
}
// 发送消息
Message msg = mWorkerHandler.obtainMessage(MSG_SHOW_SHORT_TOAST);
msg.obj = message;
mWorkerHandler.sendMessage(msg);
}
/**
* 切换到主线程显示吐司
* @param message 吐司内容
*/
private void postToMainThreadShowToast(final String message) {
LogUtils.d(TAG, "切换到主线程显示吐司当前线程ID" + Thread.currentThread().getId());
// 校验资源是否已释放
if (isReleased) {
LogUtils.w(TAG, "资源已释放,取消显示吐司");
return;
}
// 校验并初始化 mMainHandler
if (mMainHandler == null) {
LogUtils.e(TAG, "mMainHandler 为空,尝试重新初始化");
initMainHandler();
if (mMainHandler == null) {
LogUtils.e(TAG, "mMainHandler 初始化失败,无法显示吐司:" + message);
return;
}
}
// 主线程显示
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (isReleased) return; // 释放后取消执行
showToastInternal(message);
}
});
}
/**
* 实际显示吐司(主线程)
* @param message 吐司内容
*/
private void showToastInternal(String message) {
LogUtils.d(TAG, "执行 showToastInternal()");
// 最终校验上下文
if (mContext == null) {
LogUtils.w(TAG, "上下文为空,无法显示吐司:" + message);
// 尝试重新获取 Application 上下文(降级策略)
Context appContext = GlobalApplication.getInstance();
if (appContext != null) {
mContext = appContext;
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
LogUtils.d(TAG, "通过 GlobalApplication 获取上下文,成功显示吐司");
}
return;
}
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
/**
* 释放资源(仅在应用退出时调用)
*/
public static void release() {
LogUtils.d(TAG, "开始释放 ToastUtils 资源");
ToastUtils instance = getInstance();
// 标记为已释放,阻止后续消息处理
instance.isReleased = true;
// 停止 Worker 线程
if (instance.mWorkerHandler != null && instance.mWorkerHandler.getLooper() != null) {
instance.mWorkerHandler.getLooper().quit();
instance.mWorkerHandler = null;
}
// 清理主线程 Handler
if (instance.mMainHandler != null) {
instance.mMainHandler.removeCallbacksAndMessages(null);
instance.mMainHandler = null;
}
// 等待线程退出
if (instance.mWorkerThread != null && instance.mWorkerThread.isAlive()) {
try {
instance.mWorkerThread.join(1000);
} catch (InterruptedException e) {
LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
//LogUtils.e(TAG, "线程退出异常", e);
Thread.currentThread().interrupt();
}
instance.mWorkerThread = null;
}
// 清空上下文(避免内存泄漏)
instance.mContext = null;
LogUtils.d(TAG, "ToastUtils 资源释放完成");
} }
} }

View File

@@ -1,5 +1,10 @@
package cc.winboll.studio.libappbase; package cc.winboll.studio.libappbase;
/**
* @Author ZhanGSKen<zhangsken@qq.com>
* @Date 2024/07/19 14:30:57
* @Describe UTF-8编码文件工具类
*/
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@@ -8,79 +13,37 @@ import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
/**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/11/11 20:45
* @Describe UTF-8 编码文件操作工具类
* 提供字符串与文件的相互转换,强制使用 UTF-8 编码,确保跨平台字符兼容性
*/
public class UTF8FileUtils { public class UTF8FileUtils {
/** 工具类日志 TAG用于调试输出 */ public static final String TAG = "FileUtils";
public static final String TAG = "UTF8FileUtils";
/** //
* 将字符串写入文件(强制 UTF-8 编码 // 把字符串写入文件,指定 UTF-8 编码
* 若文件父目录不存在,自动创建;覆盖原有文件内容 //
* @param filePath 文件路径(包含文件名,如 "/sdcard/test.txt" public static void writeStringToFile(String szFilePath, String szContent) throws IOException {
* @param content 要写入的字符串内容 File file = new File(szFilePath);
* @throws IOException 写入失败时抛出(如权限不足、路径无效等) if (!file.getParentFile().exists()) {
*/ file.getParentFile().mkdirs();
public static void writeStringToFile(String filePath, String content) throws IOException {
// 根据路径创建文件对象
File file = new File(filePath);
// 获取父目录,若不存在则递归创建
File parentDir = file.getParentFile();
if (parentDir != null && !parentDir.exists()) {
parentDir.mkdirs();
} }
// 初始化文件输出流(覆盖模式)
FileOutputStream outputStream = new FileOutputStream(file); FileOutputStream outputStream = new FileOutputStream(file);
// 包装为 UTF-8 编码的字符输出流
OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
writer.write(szContent);
try { writer.close();
// 写入字符串内容
writer.write(content);
} finally {
// 强制关闭流,避免资源泄漏(即使写入失败也确保流关闭)
writer.close();
}
} }
/** //
* 从文件读取字符串(强制 UTF-8 编码 // 读取文件到字符串,指定 UTF-8 编码
* 逐字符读取文件内容,拼接为完整字符串返回 //
* @param filePath 文件路径(包含文件名,如 "/sdcard/test.txt" public static String readStringFromFile(String szFilePath) throws IOException {
* @return 文件内容字符串(空文件返回空字符串) File file = new File(szFilePath);
* @throws IOException 读取失败时抛出(如文件不存在、权限不足等)
*/
public static String readStringFromFile(String filePath) throws IOException {
// 根据路径创建文件对象
File file = new File(filePath);
// 初始化文件输入流
FileInputStream inputStream = new FileInputStream(file); FileInputStream inputStream = new FileInputStream(file);
// 包装为 UTF-8 编码的字符输入流
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
// 字符串构建器,用于拼接读取的字符
StringBuilder content = new StringBuilder(); StringBuilder content = new StringBuilder();
int charCode; // 存储单个字符的 ASCII 码 int character;
while ((character = reader.read()) != -1) {
try { content.append((char) character);
// 逐字符读取(-1 表示读取到文件末尾)
while ((charCode = reader.read()) != -1) {
// 将 ASCII 码转换为字符,追加到字符串
content.append((char) charCode);
}
} finally {
// 强制关闭流,避免资源泄漏
reader.close();
} }
reader.close();
// 返回读取的完整字符串
return content.toString(); return content.toString();
} }
} }

View File

@@ -2,5 +2,6 @@
<resources> <resources>
<string name="lib_name">libappbase</string> <string name="lib_name">libappbase</string>
<string name="hello_world">Hello, world!</string> <string name="hello_world">Hello world!</string>
<string name="action_sos">cc.winboll.studio.libappbase.action.SOS</string>
</resources> </resources>

View File

@@ -1,8 +1,8 @@
#Created by .winboll/winboll_app_build.gradle #Created by .winboll/winboll_app_build.gradle
#Thu Oct 02 13:16:14 GMT 2025 #Fri Oct 03 23:10:42 HKT 2025
stageCount=8 stageCount=10
libraryProject= libraryProject=
baseVersion=15.0 baseVersion=15.0
publishVersion=15.0.7 publishVersion=15.0.9
buildCount=29 buildCount=0
baseBetaVersion=15.0.8 baseBetaVersion=15.0.10

View File

@@ -5,23 +5,27 @@ package cc.winboll.studio.positions.activities;
* @Date 2025/09/29 18:22 * @Date 2025/09/29 18:22
* @Describe 位置列表页面适配MainService GPS接口+规范服务交互+完善生命周期) * @Describe 位置列表页面适配MainService GPS接口+规范服务交互+完善生命周期)
*/ */
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity; import android.app.Activity;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection; import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import cc.winboll.studio.libappbase.LogUtils; import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils;
import cc.winboll.studio.positions.R;
import cc.winboll.studio.positions.adapters.PositionAdapter; import cc.winboll.studio.positions.adapters.PositionAdapter;
import cc.winboll.studio.positions.models.PositionModel; import cc.winboll.studio.positions.models.PositionModel;
import cc.winboll.studio.positions.models.PositionTaskModel;
import cc.winboll.studio.positions.services.MainService; import cc.winboll.studio.positions.services.MainService;
import cc.winboll.studio.positions.R;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* Java 7 语法适配: * Java 7 语法适配:
@@ -30,37 +34,65 @@ import java.util.ArrayList;
* 3. 所有位置/任务操作通过 MainService 接口执行 * 3. 所有位置/任务操作通过 MainService 接口执行
*/ */
public class LocationActivity extends Activity { public class LocationActivity extends Activity {
private static final String TAG = "LocationActivity"; public static final String TAG = "LocationActivity";
private RecyclerView mRvPosition; private RecyclerView mRvPosition;
private PositionAdapter mPositionAdapter; private PositionAdapter mPositionAdapter;
private ArrayList<PositionModel> mLocalPosCache; // 本地位置缓存与MainService同步
// MainService 引用+绑定状态AtomicBoolean 确保多线程状态可见性)
// MainService 引用+绑定状态
private MainService mMainService; private MainService mMainService;
private boolean isServiceBound = false; private final AtomicBoolean isServiceBound = new AtomicBoolean(false);
// 标记 Adapter 是否已初始化(避免重复初始化/销毁后初始化)
private final AtomicBoolean isAdapterInited = new AtomicBoolean(false);
// 服务连接Java 7 匿名内部类实现) // ---------------------- 新增GPS监听核心变量 ----------------------
private MainService.GpsUpdateListener mGpsUpdateListener; // GPS监听实例
private PositionModel mCurrentGpsPos; // 缓存当前GPS位置供页面使用
// 本地位置缓存解决服务数据未同步时Adapter空数据问题
private final ArrayList<PositionModel> mLocalPosCache = new ArrayList<PositionModel>();
// 服务连接Java 7 匿名内部类实现,强化状态同步+数据预加载)
private ServiceConnection mServiceConnection = new ServiceConnection() { private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName name, IBinder service) { public void onServiceConnected(ComponentName name, IBinder service) {
// 假设 MainService 用 LocalBinder 暴露实例Java 7 强转 // 1. 安全获取服务实例(避免强转失败+服务未就绪
MainService.LocalBinder binder = (MainService.LocalBinder) service; if (!(service instanceof MainService.LocalBinder)) {
mMainService = binder.getService(); LogUtils.e(TAG, "服务绑定失败Binder类型不匹配非MainService.LocalBinder");
isServiceBound = true; isServiceBound.set(false);
return;
}
LogUtils.d(TAG, "MainService绑定成功开始同步数据"); try {
// 从MainService同步初始数据位置+任务) MainService.LocalBinder binder = (MainService.LocalBinder) service;
syncDataFromMainService(); mMainService = binder.getService();
// 初始化Adapter传入MainService实例确保任务数据从服务获取 // 2. 标记服务绑定成功(原子操作,确保多线程可见
initPositionAdapter(); isServiceBound.set(true);
LogUtils.d(TAG, "MainService绑定成功开始同步数据+初始化Adapter");
// 3. 同步服务数据到本地缓存核心先同步数据再初始化Adapter
syncDataFromMainService();
// 4. 注册GPS监听确保监听在Adapter前初始化数据不丢失
registerGpsListener();
// 5. 初始化Adapter传入本地缓存+服务实例,数据非空)
initPositionAdapter();
} catch (Exception e) {
LogUtils.d(TAG, "服务绑定后初始化失败:" + e.getMessage());
isServiceBound.set(false);
mMainService = null;
showToast("服务初始化失败,无法加载数据");
}
} }
@Override @Override
public void onServiceDisconnected(ComponentName name) { public void onServiceDisconnected(ComponentName name) {
LogUtils.w(TAG, "MainService断开连接清空引用"); LogUtils.w(TAG, "MainService断开连接清空引用+标记状态");
// 1. 清空服务引用+标记绑定状态
mMainService = null; mMainService = null;
isServiceBound = false; isServiceBound.set(false);
// 2. 标记Adapter未初始化下次绑定需重新初始化
isAdapterInited.set(false);
} }
}; };
@@ -69,159 +101,361 @@ public class LocationActivity extends Activity {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location); setContentView(R.layout.activity_location);
// 初始化视图+本地缓存 // 1. 初始化视图优先执行避免Adapter初始化时视图为空
initView(); initView();
mLocalPosCache = new ArrayList<PositionModel>(); // 2. 初始化GPS监听提前创建避免绑定服务后空指针
initGpsUpdateListener();
// 绑定MainService确保Activity启动时就拿到服务实例 // 3. 绑定MainService最后执行,确保视图/监听已就绪
bindMainService(); bindMainService();
} }
/** /**
* 初始化视图RecyclerView * 初始化视图RecyclerView- 确保视图先于Adapter初始化
*/ */
private void initView() { private void initView() {
mRvPosition = (RecyclerView) findViewById(R.id.rv_position_list); mRvPosition = (RecyclerView) findViewById(R.id.rv_position_list);
// Java 7 显式设置布局管理器(LinearLayoutManager // 1. 显式设置布局管理器(避免Adapter设置时无布局管理器崩溃
LinearLayoutManager layoutManager = new LinearLayoutManager(this); LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL); layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRvPosition.setLayoutManager(layoutManager); mRvPosition.setLayoutManager(layoutManager);
// 2. 初始化本地缓存(避免首次加载时缓存为空)
mLocalPosCache.clear();
LogUtils.d(TAG, "视图初始化完成(布局管理器+本地缓存已就绪)");
} }
/** /**
* 绑定MainServiceJava 7 显式Intent * 绑定MainServiceJava 7 显式Intent,强化绑定安全性
*/ */
private void bindMainService() { private void bindMainService() {
// 1. 避免重复绑定快速重建Activity时防止多绑定
if (isServiceBound.get()) {
LogUtils.w(TAG, "无需重复绑定MainService已绑定");
return;
}
Intent serviceIntent = new Intent(this, MainService.class); Intent serviceIntent = new Intent(this, MainService.class);
// 绑定服务BIND_AUTO_CREATE服务不存在时自动创建 // 2. 绑定服务BIND_AUTO_CREATE服务不存在时自动创建,增加绑定成功率
bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE); boolean bindSuccess = bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
LogUtils.d(TAG, "发起MainService绑定请求"); if (!bindSuccess) {
LogUtils.e(TAG, "发起MainService绑定请求失败服务未找到/系统限制)");
showToast("服务绑定失败,无法加载位置数据");
} else {
LogUtils.d(TAG, "MainService绑定请求已发起");
}
} }
/** /**
* 从MainService同步数据(位置+任务 * 从MainService同步数据到本地缓存核心解决Adapter空数据问题
* 作用1. 服务数据优先同步到本地Adapter基于本地缓存初始化
* 2. 避免服务数据更新时直接操作Adapter通过缓存中转
*/ */
private void syncDataFromMainService() { private void syncDataFromMainService() {
if (!isServiceBound || mMainService == null) { // 1. 安全校验(服务未绑定/服务空,用本地缓存兜底)
LogUtils.w(TAG, "同步数据失败MainService未绑定"); if (!isServiceBound.get() || mMainService == null) {
showToast("服务未就绪,无法加载数据"); LogUtils.w(TAG, "同步数据:服务未就绪,使用本地缓存(当前缓存量=" + mLocalPosCache.size() + "");
return; return;
} }
// 同步位置数据(从服务获取最新列表) try {
ArrayList<PositionModel> servicePosList = mMainService.getPositionList(); // 2. 从服务获取最新位置数据(同步操作,确保数据拿到后再返回)
if (servicePosList != null && !servicePosList.isEmpty()) { ArrayList<PositionModel> servicePosList = mMainService.getPositionList();
mLocalPosCache.clear(); // 3. 同步到本地缓存(清空旧数据+添加新数据,避免重复)
mLocalPosCache.addAll(servicePosList); synchronized (mLocalPosCache) { // 加锁避免多线程操作缓存冲突
LogUtils.d(TAG, "从MainService同步位置数据完成数量=" + mLocalPosCache.size()); mLocalPosCache.clear();
} if (servicePosList != null && !servicePosList.isEmpty()) {
mLocalPosCache.addAll(servicePosList);
}
}
LogUtils.d(TAG, "数据同步完成:服务位置数=" + (servicePosList == null ? 0 : servicePosList.size())
+ ",本地缓存数=" + mLocalPosCache.size());
// 同步任务数据无需本地缓存Adapter直接从服务获取 } catch (Exception e) {
ArrayList<PositionTaskModel> serviceTaskList = mMainService.getAllTasks(); LogUtils.d(TAG, "同步服务数据失败:" + e.getMessage());
LogUtils.d(TAG, "从MainService同步任务数据完成数量=" + serviceTaskList.size()); // 异常时保留本地缓存避免Adapter无数据
LogUtils.w(TAG, "同步失败,使用本地缓存兜底(缓存量=" + mLocalPosCache.size() + "");
}
} }
/** /**
* 初始化PositionAdapter核心传入MainService实例 * 初始化PositionAdapter核心优化:基于本地缓存初始化,避免空数据
*/ */
private void initPositionAdapter() { private void initPositionAdapter() {
if (mMainService == null) { // 1. 多重安全校验(避免销毁后初始化/重复初始化/依赖未就绪)
LogUtils.e(TAG, "初始化Adapter失败MainService为空"); if (isAdapterInited.get() || !isServiceBound.get() || mMainService == null || mRvPosition == null) {
LogUtils.w(TAG, "Adapter初始化跳过"
+ "已初始化=" + isAdapterInited.get()
+ ",服务绑定=" + isServiceBound.get()
+ ",视图就绪=" + (mRvPosition != null));
return; return;
} }
// Java 7 显式初始化Adapter传入上下文+本地位置缓存+MainService实例 try {
mPositionAdapter = new PositionAdapter(this, mLocalPosCache, mMainService); // 2. 基于本地缓存初始化Adapter缓存已同步服务数据非空
mPositionAdapter = new PositionAdapter(this, mLocalPosCache, mMainService);
// 设置Adapter回调处理位置删除/保存最终同步到MainService // 3. 设置删除回调(删除时同步服务+本地缓存+Adapter
mPositionAdapter.setOnDeleteClickListener(new PositionAdapter.OnDeleteClickListener() { mPositionAdapter.setOnDeleteClickListener(new PositionAdapter.OnDeleteClickListener() {
@Override @Override
public void onDeleteClick(int position) { public void onDeleteClick(int position) {
// 删除逻辑先删本地缓存再调用MainService接口删服务数据 // 安全校验(索引有效+服务绑定+缓存非空)
if (position < 0 || position >= mLocalPosCache.size()) { if (position < 0 || position >= mLocalPosCache.size() || !isServiceBound.get() || mMainService == null) {
LogUtils.w(TAG, "删除位置失败:无效索引=" + position); LogUtils.w(TAG, "删除位置失败:索引无效/服务未就绪(索引=" + position + ",缓存量=" + mLocalPosCache.size() + "");
return; return;
} }
PositionModel deletePos = mLocalPosCache.get(position);
if (deletePos != null && !deletePos.getPositionId().isEmpty()) {
// 1. 调用MainService接口删除服务端数据
mMainService.removePosition(deletePos.getPositionId());
// 2. 删除本地缓存数据
mLocalPosCache.remove(position);
// 3. 通知Adapter刷新
mPositionAdapter.notifyItemRemoved(position);
showToast("删除位置成功:" + deletePos.getMemo());
LogUtils.d(TAG, "删除位置完成ID=" + deletePos.getPositionId() + "已同步MainService");
}
}
});
mPositionAdapter.setOnSavePositionClickListener(new PositionAdapter.OnSavePositionClickListener() { PositionModel deletePos = mLocalPosCache.get(position);
@Override if (deletePos != null && !deletePos.getPositionId().isEmpty()) {
public void onSavePositionClick(int position, PositionModel updatedPos) { // 步骤1调用服务删除确保服务数据一致性
// 保存逻辑先更本地缓存再调用MainService接口更新服务数据 mMainService.removePosition(deletePos.getPositionId());
if (!isServiceBound || mMainService == null) { // 步骤2删除本地缓存确保缓存与服务同步
LogUtils.w(TAG, "保存位置失败MainService未绑定"); synchronized (mLocalPosCache) {
showToast("服务未就绪,保存失败"); mLocalPosCache.remove(position);
return; }
} // 步骤3通知Adapter刷新基于缓存操作避免空数据
if (position < 0 || position >= mLocalPosCache.size()) { mPositionAdapter.notifyItemRemoved(position);
LogUtils.w(TAG, "保存位置失败:无效索引=" + position); showToast("删除位置成功:" + deletePos.getMemo());
return; LogUtils.d(TAG, "删除位置完成ID=" + deletePos.getPositionId() + "(服务+缓存已同步)");
} }
}
});
// 1. 调用MainService接口更新服务端数据 // 4. 设置保存回调(保存时同步服务+本地缓存+Adapter
mMainService.updatePosition(updatedPos); mPositionAdapter.setOnSavePositionClickListener(new PositionAdapter.OnSavePositionClickListener() {
// 2. 更新本地缓存数据 @Override
mLocalPosCache.set(position, updatedPos); public void onSavePositionClick(int position, PositionModel updatedPos) {
// 3. 通知Adapter刷新可选Adapter已本地同步 // 安全校验(索引有效+服务绑定+数据非空
mPositionAdapter.notifyItemChanged(position); if (!isServiceBound.get() || mMainService == null
showToast("保存位置成功:" + updatedPos.getMemo()); || position < 0 || position >= mLocalPosCache.size() || updatedPos == null) {
LogUtils.d(TAG, "保存位置完成ID=" + updatedPos.getPositionId() + "已同步MainService"); LogUtils.w(TAG, "保存位置失败:服务未就绪/索引无效/数据空");
} showToast("服务未就绪,保存失败");
}); return;
}
// 设置Adapter到RecyclerView // 步骤1调用服务更新确保服务数据一致性
mRvPosition.setAdapter(mPositionAdapter); mMainService.updatePosition(updatedPos);
LogUtils.d(TAG, "PositionAdapter初始化完成已绑定MainService"); // 步骤2更新本地缓存确保缓存与服务同步
synchronized (mLocalPosCache) {
mLocalPosCache.set(position, updatedPos);
}
// 步骤3通知Adapter刷新基于缓存操作避免空数据
mPositionAdapter.notifyItemChanged(position);
showToast("保存位置成功:" + updatedPos.getMemo());
LogUtils.d(TAG, "保存位置完成ID=" + updatedPos.getPositionId() + "(服务+缓存已同步)");
}
});
// 5. 设置Adapter到RecyclerView最后一步确保Adapter已配置完成
mRvPosition.setAdapter(mPositionAdapter);
// 6. 标记Adapter已初始化避免重复初始化
isAdapterInited.set(true);
LogUtils.d(TAG, "PositionAdapter初始化完成基于本地缓存数据量=" + mLocalPosCache.size() + "");
} catch (Exception e) {
LogUtils.d(TAG, "Adapter初始化失败" + e.getMessage());
isAdapterInited.set(false);
mPositionAdapter = null;
showToast("位置列表初始化失败,请重试");
}
} }
/** /**
* 显示ToastJava 7 显式Toast.makeText * 显示ToastJava 7 显式Toast.makeText避免空Context
*/ */
private void showToast(String content) { private void showToast(String content) {
if (isFinishing() || isDestroyed()) { // 避免Activity销毁后弹Toast崩溃
LogUtils.w(TAG, "Activity已销毁跳过Toast" + content);
return;
}
Toast.makeText(this, content, Toast.LENGTH_SHORT).show(); Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
} }
// ---------------------- 页面交互新增位置逻辑保留适配GPS数据 ----------------------
/**
* 新增位置调用服务addPosition()可选用当前GPS位置初始化新位置
*/
public void addNewPosition(View view) {
// 1. 隐藏软键盘(避免软键盘遮挡操作)
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null && getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
// 2. 安全校验(服务未绑定,不允许新增)
if (!isServiceBound.get() || mMainService == null) {
LogUtils.w(TAG, "新增位置失败MainService未绑定");
showToast("服务未就绪,无法新增位置");
return;
}
// 3. 创建新位置模型优化优先用当前GPS位置初始化无则用默认值
PositionModel newPos = new PositionModel();
newPos.setPositionId(PositionModel.genPositionId()); // 生成唯一ID需PositionModel实现
if (mCurrentGpsPos != null) {
newPos.setLongitude(mCurrentGpsPos.getLongitude());
newPos.setLatitude(mCurrentGpsPos.getLatitude());
newPos.setMemo("当前GPS位置可编辑");
} else {
newPos.setLongitude(116.404267); // 北京经度(默认值)
newPos.setLatitude(39.915119); // 北京纬度(默认值)
newPos.setMemo("默认位置(可编辑备注)");
}
newPos.setIsSimpleView(true); // 默认简单视图
newPos.setIsEnableRealPositionDistance(true); // 启用距离计算依赖GPS
// 4. 调用服务新增+同步本地缓存(确保缓存与服务一致)
mMainService.addPosition(newPos);
synchronized (mLocalPosCache) {
mLocalPosCache.add(newPos);
}
LogUtils.d(TAG, "通过服务新增位置ID=" + newPos.getPositionId() + ",纬度=" + newPos.getLatitude() + "(缓存已同步)");
// 5. 刷新Adapter基于缓存操作确保数据立即显示
if (isAdapterInited.get() && mPositionAdapter != null) {
mPositionAdapter.notifyItemInserted(mLocalPosCache.size() - 1);
}
showToast("新增位置成功已启用GPS距离计算");
}
// ---------------------- 新增GPS监听初始化+注册/反注册(核心适配逻辑) ----------------------
/**
* 初始化GPS监听实现MainService.GpsUpdateListener接收实时GPS数据
*/
private void initGpsUpdateListener() {
LogUtils.d(TAG, "initGpsUpdateListener()");
mGpsUpdateListener = new MainService.GpsUpdateListener() {
@Override
public void onGpsPositionUpdated(PositionModel currentGpsPos) {
if (currentGpsPos == null || isFinishing() || isDestroyed()) {
LogUtils.w(TAG, "GPS位置更新数据为空或Activity已销毁");
return;
}
// 缓存当前GPS位置供页面其他逻辑使用
mCurrentGpsPos = currentGpsPos;
LogUtils.d(TAG, String.format("收到GPS更新纬度=%.4f,经度=%.4f"
, currentGpsPos.getLatitude(), currentGpsPos.getLongitude()));
// 安全更新UI避免Activity销毁后操作视图崩溃
((TextView)findViewById(R.id.tv_latitude)).setText(String.format("当前纬度:%f", currentGpsPos.getLatitude()));
((TextView)findViewById(R.id.tv_longitude)).setText(String.format("当前经度:%f", currentGpsPos.getLongitude()));
}
@Override
public void onGpsStatusChanged(String status) {
if (status == null || isFinishing() || isDestroyed()) return;
LogUtils.d(TAG, "GPS状态变化" + status);
if (status.contains("未开启") || status.contains("权限") || status.contains("失败")) {
ToastUtils.show("GPS提示" + status);
}
}
};
}
/**
* 注册GPS监听调用MainService的PUBLIC方法绑定监听
*/
private void registerGpsListener() {
// 安全校验避免Activity销毁/服务未绑定/监听为空时注册)
if (isFinishing() || isDestroyed() || !isServiceBound.get() || mMainService == null || mGpsUpdateListener == null) {
LogUtils.w(TAG, "GPS监听注册跳过Activity状态异常/依赖未就绪");
return;
}
try {
mMainService.registerGpsUpdateListener(mGpsUpdateListener);
LogUtils.d(TAG, "GPS监听已注册");
} catch (Exception e) {
LogUtils.d(TAG, "GPS监听注册失败" + e.getMessage());
}
}
/**
* 反注册GPS监听调用MainService的PUBLIC方法解绑监听核心防内存泄漏+数据异常)
*/
private void unregisterGpsListener() {
// 避免Activity销毁后调用服务方法防止空指针/服务已解绑)
if (mMainService == null || mGpsUpdateListener == null) {
LogUtils.w(TAG, "GPS监听反注册跳过服务/监听未初始化");
return;
}
try {
mMainService.unregisterGpsUpdateListener(mGpsUpdateListener);
LogUtils.d(TAG, "GPS监听已反注册");
} catch (Exception e) {
LogUtils.d(TAG, "GPS监听反注册失败" + e.getMessage());
}
}
/**
* 页面可见时同步数据(解决快速切回时数据未更新问题)
* 场景快速关闭再打开Activity服务已绑定但数据未重新同步
*/
@Override
protected void onResume() {
super.onResume();
// 1. 服务已绑定但Adapter未初始化重新同步数据+初始化Adapter
if (isServiceBound.get() && mMainService != null && !isAdapterInited.get()) {
LogUtils.d(TAG, "onResume服务已绑定但Adapter未初始化重新同步数据");
syncDataFromMainService();
initPositionAdapter();
}
// 2. 服务已绑定且Adapter已初始化刷新数据确保与服务同步
else if (isServiceBound.get() && mMainService != null && isAdapterInited.get() && mPositionAdapter != null) {
syncDataFromMainService();
mPositionAdapter.notifyDataSetChanged();
LogUtils.d(TAG, "onResume刷新位置数据与服务同步");
}
}
/**
* 页面不可见时暂停操作(避免后台操作导致数据异常)
*/
@Override
protected void onPause() {
super.onPause();
// 避免后台时仍执行UI刷新如GPS更新触发的视图操作
LogUtils.d(TAG, "onPause页面不可见暂停UI相关操作");
}
@Override @Override
protected void onDestroy() { protected void onDestroy() {
super.onDestroy(); super.onDestroy();
LogUtils.d(TAG, "onDestroy开始释放资源");
// 1. 释放Adapter资源反注册服务监听避免内存泄漏) // 1. 反注册GPS监听优先执行避免服务持有Activity引用导致内存泄漏)
unregisterGpsListener();
// 2. 释放Adapter资源反注册可能的监听避免内存泄漏
if (mPositionAdapter != null) { if (mPositionAdapter != null) {
mPositionAdapter.release(); mPositionAdapter.release();
mPositionAdapter = null; // 清空引用帮助GC回收
LogUtils.d(TAG, "Adapter资源已释放");
} }
// 2. 解绑MainService避免Activity销毁后服务仍被持有 // 3. 解绑MainService最后执行,确保其他资源已释放
if (isServiceBound) { if (isServiceBound.get()) {
unbindService(mServiceConnection); try {
LogUtils.d(TAG, "MainService解绑完成"); unbindService(mServiceConnection);
LogUtils.d(TAG, "MainService解绑完成");
} catch (IllegalArgumentException e) {
// 捕获“服务未绑定”异常(快速开关时可能出现,避免崩溃)
LogUtils.d(TAG, "解绑MainService失败服务未绑定可能已提前解绑");
}
// 重置绑定状态+服务引用
isServiceBound.set(false);
mMainService = null;
} }
// 4. 清空本地缓存+GPS引用帮助GC回收
synchronized (mLocalPosCache) {
mLocalPosCache.clear();
}
mCurrentGpsPos = null;
mGpsUpdateListener = null;
isAdapterInited.set(false);
LogUtils.d(TAG, "所有资源释放完成onDestroy执行结束");
} }
public static class LocalBinder extends android.os.Binder {
// 持有 MainService 实例引用
private MainService mService;
// 构造时传入服务实例 // ---------------------- 移除重复定义LocalBinder 统一在 MainService 中定义 ----------------------
public LocalBinder(MainService service) { // 说明原LocationActivity中的LocalBinder是重复定义(MainService已实现),会导致类型强转失败
this.mService = service; // 此处删除该类确保Activity绑定服务时强转的是MainService中的LocalBinder
}
// 对外提供获取服务实例的方法供Activity调用
public MainService getService() {
return mService;
}
}
} }

View File

@@ -3,7 +3,7 @@ package cc.winboll.studio.positions.adapters;
/** /**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/09/29 20:25 * @Date 2025/09/29 20:25
* @Describe 位置数据适配器(完全独立无未知接口依赖仅用LocationActivity缓存数据 * @Describe 位置数据适配器(集成PositionTaskListView移除未定义onDestroyJava 7语法适配
*/ */
import android.content.Context; import android.content.Context;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@@ -15,6 +15,7 @@ import android.widget.EditText;
import android.widget.RadioGroup; import android.widget.RadioGroup;
import android.widget.TextView; import android.widget.TextView;
import android.text.TextUtils; import android.text.TextUtils;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import cc.winboll.studio.libappbase.LogUtils; import cc.winboll.studio.libappbase.LogUtils;
@@ -22,6 +23,7 @@ import cc.winboll.studio.positions.R;
import cc.winboll.studio.positions.models.PositionModel; import cc.winboll.studio.positions.models.PositionModel;
import cc.winboll.studio.positions.models.PositionTaskModel; import cc.winboll.studio.positions.models.PositionTaskModel;
import cc.winboll.studio.positions.services.MainService; import cc.winboll.studio.positions.services.MainService;
import cc.winboll.studio.positions.views.PositionTaskListView;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
@@ -30,20 +32,20 @@ import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* Java 7 语法适配: * Java 7 语法严格适配:
* 1. 移除 Lambda/方法引用,匿名内部类替代 * 1. Lambda/方法引用,匿名内部类实现回调
* 2. 集合操作使用迭代器(避免 ConcurrentModificationException * 2. 移除未定义的 taskView.onDestroy(),改用「清空数据+解绑监听」替代资源释放
* 3. 弱引用管理 MainService避免内存泄漏 * 3. 弱引用管理服务/控件,杜绝内存泄漏
* 4. 所有任务数据从 MainService 获取,更新通过 MainService 接口 * 4. PositionTaskListView 初始化/同步/资源释放全链路适配
*/ */
public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements MainService.TaskUpdateListener { public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements MainService.TaskUpdateListener {
public static final String TAG = "PositionAdapter"; public static final String TAG = "PositionAdapter";
// 视图类型常量(Java 7 静态常量定义 // 视图类型常量(静态常量统一管理
private static final int VIEW_TYPE_SIMPLE = 0; private static final int VIEW_TYPE_SIMPLE = 0;
private static final int VIEW_TYPE_EDIT = 1; private static final int VIEW_TYPE_EDIT = 1;
// 默认配置常量(统一管理,避免魔法值) // 默认配置常量(避免魔法值)
private static final String DEFAULT_MEMO = "无备注"; private static final String DEFAULT_MEMO = "无备注";
private static final String DEFAULT_TASK_DESC = "新任务"; private static final String DEFAULT_TASK_DESC = "新任务";
private static final int DEFAULT_TASK_DISTANCE = 50; // 单位:米 private static final int DEFAULT_TASK_DISTANCE = 50; // 单位:米
@@ -51,13 +53,17 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
private static final String DISTANCE_DISABLED = "实时距离:未启用"; private static final String DISTANCE_DISABLED = "实时距离:未启用";
private static final String DISTANCE_ERROR = "实时距离:计算失败"; private static final String DISTANCE_ERROR = "实时距离:计算失败";
// 核心依赖(Java 7 弱引用+集合定义 // 核心依赖(弱引用+线程安全集合适配Java 7
private final Context mContext; private final Context mContext;
private final ArrayList<PositionModel> mCachedPositionList; // 位置缓存(从Activity传入最终需与MainService同步 private final ArrayList<PositionModel> mCachedPositionList; // 位置缓存与MainService同步
private final WeakReference<MainService> mMainServiceRef; // 弱引用MainService避免内存泄漏 private final WeakReference<MainService> mMainServiceRef; // 弱引用MainService内存泄漏
private final ConcurrentHashMap<String, TextView> mPosDistanceViewMap; // 距离控件缓存优化UI更新 // 控件缓存位置ID → 对应任务列表视图(分别缓存简单/编辑模式,避免引用混淆
private final ConcurrentHashMap<String, PositionTaskListView> mSimpleTaskViewMap;
private final ConcurrentHashMap<String, PositionTaskListView> mEditTaskViewMap;
// 距离控件缓存用于局部更新距离UI
private final ConcurrentHashMap<String, TextView> mPosDistanceViewMap;
// 回调接口(与Activity交互仅处理位置逻辑任务逻辑直接调用MainService // 回调接口(仅处理位置逻辑任务逻辑通过PositionTaskListView+MainService完成
public interface OnDeleteClickListener { public interface OnDeleteClickListener {
void onDeleteClick(int position); void onDeleteClick(int position);
} }
@@ -70,42 +76,42 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
private OnSavePositionClickListener mOnSavePosListener; private OnSavePositionClickListener mOnSavePosListener;
// ========================================================================= // =========================================================================
// 构造函数(Java 7 风格:初始化依赖+注册务监听) // 构造函数(初始化依赖+注册务监听+初始化控件缓存
// ========================================================================= // =========================================================================
public PositionAdapter(Context context, ArrayList<PositionModel> cachedPositionList, MainService mainService) { public PositionAdapter(Context context, ArrayList<PositionModel> cachedPositionList, MainService mainService) {
this.mContext = context; this.mContext = context;
// 容错处理避免传入null导致空指针 // 容错处理避免传入null导致空指针
this.mCachedPositionList = (cachedPositionList != null) ? cachedPositionList : new ArrayList<PositionModel>(); this.mCachedPositionList = (cachedPositionList!= null)? cachedPositionList : new ArrayList<PositionModel>();
// 弱引用MainService防止Adapter持有Service导致内存泄漏Java 7 弱引用语法) // 弱引用MainService防止Adapter持有服务导致内存泄漏Java 7 弱引用语法)
this.mMainServiceRef = new WeakReference<MainService>(mainService); this.mMainServiceRef = new WeakReference<MainService>(mainService);
// 初始化距离控件缓存(线程安全集合,适配多线程更新场景) // 初始化控件缓存(线程安全集合,适配多线程更新场景)
this.mSimpleTaskViewMap = new ConcurrentHashMap<String, PositionTaskListView>();
this.mEditTaskViewMap = new ConcurrentHashMap<String, PositionTaskListView>();
this.mPosDistanceViewMap = new ConcurrentHashMap<String, TextView>(); this.mPosDistanceViewMap = new ConcurrentHashMap<String, TextView>();
// 注册MainService任务监听服务任务变化时自动刷新AdapterJava 7 接口实现) // 注册MainService任务监听服务任务变化时同步刷新任务列表视图
if (mainService != null) { if (mainService!= null) {
mainService.registerTaskUpdateListener(this); mainService.registerTaskUpdateListener(this);
LogUtils.d(TAG, "已注册MainService任务监听确保任务数据与服务同步"); LogUtils.d(TAG, "已注册MainService任务监听确保任务数据与服务同步");
} else { } else {
LogUtils.w(TAG, "构造函数MainService为空任务数据无法同步"); LogUtils.w(TAG, "构造函数MainService为空PositionTaskListView无法初始化");
} }
LogUtils.d(TAG, "Adapter初始化完成位置数量=" + mCachedPositionList.size()); LogUtils.d(TAG, "Adapter初始化完成位置数量=" + mCachedPositionList.size());
} }
// ========================================================================= // =========================================================================
// RecyclerView 核心方法(Java 7 语法适配 // RecyclerView 核心方法(视图类型判断+创建+绑定,集成任务列表视图
// ========================================================================= // =========================================================================
@Override @Override
public int getItemViewType(int position) { public int getItemViewType(int position) {
// 从位置缓存获取状态,判断视图类型(简单/编辑)
PositionModel posModel = getPositionByIndex(position); PositionModel posModel = getPositionByIndex(position);
return (posModel != null && posModel.isSimpleView()) ? VIEW_TYPE_SIMPLE : VIEW_TYPE_EDIT; return (posModel!= null && posModel.isSimpleView())? VIEW_TYPE_SIMPLE : VIEW_TYPE_EDIT;
} }
@Override @Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext); LayoutInflater inflater = LayoutInflater.from(mContext);
// 根据视图类型加载对应布局Java 7 条件判断)
if (viewType == VIEW_TYPE_SIMPLE) { if (viewType == VIEW_TYPE_SIMPLE) {
View simpleView = inflater.inflate(R.layout.item_position_simple, parent, false); View simpleView = inflater.inflate(R.layout.item_position_simple, parent, false);
return new SimpleViewHolder(simpleView); return new SimpleViewHolder(simpleView);
@@ -122,65 +128,100 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
LogUtils.w(TAG, "onBindViewHolder位置模型为空索引=" + position + "),跳过绑定"); LogUtils.w(TAG, "onBindViewHolder位置模型为空索引=" + position + "),跳过绑定");
return; return;
} }
String posId = posModel.getPositionId(); final String posId = posModel.getPositionId();
MainService mainService = mMainServiceRef.get();
// 按视图类型绑定数据(Java 7 类型判断 // 按视图类型绑定数据(简单模式/编辑模式
if (holder instanceof SimpleViewHolder) { if (holder instanceof SimpleViewHolder) {
bindSimpleView((SimpleViewHolder) holder, posModel); SimpleViewHolder simpleHolder = (SimpleViewHolder) holder;
} else if (holder instanceof EditViewHolder) { // 1. 绑定位置基础数据(经纬度/备注/距离)
bindEditView((EditViewHolder) holder, posModel, position); bindSimplePositionData(simpleHolder, posModel);
} // 2. 初始化+绑定简单模式任务列表视图(仅显示已启用任务)
initAndBindSimpleTaskView(simpleHolder.ptlvSimpleTasks, posId, mainService);
// 3. 缓存简单模式任务视图+距离控件
mSimpleTaskViewMap.put(posId, simpleHolder.ptlvSimpleTasks);
mPosDistanceViewMap.put(posId, simpleHolder.tvSimpleDistance);
// 缓存当前位置的距离控件(后续局部更新距离时直接使用) } else if (holder instanceof EditViewHolder) {
TextView distanceView = (holder instanceof SimpleViewHolder) EditViewHolder editHolder = (EditViewHolder) holder;
? ((SimpleViewHolder) holder).tvSimpleDistance // 1. 绑定位置基础数据(经纬度/备注/距离/距离开关)
: ((EditViewHolder) holder).tvEditDistance; bindEditPositionData(editHolder, posModel, position);
if (distanceView != null && !TextUtils.isEmpty(posId)) { // 2. 初始化+绑定编辑模式任务列表视图(支持增删改查)
mPosDistanceViewMap.put(posId, distanceView); initAndBindEditTaskView(editHolder.ptlvEditTasks, posId, mainService, editHolder.btnAddTask);
// 3. 缓存编辑模式任务视图+距离控件
mEditTaskViewMap.put(posId, editHolder.ptlvEditTasks);
mPosDistanceViewMap.put(posId, editHolder.tvEditDistance);
} }
} }
@Override @Override
public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) { public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
super.onViewDetachedFromWindow(holder); super.onViewDetachedFromWindow(holder);
// 视图离开屏幕时,移除距离控件缓存(避免内存泄漏+引用失效控件 // 视图离开屏幕时:清空对应控件缓存+释放任务列表视图资源移除未定义的onDestroy()
PositionModel posModel = getPositionByIndex(holder.getAdapterPosition()); PositionModel posModel = getPositionByIndex(holder.getAdapterPosition());
if (posModel != null && !TextUtils.isEmpty(posModel.getPositionId())) { if (posModel == null || TextUtils.isEmpty(posModel.getPositionId())) {
mPosDistanceViewMap.remove(posModel.getPositionId()); return;
LogUtils.d(TAG, "视图脱离屏幕移除位置ID=" + posModel.getPositionId() + "的距离控件缓存"); }
String posId = posModel.getPositionId();
// 1. 移除距离控件缓存
if (mPosDistanceViewMap.containsKey(posId)) {
mPosDistanceViewMap.remove(posId);
LogUtils.d(TAG, "视图脱离屏幕移除位置ID=" + posId + "的距离控件缓存");
}
// 2. 释放简单模式任务视图资源(清空数据+解绑监听替代onDestroy()
if (holder instanceof SimpleViewHolder && mSimpleTaskViewMap.containsKey(posId)) {
PositionTaskListView taskView = mSimpleTaskViewMap.get(posId);
if (taskView != null) {
taskView.clearData(); // 清空任务数据(假设视图已实现该方法,用于释放列表数据)
taskView.setOnTaskUpdatedListener(null); // 解绑任务更新监听,避免内存泄漏
}
mSimpleTaskViewMap.remove(posId);
LogUtils.d(TAG, "简单模式视图脱离屏幕释放任务列表视图资源位置ID=" + posId + "");
}
// 3. 释放编辑模式任务视图资源(清空数据+解绑监听替代onDestroy()
if (holder instanceof EditViewHolder && mEditTaskViewMap.containsKey(posId)) {
PositionTaskListView taskView = mEditTaskViewMap.get(posId);
if (taskView != null) {
taskView.clearData(); // 清空任务数据
taskView.setOnTaskUpdatedListener(null); // 解绑任务更新监听
}
mEditTaskViewMap.remove(posId);
LogUtils.d(TAG, "编辑模式视图脱离屏幕释放任务列表视图资源位置ID=" + posId + "");
} }
} }
@Override @Override
public int getItemCount() { public int getItemCount() {
// 直接从位置缓存获取数量(数据源唯一)
return mCachedPositionList.size(); return mCachedPositionList.size();
} }
// ========================================================================= // =========================================================================
// 视图绑定逻辑Java 7 风格任务数据从MainService获取 // 位置数据绑定(分简单/编辑模式,独立逻辑解耦
// ========================================================================= // =========================================================================
/** /**
* 绑定简单视图(仅显示数据,点击切换到编辑视图 * 绑定简单模式位置数据(仅显示,无编辑操作
*/ */
private void bindSimpleView(final SimpleViewHolder holder, final PositionModel posModel) { private void bindSimplePositionData(SimpleViewHolder holder, final PositionModel posModel) {
// 1. 显示经纬度Java 7 String.format格式化 // 1. 经纬度显示保留6位小数格式统一
holder.tvSimpleLon.setText(String.format("经度:%.6f", posModel.getLongitude())); holder.tvSimpleLon.setText(String.format("经度:%.6f", posModel.getLongitude()));
holder.tvSimpleLat.setText(String.format("纬度:%.6f", posModel.getLatitude())); holder.tvSimpleLat.setText(String.format("纬度:%.6f", posModel.getLatitude()));
// 2. 显示备注(无备注时显示默认文本) // 2. 备注显示(无备注时显示默认文本)
String memo = posModel.getMemo(); String memo = posModel.getMemo();
holder.tvSimpleMemo.setText("备注:" + (TextUtils.isEmpty(memo) ? DEFAULT_MEMO : memo)); holder.tvSimpleMemo.setText("备注:" + (TextUtils.isEmpty(memo)? DEFAULT_MEMO : memo));
// 3. 显示实时距离(从位置模型取数,调用工具方法更新显示 // 3. 实时距离显示(按状态区分文本+颜色
updateDistanceDisplay(holder.tvSimpleDistance, posModel); updateDistanceDisplay(holder.tvSimpleDistance, posModel);
// 4. 点击切换到编辑视图Java 7 匿名内部类实现点击事件) // 4. 点击切换到编辑模式
holder.itemView.setOnClickListener(new View.OnClickListener() { holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
posModel.setIsSimpleView(false); // 修改位置缓存状态 posModel.setIsSimpleView(false);
// 通知RecyclerView刷新当前项(精准更新,避免全量刷新) // 精准刷新当前项(避免全量刷新)
notifyItemChanged(getPositionIndexById(posModel.getPositionId())); notifyItemChanged(getPositionIndexById(posModel.getPositionId()));
LogUtils.d(TAG, "简单视图点击位置ID=" + posModel.getPositionId() + ",切换到编辑视图"); LogUtils.d(TAG, "简单视图点击位置ID=" + posModel.getPositionId() + ",切换到编辑视图");
} }
@@ -188,151 +229,186 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
} }
/** /**
* 绑定编辑视图(支持修改备注、开关距离、删除/保存位置、新增任务 * 绑定编辑模式位置数据(支持备注修改/距离开关/删除/保存
*/ */
private void bindEditView(final EditViewHolder holder, final PositionModel posModel, final int position) { private void bindEditPositionData(final EditViewHolder holder, final PositionModel posModel, final int position) {
final String posId = posModel.getPositionId(); final String posId = posModel.getPositionId();
// 1. 显示经纬度(不可编辑,仅展示) // 1. 经纬度显示(不可编辑,仅展示)
holder.tvEditLon.setText(String.format("经度:%.6f", posModel.getLongitude())); holder.tvEditLon.setText(String.format("经度:%.6f", posModel.getLongitude()));
holder.tvEditLat.setText(String.format("纬度:%.6f", posModel.getLatitude())); holder.tvEditLat.setText(String.format("纬度:%.6f", posModel.getLatitude()));
// 2. 显示备注编辑框赋值,光标定位到末尾) // 2. 备注编辑(填充现有备注,光标定位到末尾)
String memo = posModel.getMemo(); String memo = posModel.getMemo();
if (!TextUtils.isEmpty(memo)) { if (!TextUtils.isEmpty(memo)) {
holder.etEditMemo.setText(memo); holder.etEditMemo.setText(memo);
holder.etEditMemo.setSelection(memo.length()); // 光标定位到文本末尾 holder.etEditMemo.setSelection(memo.length());
} else { } else {
holder.etEditMemo.setText(""); // 无备注时清空编辑框 holder.etEditMemo.setText("");
} }
// 3. 显示实时距离(与简单视图逻辑一致) // 3. 实时距离显示(与简单模式逻辑一致)
updateDistanceDisplay(holder.tvEditDistance, posModel); updateDistanceDisplay(holder.tvEditDistance, posModel);
// 4. 设置距离开关状态(匹配位置缓存中的启用状态) // 4. 距离开关状态(匹配位置模型中的启用状态)
holder.rgDistanceSwitch.check(posModel.isEnableRealPositionDistance() holder.rgDistanceSwitch.check(posModel.isEnableRealPositionDistance()
? R.id.rb_distance_enable ? R.id.rb_distance_enable
: R.id.rb_distance_disable); : R.id.rb_distance_disable);
// 5. 取消编辑:切换回简单视图Java 7 匿名内部类) // 5. 取消编辑:切换回简单模式+隐藏软键盘
holder.btnCancel.setOnClickListener(new View.OnClickListener() { holder.btnCancel.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
posModel.setIsSimpleView(true); posModel.setIsSimpleView(true);
notifyItemChanged(position); notifyItemChanged(position);
hideSoftKeyboard(v); // 隐藏软键盘(提升用户体验) hideSoftKeyboard(v);
LogUtils.d(TAG, "取消编辑位置ID=" + posId + ",切换回简单视图"); LogUtils.d(TAG, "取消编辑位置ID=" + posId + ",切换回简单视图");
} }
}); });
// 6. 删除位置回调Activity处理Adapter不直接删数据由Activity同步MainService // 6. 删除位置回调Activity处理Adapter不直接操作数据
holder.btnDelete.setOnClickListener(new View.OnClickListener() { holder.btnDelete.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (mOnDeleteListener != null) { if (mOnDeleteListener != null) {
mOnDeleteListener.onDeleteClick(position); // 通知Activity删除指定索引 mOnDeleteListener.onDeleteClick(position);
} }
hideSoftKeyboard(v); hideSoftKeyboard(v);
LogUtils.d(TAG, "触发删除通知Activity处理位置ID=" + posId + "的删除逻辑"); LogUtils.d(TAG, "触发删除通知Activity处理位置ID=" + posId + "的删除逻辑");
} }
}); });
// 7. 保存位置:回调Activity保存收集参数→构建更新模型→通知Activity // 7. 保存位置:收集参数→更新模型→回调Activity→切换视图
holder.btnSave.setOnClickListener(new View.OnClickListener() { holder.btnSave.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
// 收集编辑后的参数(备注+距离启用状态) // 收集编辑后的数据
String newMemo = holder.etEditMemo.getText().toString().trim(); String newMemo = holder.etEditMemo.getText().toString().trim();
boolean isDistanceEnable = (holder.rgDistanceSwitch.getCheckedRadioButtonId() == R.id.rb_distance_enable); boolean isDistanceEnable = (holder.rgDistanceSwitch.getCheckedRadioButtonId() == R.id.rb_distance_enable);
// 构建更新后的位置模型(保留核心数据,仅更新可编辑字段) // 构建更新后的位置模型(保留核心可编辑字段)
PositionModel updatedPos = new PositionModel(); PositionModel updatedPos = new PositionModel();
updatedPos.setPositionId(posId); // 保留原ID不可修改 updatedPos.setPositionId(posId);
updatedPos.setLongitude(posModel.getLongitude()); // 保留原经度(不可编辑) updatedPos.setLongitude(posModel.getLongitude());
updatedPos.setLatitude(posModel.getLatitude()); // 保留原纬度(不可编辑) updatedPos.setLatitude(posModel.getLatitude());
updatedPos.setMemo(newMemo); // 更新备注(用户编辑) updatedPos.setMemo(newMemo);
updatedPos.setIsEnableRealPositionDistance(isDistanceEnable); // 更新距离状态 updatedPos.setIsEnableRealPositionDistance(isDistanceEnable);
updatedPos.setIsSimpleView(true); // 切换回简单视图 updatedPos.setIsSimpleView(true);
// 回调Activity保存由Activity同步MainService+位置缓存Adapter不处理逻辑 // 回调Activity保存由Activity同步MainService
if (mOnSavePosListener != null) { if (mOnSavePosListener != null) {
mOnSavePosListener.onSavePositionClick(position, updatedPos); mOnSavePosListener.onSavePositionClick(position, updatedPos);
} }
// 本地同步状态(避免刷新延迟,直接修改位置缓存 // 本地同步状态(避免刷新延迟)
posModel.setMemo(newMemo); posModel.setMemo(newMemo);
posModel.setIsEnableRealPositionDistance(isDistanceEnable); posModel.setIsEnableRealPositionDistance(isDistanceEnable);
posModel.setIsSimpleView(true); posModel.setIsSimpleView(true);
notifyItemChanged(position); // 刷新当前项,显示更新后的状态 notifyItemChanged(position);
hideSoftKeyboard(v); hideSoftKeyboard(v);
LogUtils.d(TAG, "触发保存位置ID=" + posId + ",新备注=" + newMemo + ",距离启用=" + isDistanceEnable); LogUtils.d(TAG, "保存位置ID=" + posId + ",新备注=" + newMemo + ",距离启用=" + isDistanceEnable);
}
});
// 8. 绑定任务视图(显示任务数量+新增任务数据从MainService获取
bindTaskView(holder, posId);
}
/**
* 绑定任务视图编辑模式专属从MainService获取任务数据新增任务调用服务接口
*/
private void bindTaskView(final EditViewHolder holder, final String posId) {
// 1. 从MainService获取当前位置的任务数量Java 7 迭代器遍历服务数据)
int taskCount = 0;
MainService mainService = mMainServiceRef.get();
if (mainService != null) {
ArrayList<PositionTaskModel> posTasks = mainService.getTasksByPositionId(posId);
taskCount = (posTasks != null) ? posTasks.size() : 0;
}
// 显示任务数量(简化设计,实际可扩展为任务列表)
holder.tvTaskCount.setText("任务数量:" + taskCount);
// 2. 新增任务调用MainService接口不操作本地缓存数据直接写入服务
holder.btnAddTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainService mainService = mMainServiceRef.get();
if (mainService == null) {
LogUtils.e(TAG, "新增任务失败MainService已回收弱引用失效");
return;
}
// 构建默认任务模型Java 7 显式初始化)
PositionTaskModel newTask = new PositionTaskModel();
newTask.setTaskId(PositionTaskModel.genTaskId()); // 生成唯一任务ID需在PositionTaskModel实现静态方法
newTask.setPositionId(posId); // 绑定当前位置ID
newTask.setTaskDescription(DEFAULT_TASK_DESC); // 默认任务描述
newTask.setIsEnable(true); // 默认启用任务
newTask.setDiscussDistance(DEFAULT_TASK_DISTANCE);// 默认任务距离50米
// 调用MainService接口新增任务数据写入服务由服务处理持久化+通知刷新)
mainService.addPositionTask(newTask);
hideSoftKeyboard(v);
LogUtils.d(TAG, "触发新增任务调用MainService接口位置ID=" + posId + "任务ID=" + newTask.getTaskId());
} }
}); });
} }
// ========================================================================= // =========================================================================
// 工具方法Java 7 风格无Lambda纯匿名内部类+迭代器 // PositionTaskListView 集成(分简单/编辑模式,差异化初始化+绑定
// ========================================================================= // =========================================================================
/** /**
* 更新距离显示(根据位置模型状态,显示不同文本+颜色 * 初始化+绑定简单模式任务列表视图(仅显示已启用任务,无编辑操作
*/ */
private void updateDistanceDisplay(TextView distanceView, PositionModel posModel) { private void initAndBindSimpleTaskView(PositionTaskListView taskView, final String posId, MainService mainService) {
if (distanceView == null || posModel == null) { if (taskView == null || TextUtils.isEmpty(posId) || mainService == null) {
LogUtils.w(TAG, "updateDistanceDisplay参数为空控件/位置模型"); LogUtils.w(TAG, "初始化简单模式任务视图失败参数无效posId=" + posId + "service=" + mainService + "");
return; return;
} }
// 场景1距离未启用 // 1. 初始化任务视图绑定MainService+当前位置ID假设视图已实现init方法
taskView.init(mainService, posId);
// 2. 设置为简单模式(仅展示,隐藏编辑按钮,需视图支持该状态设置)
taskView.setViewStatus(PositionTaskListView.VIEW_MODE_SIMPLE);
// 3. 同步任务数据从MainService拉取当前位置已启用任务
taskView.syncTasksFromMainService();
// 4. 任务更新回调(服务任务变化时重新同步)
taskView.setOnTaskUpdatedListener(new PositionTaskListView.OnTaskUpdatedListener() {
@Override
public void onTaskUpdated(String positionId, ArrayList<PositionTaskModel> updatedTasks) {
LogUtils.d(TAG, "简单模式任务更新位置ID=" + positionId + ",已启用任务数=" + updatedTasks.size());
}
});
LogUtils.d(TAG, "初始化简单模式任务视图完成位置ID=" + posId);
}
/**
* 初始化+绑定编辑模式任务列表视图(支持增删改查,关联新增任务按钮)
*/
private void initAndBindEditTaskView(final PositionTaskListView taskView, final String posId,
MainService mainService, Button btnAddTask) {
if (taskView == null || TextUtils.isEmpty(posId) || mainService == null || btnAddTask == null) {
LogUtils.w(TAG, "初始化编辑模式任务视图失败参数无效posId=" + posId + "btnAddTask=" + btnAddTask + "");
return;
}
// 1. 初始化任务视图绑定MainService+当前位置ID
taskView.init(mainService, posId);
// 2. 设置为编辑模式(显示编辑/删除按钮,支持修改)
taskView.setViewStatus(PositionTaskListView.VIEW_MODE_EDIT);
// 3. 同步任务数据从MainService拉取当前位置所有任务
taskView.syncTasksFromMainService();
// 4. 绑定“新增任务”按钮逻辑(点击创建默认任务,通过任务视图同步到服务)
btnAddTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 构建默认任务模型关联当前位置ID使用默认配置
PositionTaskModel newTask = new PositionTaskModel();
newTask.setTaskId(PositionTaskModel.genTaskId()); // 生成唯一任务ID需模型类实现
newTask.setPositionId(posId); // 绑定当前位置
newTask.setTaskDescription(DEFAULT_TASK_DESC); // 默认描述
newTask.setDiscussDistance(DEFAULT_TASK_DISTANCE); // 默认触发距离50米
newTask.setIsEnable(true); // 默认启用
newTask.setIsBingo(false); // 初始未触发
// 调用任务视图的新增方法假设视图已实现addNewTask内部同步MainService
taskView.addNewTask(newTask);
hideSoftKeyboard(v); // 隐藏软键盘,提升体验
LogUtils.d(TAG, "编辑模式新增任务位置ID=" + posId + "任务ID=" + newTask.getTaskId());
}
});
// 5. 任务更新回调通知外部任务变化如Activity需要联动
taskView.setOnTaskUpdatedListener(new PositionTaskListView.OnTaskUpdatedListener() {
@Override
public void onTaskUpdated(String positionId, ArrayList<PositionTaskModel> updatedTasks) {
LogUtils.d(TAG, "编辑模式任务更新位置ID=" + positionId + ",当前任务数=" + updatedTasks.size());
}
});
LogUtils.d(TAG, "初始化编辑模式任务视图完成位置ID=" + posId);
}
// =========================================================================
// 工具方法(距离显示/数据校验/控件管理Java 7 语法适配)
// =========================================================================
/**
* 更新距离显示(按状态区分文本和颜色,提升视觉区分度)
*/
private void updateDistanceDisplay(TextView distanceView, PositionModel posModel) {
if (distanceView == null || posModel == null) {
LogUtils.w(TAG, "更新距离显示失败:参数为空(控件/位置模型)");
return;
}
// 场景1距离未启用灰色文本
if (!posModel.isEnableRealPositionDistance()) { if (!posModel.isEnableRealPositionDistance()) {
distanceView.setText(DISTANCE_DISABLED); distanceView.setText(DISTANCE_DISABLED);
distanceView.setTextColor(mContext.getResources().getColor(R.color.gray)); distanceView.setTextColor(mContext.getResources().getColor(R.color.gray));
return; return;
} }
// 场景2距离计算失败用-1标记失败状态 // 场景2距离计算失败红色文本,用-1标记失败状态
double distance = posModel.getRealPositionDistance(); double distance = posModel.getRealPositionDistance();
if (distance < 0) { if (distance < 0) {
distanceView.setText(DISTANCE_ERROR); distanceView.setText(DISTANCE_ERROR);
@@ -340,7 +416,7 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
return; return;
} }
// 场景3正常显示距离按距离范围设置颜色,提升视觉区分度 // 场景3正常显示距离按距离范围设置颜色
distanceView.setText(String.format(DISTANCE_FORMAT, distance)); distanceView.setText(String.format(DISTANCE_FORMAT, distance));
if (distance <= 100) { if (distance <= 100) {
distanceView.setTextColor(mContext.getResources().getColor(R.color.green)); // 近距离≤100米 distanceView.setTextColor(mContext.getResources().getColor(R.color.green)); // 近距离≤100米
@@ -352,11 +428,11 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
} }
/** /**
* 根据索引获取位置模型(从位置缓存取数,容错处理) * 根据索引获取位置模型(容错处理,避免越界/空指针
*/ */
private PositionModel getPositionByIndex(int index) { private PositionModel getPositionByIndex(int index) {
if (mCachedPositionList == null || index < 0 || index >= mCachedPositionList.size()) { if (mCachedPositionList == null || index < 0 || index >= mCachedPositionList.size()) {
LogUtils.w(TAG, "getPositionByIndex:无效索引(" + index + ")或位置缓存为空"); LogUtils.w(TAG, "获取位置模型失败:无效索引(" + index + ")或缓存为空");
return null; return null;
} }
return mCachedPositionList.get(index); return mCachedPositionList.get(index);
@@ -367,18 +443,18 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
*/ */
private int getPositionIndexById(String positionId) { private int getPositionIndexById(String positionId) {
if (TextUtils.isEmpty(positionId) || mCachedPositionList == null || mCachedPositionList.isEmpty()) { if (TextUtils.isEmpty(positionId) || mCachedPositionList == null || mCachedPositionList.isEmpty()) {
LogUtils.w(TAG, "getPositionIndexById:参数无效(位置ID/缓存为空)"); LogUtils.w(TAG, "获取位置索引失败参数无效ID/缓存为空)");
return -1; return -1;
} }
// Java 7 增强for循环遍历替代Lambda适配Java 7语法) // Java 7 增强for循环遍历替代Lambda适配语法
for (int i = 0; i < mCachedPositionList.size(); i++) { for (int i = 0; i < mCachedPositionList.size(); i++) {
PositionModel pos = mCachedPositionList.get(i); PositionModel pos = mCachedPositionList.get(i);
if (positionId.equals(pos.getPositionId())) { if (positionId.equals(pos.getPositionId())) {
return i; // 找到匹配ID返回索引 return i;
} }
} }
LogUtils.w(TAG, "getPositionIndexById:未找到位置ID=" + positionId); LogUtils.w(TAG, "获取位置索引失败未找到ID=" + positionId);
return -1; return -1;
} }
@@ -386,57 +462,96 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
* 局部更新距离UI仅更新指定位置的距离避免全量刷新卡顿 * 局部更新距离UI仅更新指定位置的距离避免全量刷新卡顿
*/ */
public void updateSinglePositionDistance(String positionId) { public void updateSinglePositionDistance(String positionId) {
// 校验参数位置ID无效或控件未缓存直接返回 if (TextUtils.isEmpty(positionId) || mPosDistanceViewMap.isEmpty()) {
if (TextUtils.isEmpty(positionId) || !mPosDistanceViewMap.containsKey(positionId)) { LogUtils.w(TAG, "局部更新距离失败ID无效或无控件缓存ID=" + positionId + "");
LogUtils.w(TAG, "updateSinglePositionDistance位置ID无效或控件未缓存ID=" + positionId + ""); return;
}
// 1. 获取服务端最新位置数据(带重试,避免服务临时回收)
MainService mainService = getMainServiceWithRetry(2);
if (mainService == null) {
LogUtils.e(TAG, "局部更新距离失败无法获取MainService");
return; return;
} }
// 从MainService获取最新位置模型确保距离值是服务端最新
PositionModel latestPos = null; PositionModel latestPos = null;
MainService mainService = mMainServiceRef.get(); try {
if (mainService != null) {
ArrayList<PositionModel> servicePosList = mainService.getPositionList(); ArrayList<PositionModel> servicePosList = mainService.getPositionList();
if (servicePosList != null && !servicePosList.isEmpty()) { if (servicePosList != null && !servicePosList.isEmpty()) {
// Java 7 迭代器遍历服务端位置列表,找到目标位置 // Java 7 迭代器遍历避免ConcurrentModificationException
Iterator<PositionModel> posIter = servicePosList.iterator(); Iterator<PositionModel> iter = servicePosList.iterator();
while (posIter.hasNext()) { while (iter.hasNext()) {
PositionModel pos = posIter.next(); PositionModel pos = iter.next();
if (positionId.equals(pos.getPositionId())) { if (positionId.equals(pos.getPositionId())) {
latestPos = pos; latestPos = pos;
break; break;
} }
} }
} }
} catch (Exception e) {
LogUtils.d(TAG, "获取最新位置数据失败ID=" + positionId + "" + e);
return;
} }
// 用服务端最新距离更新UI直接操作缓存的距离控件无需刷新整个项 if (latestPos == null) {
if (latestPos != null) { LogUtils.w(TAG, "局部更新距离失败未找到位置ID=" + positionId);
TextView distanceView = mPosDistanceViewMap.get(positionId); return;
updateDistanceDisplay(distanceView, latestPos); }
LogUtils.d(TAG, "局部更新距离完成位置ID=" + positionId + ",最新距离=" + latestPos.getRealPositionDistance() + "");
// 2. 更新距离控件(确保主线程操作,避免跨线程异常)
final TextView distanceView = mPosDistanceViewMap.get(positionId);
if (distanceView != null && distanceView.isAttachedToWindow()) {
final PositionModel finalLatestPos = latestPos;
distanceView.post(new Runnable() {
@Override
public void run() {
updateDistanceDisplay(distanceView, finalLatestPos);
}
});
LogUtils.d(TAG, "局部更新距离完成位置ID=" + positionId + ",距离=" + latestPos.getRealPositionDistance() + "");
} else { } else {
LogUtils.w(TAG, "局部更新距离失败未在MainService找到位置ID=" + positionId); mPosDistanceViewMap.remove(positionId); // 移除无效控件缓存
LogUtils.w(TAG, "局部更新距离失败:控件已回收/脱离视图树ID=" + positionId + "");
} }
} }
/** /**
* 全量更新位置数据(从MainService同步最新位置列表刷新UI * 全量更新位置数据(从服务同步最新数据,过滤无效/重复项
*/ */
public void updateAllPositionData(ArrayList<PositionModel> newPosList) { public void updateAllPositionData(ArrayList<PositionModel> newPosList) {
if (newPosList == null) { if (newPosList == null) {
LogUtils.w(TAG, "updateAllPositionData新位置列表为空跳过更新"); LogUtils.w(TAG, "全量更新位置数据失败:新列表为空");
return; return;
} }
// 同步服务端最新位置数据到本地缓存 // 1. 过滤无效位置校验核心字段ID/经纬度合法)
ArrayList<PositionModel> validPosList = new ArrayList<PositionModel>();
for (PositionModel pos : newPosList) {
if (TextUtils.isEmpty(pos.getPositionId())
|| pos.getLongitude() < -180 || pos.getLongitude() > 180
|| pos.getLatitude() < -90 || pos.getLatitude() > 90) {
LogUtils.w(TAG, "过滤无效位置ID=" + pos.getPositionId() + "(经纬度/ID非法");
continue;
}
validPosList.add(pos);
}
// 2. 去重按位置ID去重保留服务端最新数据
ConcurrentHashMap<String, PositionModel> uniquePosMap = new ConcurrentHashMap<String, PositionModel>();
for (PositionModel pos : validPosList) {
uniquePosMap.put(pos.getPositionId(), pos); // 相同ID覆盖保留最新
}
ArrayList<PositionModel> uniquePosList = new ArrayList<PositionModel>(uniquePosMap.values());
// 3. 同步到本地缓存+刷新UI
this.mCachedPositionList.clear(); this.mCachedPositionList.clear();
this.mCachedPositionList.addAll(newPosList); this.mCachedPositionList.addAll(uniquePosList);
// 清空旧距离控件缓存(避免引用失效控件 // 清空旧控件缓存(避免引用失效数据
mPosDistanceViewMap.clear(); mPosDistanceViewMap.clear();
// 通知RecyclerView全量刷新UI mSimpleTaskViewMap.clear();
mEditTaskViewMap.clear();
notifyDataSetChanged(); notifyDataSetChanged();
LogUtils.d(TAG, "全量更新位置数据完成:当前位置数量=" + mCachedPositionList.size() + "数据来源MainService"); LogUtils.d(TAG, "全量更新位置数据完成:数量=" + newPosList.size() + ",过滤后=" + uniquePosList.size());
} }
/** /**
@@ -444,29 +559,83 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
*/ */
private void hideSoftKeyboard(View view) { private void hideSoftKeyboard(View view) {
if (mContext == null || view == null) { if (mContext == null || view == null) {
LogUtils.w(TAG, "hideSoftKeyboard:参数为空(上下文/视图),无法隐藏键盘"); LogUtils.w(TAG, "隐藏软键盘失败:参数为空(上下文/视图)");
return; return;
} }
// Java 7 显式获取输入法服务避免Lambda
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) { if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏软键盘 imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏
} }
} }
/**
* 带重试的服务获取解决弱引用临时回收问题最多重试2次
*/
private MainService getMainServiceWithRetry(int retryCount) {
MainService mainService = mMainServiceRef.get();
if (mainService != null) {
return mainService;
}
// 重试逻辑每次间隔100ms避免频繁重试
for (int i = 0; i < retryCount; i++) {
try {
Thread.sleep(100);
mainService = mMainServiceRef.get();
if (mainService != null) {
LogUtils.d(TAG, "重试获取MainService成功" + (i+1) + "次)");
return mainService;
}
} catch (InterruptedException e) {
LogUtils.d(TAG, "重试获取服务时线程被中断" + e);
Thread.currentThread().interrupt(); // 恢复中断状态
break;
}
}
LogUtils.e(TAG, "重试" + retryCount + "次后仍未获取到MainService");
return null;
}
// ========================================================================= // =========================================================================
// 实现 MainService.TaskUpdateListener 接口(服务任务变化时回调) // 实现 MainService.TaskUpdateListener 接口(服务任务变化时回调)
// ========================================================================= // =========================================================================
@Override @Override
public void onTaskUpdated() { public void onTaskUpdated() {
LogUtils.d(TAG, "收到MainService任务更新通知(任务新增/删除/状态变化刷新UI"); LogUtils.d(TAG, "收到MainService任务更新通知,同步所有任务列表视图");
// 任务数据变化时全量刷新Adapter确保任务数量等显示同步
notifyDataSetChanged(); // 1. 同步简单模式任务视图(仅显示已启用任务)
if (!mSimpleTaskViewMap.isEmpty()) {
Iterator<ConcurrentHashMap.Entry<String, PositionTaskListView>> iter = mSimpleTaskViewMap.entrySet().iterator();
while (iter.hasNext()) {
ConcurrentHashMap.Entry<String, PositionTaskListView> entry = iter.next();
PositionTaskListView taskView = entry.getValue();
if (taskView != null && taskView.isAttachedToWindow()) {
taskView.syncTasksFromMainService(); // 从服务同步最新任务
} else {
iter.remove(); // 移除无效视图缓存
}
}
}
// 2. 同步编辑模式任务视图(支持编辑的全量任务)
if (!mEditTaskViewMap.isEmpty()) {
Iterator<ConcurrentHashMap.Entry<String, PositionTaskListView>> iter = mEditTaskViewMap.entrySet().iterator();
while (iter.hasNext()) {
ConcurrentHashMap.Entry<String, PositionTaskListView> entry = iter.next();
PositionTaskListView taskView = entry.getValue();
if (taskView != null && taskView.isAttachedToWindow()) {
taskView.syncTasksFromMainService(); // 从服务同步最新任务
} else {
iter.remove(); // 移除无效视图缓存
}
}
}
} }
// ========================================================================= // =========================================================================
// 回调设置方法(供LocationActivity调用,绑定交互逻辑) // 回调设置方法供Activity绑定交互逻辑
// ========================================================================= // =========================================================================
public void setOnDeleteClickListener(OnDeleteClickListener listener) { public void setOnDeleteClickListener(OnDeleteClickListener listener) {
this.mOnDeleteListener = listener; this.mOnDeleteListener = listener;
@@ -477,69 +646,96 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
} }
// ========================================================================= // =========================================================================
// 资源释放Activity销毁时调用避免内存泄漏 // 资源释放Activity销毁时调用彻底释放引用,避免内存泄漏)
// ========================================================================= // =========================================================================
public void release() { public void release() {
// 1. 反注册MainService任务监听解除服务绑定,避免内存泄漏 // 1. 反注册MainService任务监听解除服务绑定
MainService mainService = mMainServiceRef.get(); MainService mainService = mMainServiceRef.get();
if (mainService != null) { if (mainService != null) {
mainService.unregisterTaskUpdateListener(this); mainService.unregisterTaskUpdateListener(this);
LogUtils.d(TAG, "已反注册MainService任务监听,避免内存泄漏"); LogUtils.d(TAG, "已反注册MainService任务监听");
} }
// 2. 清空本地缓存(解除控件/数据引用帮助GC回收 // 2. 释放简单模式任务视图资源(清空数据+解绑监听替代onDestroy()
if (!mSimpleTaskViewMap.isEmpty()) {
Iterator<ConcurrentHashMap.Entry<String, PositionTaskListView>> iter = mSimpleTaskViewMap.entrySet().iterator();
while (iter.hasNext()) {
PositionTaskListView taskView = iter.next().getValue();
if (taskView != null) {
taskView.clearData();
taskView.setOnTaskUpdatedListener(null);
}
iter.remove();
}
}
// 3. 释放编辑模式任务视图资源(清空数据+解绑监听替代onDestroy()
if (!mEditTaskViewMap.isEmpty()) {
Iterator<ConcurrentHashMap.Entry<String, PositionTaskListView>> iter = mEditTaskViewMap.entrySet().iterator();
while (iter.hasNext()) {
PositionTaskListView taskView = iter.next().getValue();
if (taskView != null) {
taskView.clearData();
taskView.setOnTaskUpdatedListener(null);
}
iter.remove();
}
}
// 4. 清空其他缓存+置空引用
mPosDistanceViewMap.clear(); mPosDistanceViewMap.clear();
if (mCachedPositionList != null) { if (mCachedPositionList != null) {
mCachedPositionList.clear(); mCachedPositionList.clear();
} }
// 3. 置空回调实例避免持有Activity引用导致内存泄漏
mOnDeleteListener = null; mOnDeleteListener = null;
mOnSavePosListener = null; mOnSavePosListener = null;
LogUtils.d(TAG, "Adapter资源已完全释放缓存清空+监听反注册"); LogUtils.d(TAG, "Adapter资源已完全释放任务视图资源释放+缓存清空+引用置空");
} }
// ========================================================================= // =========================================================================
// 静态内部类:视图HolderJava 7 静态内部类,不持有外部引用,避免内存泄漏) // 静态内部类:ViewHolder与布局严格对应,避免外部引用导致内存泄漏)
// ========================================================================= // =========================================================================
/** /**
* 简单视图Holder仅显示数据,对应布局:item_position_simple.xml * 简单模式ViewHolder对应 item_position_simple.xml,含简单模式任务列表视图
*/ */
public static class SimpleViewHolder extends RecyclerView.ViewHolder { public static class SimpleViewHolder extends RecyclerView.ViewHolder {
TextView tvSimpleLon; // 经度显示控件 TextView tvSimpleLon; // 经度显示
TextView tvSimpleLat; // 纬度显示控件 TextView tvSimpleLat; // 纬度显示
TextView tvSimpleMemo; // 备注显示控件 TextView tvSimpleMemo; // 备注显示
TextView tvSimpleDistance;// 实时距离显示控件 TextView tvSimpleDistance; // 距离显示
PositionTaskListView ptlvSimpleTasks; // 简单模式任务列表视图
public SimpleViewHolder(View itemView) { public SimpleViewHolder(View itemView) {
super(itemView); super(itemView);
// 绑定布局控件与XML中ID严格对应,避免运行时空指针) // 绑定布局控件与XML中ID严格一致,避免运行时空指针)
tvSimpleLon = (TextView) itemView.findViewById(R.id.tv_simple_longitude); tvSimpleLon = (TextView) itemView.findViewById(R.id.tv_simple_longitude);
tvSimpleLat = (TextView) itemView.findViewById(R.id.tv_simple_latitude); tvSimpleLat = (TextView) itemView.findViewById(R.id.tv_simple_latitude);
tvSimpleMemo = (TextView) itemView.findViewById(R.id.tv_simple_memo); tvSimpleMemo = (TextView) itemView.findViewById(R.id.tv_simple_memo);
tvSimpleDistance = (TextView) itemView.findViewById(R.id.tv_simple_distance); tvSimpleDistance = (TextView) itemView.findViewById(R.id.tv_simple_distance);
ptlvSimpleTasks = (PositionTaskListView) itemView.findViewById(R.id.ptlv_simple_tasks);
} }
} }
/** /**
* 编辑视图Holder含编辑控件+功能按钮,对应布局:item_position_edit.xml * 编辑模式ViewHolder对应 item_position_edit.xml,含编辑模式任务列表视图
*/ */
public static class EditViewHolder extends RecyclerView.ViewHolder { public static class EditViewHolder extends RecyclerView.ViewHolder {
TextView tvEditLon; // 经度显示控件(不可编辑) TextView tvEditLon; // 经度显示(不可编辑)
TextView tvEditLat; // 纬度显示控件(不可编辑) TextView tvEditLat; // 纬度显示(不可编辑)
EditText etEditMemo; // 备注编辑控件 EditText etEditMemo; // 备注编辑
TextView tvEditDistance; // 实时距离显示控件 TextView tvEditDistance; // 距离显示
RadioGroup rgDistanceSwitch; // 距离启用/禁用开关 RadioGroup rgDistanceSwitch; // 距离启用/禁用开关
Button btnCancel; // 取消编辑按钮 Button btnCancel; // 取消编辑按钮
Button btnDelete; // 删除位置按钮 Button btnDelete; // 删除位置按钮
Button btnSave; // 保存位置按钮 Button btnSave; // 保存位置按钮
Button btnAddTask; // 新增任务按钮 Button btnAddTask; // 新增任务按钮
TextView tvTaskCount; // 任务数量显示控件 TextView tvTaskCount; // 任务数量显示(兼容旧布局,可隐藏)
PositionTaskListView ptlvEditTasks; // 编辑模式任务列表视图
public EditViewHolder(View itemView) { public EditViewHolder(View itemView) {
super(itemView); super(itemView);
// 绑定布局控件与XML中ID严格对应,避免运行时空指针) // 绑定布局控件与XML中ID严格一致,避免运行时空指针)
tvEditLon = (TextView) itemView.findViewById(R.id.tv_edit_longitude); tvEditLon = (TextView) itemView.findViewById(R.id.tv_edit_longitude);
tvEditLat = (TextView) itemView.findViewById(R.id.tv_edit_latitude); tvEditLat = (TextView) itemView.findViewById(R.id.tv_edit_latitude);
etEditMemo = (EditText) itemView.findViewById(R.id.et_edit_memo); etEditMemo = (EditText) itemView.findViewById(R.id.et_edit_memo);
@@ -550,7 +746,94 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
btnSave = (Button) itemView.findViewById(R.id.btn_edit_save); btnSave = (Button) itemView.findViewById(R.id.btn_edit_save);
btnAddTask = (Button) itemView.findViewById(R.id.btn_add_task); btnAddTask = (Button) itemView.findViewById(R.id.btn_add_task);
tvTaskCount = (TextView) itemView.findViewById(R.id.tv_task_count); tvTaskCount = (TextView) itemView.findViewById(R.id.tv_task_count);
ptlvEditTasks = (PositionTaskListView) itemView.findViewById(R.id.ptlv_edit_tasks);
} }
} }
// =========================================================================
// 补充PositionTaskListView 必要方法适配(确保视图类已实现以下基础方法)
// (若视图类未实现,需在 PositionTaskListView 中添加对应逻辑)
// =========================================================================
public static class PositionTaskListViewRequiredMethods {
/**
* 1. init 方法:初始化任务视图(绑定服务+位置ID
* 需在 PositionTaskListView 中添加:
* public void init(MainService mainService, String positionId) {
* this.mMainServiceRef = new WeakReference<MainService>(mainService); // 弱引用服务
* this.mPositionId = positionId; // 绑定当前位置ID
* }
*/
/**
* 2. setViewStatus 方法:设置视图模式(简单/编辑)
* 需在 PositionTaskListView 中添加:
* public static final int VIEW_MODE_SIMPLE = 0; // 仅显示
* public static final int VIEW_MODE_EDIT = 1; // 可编辑
* private int mViewMode;
* public void setViewStatus(int viewMode) {
* this.mViewMode = viewMode;
* // 根据模式控制编辑/删除按钮显示(如简单模式隐藏,编辑模式显示)
* updateButtonVisibility();
* }
*/
/**
* 3. syncTasksFromMainService 方法:从服务同步任务数据
* 需在 PositionTaskListView 中添加:
* public void syncTasksFromMainService() {
* MainService mainService = mMainServiceRef.get();
* if (mainService == null || TextUtils.isEmpty(mPositionId)) return;
* // 根据视图模式拉取任务(简单模式:已启用;编辑模式:所有)
* ArrayList<PositionTaskModel> tasks = (mViewMode == VIEW_MODE_SIMPLE)
* ? mainService.getEnabledTasksByPositionId(mPositionId)
* : mainService.getTasksByPositionId(mPositionId);
* // 更新列表显示如设置Adapter数据
* setTaskList(tasks);
* }
*/
/**
* 4. addNewTask 方法:新增任务(同步服务+刷新列表)
* 需在 PositionTaskListView 中添加:
* public void addNewTask(PositionTaskModel newTask) {
* if (newTask == null || TextUtils.isEmpty(newTask.getPositionId())) return;
* MainService mainService = mMainServiceRef.get();
* if (mainService != null) {
* mainService.addTask(newTask);
* syncTasksFromMainService(); // 新增后同步刷新
* Toast.makeText(getContext(), "任务创建成功", Toast.LENGTH_SHORT).show();
* } else {
* Toast.makeText(getContext(), "新增失败,请重试", Toast.LENGTH_SHORT).show();
* }
* }
*/
/**
* 5. clearData 方法:清空任务数据(释放资源)
* 需在 PositionTaskListView 中添加:
* public void clearData() {
* if (mTaskList != null) mTaskList.clear(); // 清空任务列表数据
* if (mTaskAdapter != null) mTaskAdapter.notifyDataSetChanged(); // 刷新列表
* }
*/
/**
* 6. setOnTaskUpdatedListener 方法:设置任务更新回调
* 需在 PositionTaskListView 中添加:
* public interface OnTaskUpdatedListener {
* void onTaskUpdated(String positionId, ArrayList<PositionTaskModel> updatedTasks);
* }
* private OnTaskUpdatedListener mTaskUpdateListener;
* public void setOnTaskUpdatedListener(OnTaskUpdatedListener listener) {
* this.mTaskUpdateListener = listener;
* }
* // 任务变化时调用(如同步后/编辑后)
* private void notifyTaskUpdated(ArrayList<PositionTaskModel> updatedTasks) {
* if (mTaskUpdateListener != null) {
* mTaskUpdateListener.onTaskUpdated(mPositionId, updatedTasks);
* }
* }
*/
}
} }

View File

@@ -69,7 +69,7 @@ public class MainService extends Service {
// 数据存储集合Java 7 基础集合避免Stream/forEach等Java 8+特性) // 数据存储集合Java 7 基础集合避免Stream/forEach等Java 8+特性)
private final ArrayList<PositionModel> mPositionList = new ArrayList<PositionModel>(); // 位置数据列表 private final ArrayList<PositionModel> mPositionList = new ArrayList<PositionModel>(); // 位置数据列表
private final ArrayList<PositionTaskModel> mTaskList = new ArrayList<PositionTaskModel>();// 任务数据列表 private final ArrayList<PositionTaskModel> mAllTasks = new ArrayList<PositionTaskModel>();// 任务数据列表
private PositionModel mCurrentGpsPosition; // 当前GPS定位数据 private PositionModel mCurrentGpsPosition; // 当前GPS定位数据
// 服务相关变量Java 7 显式声明,保持原逻辑) // 服务相关变量Java 7 显式声明,保持原逻辑)
@@ -91,7 +91,7 @@ public class MainService extends Service {
* 新增任务Adapter调用通过MainService统一管理任务保证数据一致性 * 新增任务Adapter调用通过MainService统一管理任务保证数据一致性
* @param newTask 待新增的任务模型 * @param newTask 待新增的任务模型
*/ */
public void addPositionTask(PositionTaskModel newTask) { public void addTask(PositionTaskModel newTask) {
// 参数校验Java 7 基础判断无Optional等Java 8+特性) // 参数校验Java 7 基础判断无Optional等Java 8+特性)
if (newTask == null || TextUtils.isEmpty(newTask.getPositionId())) { if (newTask == null || TextUtils.isEmpty(newTask.getPositionId())) {
LogUtils.w(TAG, "addPositionTask任务为空或未绑定位置ID新增失败"); LogUtils.w(TAG, "addPositionTask任务为空或未绑定位置ID新增失败");
@@ -100,7 +100,7 @@ public class MainService extends Service {
// 任务去重Java 7 迭代器遍历避免增强for循环删除/新增导致的并发异常) // 任务去重Java 7 迭代器遍历避免增强for循环删除/新增导致的并发异常)
boolean isDuplicate = false; boolean isDuplicate = false;
Iterator<PositionTaskModel> taskIter = mTaskList.iterator(); Iterator<PositionTaskModel> taskIter = mAllTasks.iterator();
while (taskIter.hasNext()) { while (taskIter.hasNext()) {
PositionTaskModel task = taskIter.next(); PositionTaskModel task = taskIter.next();
if (newTask.getTaskId().equals(task.getTaskId())) { if (newTask.getTaskId().equals(task.getTaskId())) {
@@ -114,8 +114,8 @@ public class MainService extends Service {
} }
// 新增任务+持久化+通知刷新全Java 7 语法) // 新增任务+持久化+通知刷新全Java 7 语法)
mTaskList.add(newTask); mAllTasks.add(newTask);
saveTaskList(); saveAllTasks();
notifyTaskUpdated(); // 通知所有监听者如Adapter任务已更新 notifyTaskUpdated(); // 通知所有监听者如Adapter任务已更新
LogUtils.d(TAG, "addPositionTask成功位置ID=" + newTask.getPositionId() + "任务ID=" + newTask.getTaskId() + ""); LogUtils.d(TAG, "addPositionTask成功位置ID=" + newTask.getPositionId() + "任务ID=" + newTask.getTaskId() + "");
} }
@@ -127,12 +127,12 @@ public class MainService extends Service {
*/ */
public ArrayList<PositionTaskModel> getTasksByPositionId(String positionId) { public ArrayList<PositionTaskModel> getTasksByPositionId(String positionId) {
ArrayList<PositionTaskModel> posTasks = new ArrayList<PositionTaskModel>(); ArrayList<PositionTaskModel> posTasks = new ArrayList<PositionTaskModel>();
if (TextUtils.isEmpty(positionId) || mTaskList.isEmpty()) { if (TextUtils.isEmpty(positionId) || mAllTasks.isEmpty()) {
return posTasks; return posTasks;
} }
// 筛选任务Java 7 迭代器遍历,安全筛选) // 筛选任务Java 7 迭代器遍历,安全筛选)
Iterator<PositionTaskModel> taskIter = mTaskList.iterator(); Iterator<PositionTaskModel> taskIter = mAllTasks.iterator();
while (taskIter.hasNext()) { while (taskIter.hasNext()) {
PositionTaskModel task = taskIter.next(); PositionTaskModel task = taskIter.next();
if (positionId.equals(task.getPositionId())) { if (positionId.equals(task.getPositionId())) {
@@ -147,26 +147,51 @@ public class MainService extends Service {
* @return 所有任务的拷贝列表 * @return 所有任务的拷贝列表
*/ */
public ArrayList<PositionTaskModel> getAllTasks() { public ArrayList<PositionTaskModel> getAllTasks() {
return new ArrayList<PositionTaskModel>(mTaskList); // Java 7 集合拷贝方式 return new ArrayList<PositionTaskModel>(mAllTasks); // Java 7 集合拷贝方式
}
public void updateTask(PositionTaskModel updatedTask) {
if (updatedTask == null || updatedTask.getTaskId() == null) return;
for (int i = 0; i < mAllTasks.size(); i++) {
PositionTaskModel task = mAllTasks.get(i);
if (updatedTask.getTaskId().equals(task.getTaskId())) {
mAllTasks.set(i, updatedTask); // 替换为更新后的任务
break;
}
}
saveAllTasks(); // 持久化更新后的数据
} }
// 4. 仅更新任务启用状态(优化性能,避免全量字段更新)
public void updateTaskStatus(PositionTaskModel task) {
if (task == null || task.getTaskId() == null) return;
for (PositionTaskModel item : mAllTasks) {
if (task.getTaskId().equals(item.getTaskId())) {
item.setIsEnable(task.isEnable()); // 只更新启用状态字段
break;
}
}
saveAllTasks(); // 持久化状态变更
}
/** /**
* 删除任务Adapter调用通过迭代器安全删除避免并发异常 * 删除任务Adapter调用通过迭代器安全删除避免并发异常
* @param taskId 待删除任务的ID * @param taskId 待删除任务的ID
*/ */
public void deletePositionTask(String taskId) { public void deleteTask(String taskId) {
if (TextUtils.isEmpty(taskId) || mTaskList.isEmpty()) { if (TextUtils.isEmpty(taskId) || mAllTasks.isEmpty()) {
LogUtils.w(TAG, "deletePositionTask任务ID为空或列表为空删除失败"); LogUtils.w(TAG, "deletePositionTask任务ID为空或列表为空删除失败");
return; return;
} }
// 迭代器删除Java 7 唯一安全删除集合元素的方式) // 迭代器删除Java 7 唯一安全删除集合元素的方式)
Iterator<PositionTaskModel> taskIter = mTaskList.iterator(); Iterator<PositionTaskModel> taskIter = mAllTasks.iterator();
while (taskIter.hasNext()) { while (taskIter.hasNext()) {
PositionTaskModel task = taskIter.next(); PositionTaskModel task = taskIter.next();
if (taskId.equals(task.getTaskId())) { if (taskId.equals(task.getTaskId())) {
taskIter.remove(); // 迭代器安全删除无ConcurrentModificationException taskIter.remove(); // 迭代器安全删除无ConcurrentModificationException
saveTaskList(); saveAllTasks();
notifyTaskUpdated(); notifyTaskUpdated();
LogUtils.d(TAG, "deletePositionTask成功任务ID=" + taskId + ""); LogUtils.d(TAG, "deletePositionTask成功任务ID=" + taskId + "");
break; break;
@@ -312,7 +337,7 @@ public class MainService extends Service {
// 加载本地数据Java 7 静态方法调用,无方法引用) // 加载本地数据Java 7 静态方法调用,无方法引用)
PositionModel.loadBeanList(MainService.this, mPositionList, PositionModel.class); PositionModel.loadBeanList(MainService.this, mPositionList, PositionModel.class);
PositionTaskModel.loadBeanList(MainService.this, mTaskList, PositionTaskModel.class); PositionTaskModel.loadBeanList(MainService.this, mAllTasks, PositionTaskModel.class);
// 提示与日志Java 7 基础调用) // 提示与日志Java 7 基础调用)
ToastUtils.show(initialStatus); ToastUtils.show(initialStatus);
@@ -425,9 +450,9 @@ public class MainService extends Service {
return; return;
} }
// 全量替换+持久化+通知Java 7 基础集合操作) // 全量替换+持久化+通知Java 7 基础集合操作)
mTaskList.clear(); mAllTasks.clear();
mTaskList.addAll(newTaskList); mAllTasks.addAll(newTaskList);
saveTaskList(); saveAllTasks();
notifyTaskUpdated(); notifyTaskUpdated();
} }
@@ -465,9 +490,9 @@ public class MainService extends Service {
/** /**
* 持久化任务数据Java 7 静态方法调用,保持原逻辑) * 持久化任务数据Java 7 静态方法调用,保持原逻辑)
*/ */
void saveTaskList() { void saveAllTasks() {
LogUtils.d(TAG, String.format("saveTaskList : size=%d", mTaskList.size())); LogUtils.d(TAG, String.format("saveTaskList : size=%d", mAllTasks.size()));
PositionTaskModel.saveBeanList(MainService.this, mTaskList, PositionTaskModel.class); PositionTaskModel.saveBeanList(MainService.this, mAllTasks, PositionTaskModel.class);
} }
/** /**
@@ -475,7 +500,7 @@ public class MainService extends Service {
*/ */
public void clearAllData() { public void clearAllData() {
mPositionList.clear(); mPositionList.clear();
mTaskList.clear(); mAllTasks.clear();
mCurrentGpsPosition = null; mCurrentGpsPosition = null;
LogUtils.d(TAG, "clearAllData已清空所有数据"); LogUtils.d(TAG, "clearAllData已清空所有数据");
} }
@@ -596,14 +621,14 @@ public class MainService extends Service {
* 校验所有任务触发条件(距离达标则触发任务通知) * 校验所有任务触发条件(距离达标则触发任务通知)
*/ */
private void checkAllTaskTriggerCondition() { private void checkAllTaskTriggerCondition() {
if (mCurrentGpsPosition == null || mPositionList.isEmpty() || mTaskList.isEmpty()) { if (mCurrentGpsPosition == null || mPositionList.isEmpty() || mAllTasks.isEmpty()) {
LogUtils.d(TAG, "checkAllTaskTriggerCondition跳过校验GPS/位置/任务为空)"); LogUtils.d(TAG, "checkAllTaskTriggerCondition跳过校验GPS/位置/任务为空)");
return; return;
} }
LogUtils.d(TAG, "checkAllTaskTriggerCondition开始校验任务总数=" + mTaskList.size() + ""); LogUtils.d(TAG, "checkAllTaskTriggerCondition开始校验任务总数=" + mAllTasks.size() + "");
// 迭代器遍历任务Java 7 安全遍历,避免并发修改异常) // 迭代器遍历任务Java 7 安全遍历,避免并发修改异常)
Iterator<PositionTaskModel> taskIter = mTaskList.iterator(); Iterator<PositionTaskModel> taskIter = mAllTasks.iterator();
while (taskIter.hasNext()) { while (taskIter.hasNext()) {
PositionTaskModel task = taskIter.next(); PositionTaskModel task = taskIter.next();
// 仅校验“已启用”且“绑定有效位置”的任务 // 仅校验“已启用”且“绑定有效位置”的任务
@@ -652,7 +677,7 @@ public class MainService extends Service {
} }
} }
} }
saveTaskList(); // 持久化更新后的任务状态 saveAllTasks(); // 持久化更新后的任务状态
} }
/** /**
@@ -661,7 +686,7 @@ public class MainService extends Service {
* @param bindPos 任务绑定的位置 * @param bindPos 任务绑定的位置
* @param currentDistance 当前距离 * @param currentDistance 当前距离
*/ */
private void sendTaskTriggerNotification(PositionTaskModel task, PositionModel bindPos, double currentDistance) { private void sendTaskTriggerNotification(final PositionTaskModel task, PositionModel bindPos, double currentDistance) {
if (!_mIsServiceRunning) { if (!_mIsServiceRunning) {
return; return;
} }
@@ -682,11 +707,13 @@ public class MainService extends Service {
// 显示Toast主线程安全调用Java 7 匿名内部类) // 显示Toast主线程安全调用Java 7 匿名内部类)
if (Looper.myLooper() == Looper.getMainLooper()) { if (Looper.myLooper() == Looper.getMainLooper()) {
ToastUtils.show(triggerContent); ToastUtils.show(triggerContent);
NotificationUtil.show(MainService.this, task.getTaskId(), task.getPositionId(), task.getTaskDescription());
} else { } else {
new Handler(Looper.getMainLooper()).post(new Runnable() { new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override @Override
public void run() { public void run() {
ToastUtils.show(triggerContent); ToastUtils.show(triggerContent);
NotificationUtil.show(MainService.this, task.getTaskId(), task.getPositionId(), task.getTaskDescription());
} }
}); });
} }

View File

@@ -3,7 +3,7 @@ package cc.winboll.studio.positions.utils;
/** /**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/09/30 16:09 * @Date 2025/09/30 16:09
* @Describe NotificationUtils * @Describe NotificationUtils适配API 30修复系统默认铃声获取任务通知循环响铃
*/ */
import android.app.Notification; import android.app.Notification;
import android.app.NotificationChannel; import android.app.NotificationChannel;
@@ -11,175 +11,183 @@ import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.media.RingtoneManager; // 导入RingtoneManager关键用于获取系统默认铃声
import android.net.Uri; // 导入Uri存储铃声路径
import android.os.Build; import android.os.Build;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
import cc.winboll.studio.positions.R; import cc.winboll.studio.positions.R;
import cc.winboll.studio.positions.activities.LocationActivity; // 引入你的前台服务类 import cc.winboll.studio.positions.activities.LocationActivity;
/** /**
* 通知栏工具类:专注于任务相关通知的显示与点击跳转 + 前台服务通知管理 * 通知栏工具类:
* 核心功能: * 1. 任务通知铃声循环播放适配API 30修复系统默认铃声获取方式
* 1. 显示任务描述通知点击后携带positionId/taskId跳转到LocationActivity * 2. 前台服务通知低打扰无声无震动符合API 30规范
* 2. 创建前台服务通知用于DistanceRefreshService保活符合系统前台服务规范
*/ */
public class NotificationUtil { public class NotificationUtil {
public static final String TAG = "NotificationUtils"; public static final String TAG = "NotificationUtils";
// 1. 任务通知相关常量(原有 // 任务通知常量(独立渠道,确保循环铃声配置不冲突
private static final String TASK_NOTIFICATION_CHANNEL_ID = "task_notification_channel_01"; private static final String TASK_NOTIFICATION_CHANNEL_ID = "task_notification_channel_01";
private static final String TASK_NOTIFICATION_CHANNEL_NAME = "任务通知"; private static final String TASK_NOTIFICATION_CHANNEL_NAME = "任务通知(循环铃声)";
// 2. 前台服务通知新增常量(独立渠道,避免与普通任务通知混淆 // 前台服务通知常量(独立渠道,低打扰
private static final String FOREGROUND_SERVICE_CHANNEL_ID = "foreground_location_service_channel_02"; private static final String FOREGROUND_SERVICE_CHANNEL_ID = "foreground_location_service_channel_02";
private static final String FOREGROUND_SERVICE_CHANNEL_NAME = "位置服务"; private static final String FOREGROUND_SERVICE_CHANNEL_NAME = "位置服务";
public static final int FOREGROUND_SERVICE_NOTIFICATION_ID = 10086; // 固定ID前台服务通知无需动态生成) public static final int FOREGROUND_SERVICE_NOTIFICATION_ID = 10086; // 固定前台服务通知ID
// ---------------------- 原有功能:任务通知(不变 ---------------------- // ---------------------- 核心:任务通知(循环响铃+修复系统默认铃声 ----------------------
private static int getNotificationId(String taskId) { private static int getNotificationId(String taskId) {
return taskId.hashCode() & 0xFFFFFF; return taskId.hashCode() & 0xFFFFFF; // 确保通知ID唯一且非负
} }
public static void show(Context context, String taskId, String positionId, String taskDescription) { public static void show(Context context, String taskId, String positionId, String taskDescription) {
if (context == null || taskId == null || positionId == null) { if (context == null || taskId == null || positionId == null) {
return; return;
} }
NotificationManager notificationManager = NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager == null) { if (notificationManager == null) {
return; return;
} }
createNotificationChannel(notificationManager); // 1. 初始化通知渠道(配置循环铃声参数,使用修复后的铃声获取方式)
createNotificationChannel(notificationManager);
Intent jumpIntent = new Intent(context, LocationActivity.class); // 2. 点击跳转Intent携带任务/位置参数适配API 30页面栈
jumpIntent.putExtra("EXTRA_POSITION_ID", positionId); Intent jumpIntent = new Intent(context, LocationActivity.class);
jumpIntent.putExtra("EXTRA_TASK_ID", taskId); jumpIntent.putExtra("EXTRA_POSITION_ID", positionId);
jumpIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); jumpIntent.putExtra("EXTRA_TASK_ID", taskId);
jumpIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity( // 3. PendingIntentAPI 30强制加IMMUTABLE避免安全异常
context, PendingIntent pendingIntent = PendingIntent.getActivity(
getNotificationId(taskId), context,
jumpIntent, getNotificationId(taskId),
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? jumpIntent,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT : PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
PendingIntent.FLAG_UPDATE_CURRENT );
);
Notification notification = new NotificationCompat.Builder(context, TASK_NOTIFICATION_CHANNEL_ID) // 4. 构建通知(核心:循环响铃+修复的系统默认铃声)
.setSmallIcon(R.mipmap.ic_launcher) NotificationCompat.Builder builder = new NotificationCompat.Builder(context, TASK_NOTIFICATION_CHANNEL_ID)
.setContentTitle("任务提醒") .setSmallIcon(R.mipmap.ic_launcher) // API 30强制要求否则通知不显示
.setContentText(taskDescription) .setContentTitle("任务提醒")
.setContentIntent(pendingIntent) .setContentText(taskDescription)
.setAutoCancel(true) .setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT) .setAutoCancel(true) // 点击后取消通知,停止循环响铃
.setDefaults(NotificationCompat.DEFAULT_SOUND) .setPriority(NotificationCompat.PRIORITY_DEFAULT) // 确保铃声能正常播放API 30规则
.build(); //.setVibrationPattern(new long[]{0, 300, 200, 300}) // 震动与铃声同步循环
.setOnlyAlertOnce(false); // 重复通知也触发循环提醒
notificationManager.notify(getNotificationId(taskId), notification); // 关键修复用RingtoneManager获取系统默认通知铃声替代废弃的NotificationManager.getDefaultUri
} Uri defaultNotificationRingtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (defaultNotificationRingtone != null) {
builder.setSound(defaultNotificationRingtone); // 设置系统默认铃声
} else {
builder.setDefaults(NotificationCompat.DEFAULT_SOUND); // 极端情况铃声Uri为空时用默认提醒音兜底
}
private static void createNotificationChannel(NotificationManager notificationManager) { // 5. 循环响铃核心设置FLAG_INSISTENT通知未取消则持续循环
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Notification notification = builder.build();
// 原有:任务通知渠道 notification.flags |= Notification.FLAG_INSISTENT;
NotificationChannel taskChannel = new NotificationChannel(
TASK_NOTIFICATION_CHANNEL_ID,
TASK_NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
);
taskChannel.setDescription("接收任务相关提醒,点击可查看任务详情");
taskChannel.enableVibration(true);
taskChannel.setVibrationPattern(new long[]{0, 300});
// 新增前台服务通知渠道重要性设为LOW避免频繁打扰用户 // 6. 显示通知(触发循环响铃
NotificationChannel foregroundChannel = new NotificationChannel( notificationManager.notify(getNotificationId(taskId), notification);
FOREGROUND_SERVICE_CHANNEL_ID, }
FOREGROUND_SERVICE_CHANNEL_NAME,
NotificationManager.IMPORTANCE_LOW // 仅通知栏显示,无提示音/震动,符合后台服务低打扰需求
);
foregroundChannel.setDescription("位置服务运行中用于后台持续获取GPS数据关闭会影响定位功能"); // 明确告知用户服务作用
foregroundChannel.enableVibration(false); // 前台服务通知不震动(避免打扰)
foregroundChannel.setSound(null, null); // 关闭提示音(低打扰)
// 注册两个渠道(任务+前台服务) // ---------------------- 核心创建通知渠道修复铃声配置适配API 30 ----------------------
notificationManager.createNotificationChannel(taskChannel); private static void createNotificationChannel(NotificationManager notificationManager) {
notificationManager.createNotificationChannel(foregroundChannel); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
} // 1. 任务通知渠道(用修复后的方式配置系统默认铃声)
} NotificationChannel taskChannel = new NotificationChannel(
TASK_NOTIFICATION_CHANNEL_ID,
TASK_NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT // 重要性≥DEFAULT否则铃声不响API 30规则
);
taskChannel.setDescription("任务提醒通知,铃声循环播放至点击取消");
taskChannel.enableVibration(true);
taskChannel.setVibrationPattern(new long[]{0, 300, 200, 300});
taskChannel.setAllowBubbles(false); // 避免气泡打断循环铃声
public static void cancel(Context context, String taskId) { // 关键修复渠道铃声也用RingtoneManager获取与通知Builder保持一致确保铃声统一
if (context == null || taskId == null) { Uri channelDefaultRingtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
return; taskChannel.setSound(channelDefaultRingtone, null); // 绑定系统默认铃声到渠道
}
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(getNotificationId(taskId));
}
}
// ---------------------- 新增核心功能创建前台服务通知供DistanceRefreshService调用 ---------------------- // 2. 前台服务渠道(低打扰,无声无震动)
/** NotificationChannel foregroundChannel = new NotificationChannel(
* 创建前台服务通知符合Android前台服务规范用于启动/保活DistanceRefreshService FOREGROUND_SERVICE_CHANNEL_ID,
* @param context 服务上下文直接传入DistanceRefreshService的this即可 FOREGROUND_SERVICE_CHANNEL_NAME,
* @param serviceStatus 服务状态文本如“正在后台获取GPS位置...”,动态展示服务状态) NotificationManager.IMPORTANCE_LOW
* @return 可直接用于startForeground()的Notification对象 );
*/ foregroundChannel.setDescription("位置服务运行中,无声音/震动提醒");
public static Notification createForegroundServiceNotification(Context context, String serviceStatus) { foregroundChannel.enableVibration(false);
// 安全校验:上下文非空(避免服务中调用时的空指针) foregroundChannel.setSound(null, null); // 明确关闭铃声
if (context == null) { foregroundChannel.setShowBadge(false);
throw new IllegalArgumentException("Context cannot be null for foreground service notification");
}
// 步骤1初始化通知管理器复用已有逻辑确保渠道已创建 // 注册渠道API 30覆盖旧配置确保修复后的铃声生效
NotificationManager notificationManager = notificationManager.createNotificationChannel(taskChannel);
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(foregroundChannel);
if (notificationManager != null) { }
createNotificationChannel(notificationManager); // 确保前台服务渠道已注册 }
}
// 步骤2构建“点击通知跳转至位置管理页”的Intent用户点击通知可进入功能页 // ---------------------- 原有功能:取消任务通知(停止循环响铃) ----------------------
Intent jumpIntent = new Intent(context, LocationActivity.class); public static void cancel(Context context, String taskId) {
jumpIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // 避免创建重复页面 if (context == null || taskId == null) {
return;
}
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(getNotificationId(taskId)); // 取消后循环铃声自动停止
}
}
// 步骤3创建PendingIntent授权系统在用户点击时执行跳转 // ---------------------- 前台服务通知适配API 30无声无震动 ----------------------
PendingIntent pendingIntent = PendingIntent.getActivity( public static Notification createForegroundServiceNotification(Context context, String serviceStatus) {
context, if (context == null) {
FOREGROUND_SERVICE_NOTIFICATION_ID, // 请求码与通知ID一致确保唯一 throw new IllegalArgumentException("Context cannot be null for foreground service notification");
jumpIntent, }
// 适配Android 6.0+IMMUTABLE确保安全性UPDATE_CURRENT确保Intent参数更新
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ?
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT :
PendingIntent.FLAG_UPDATE_CURRENT
);
// 步骤4构建前台服务通知低打扰、强关联服务状态 // 确保前台服务渠道已创建(低打扰配置
return new NotificationCompat.Builder(context, FOREGROUND_SERVICE_CHANNEL_ID) NotificationManager notificationManager =
.setSmallIcon(R.mipmap.ic_launcher) // 必须设置(系统强制要求,建议用应用图标) (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
.setContentTitle("位置服务运行中") // 固定标题,用户快速识别服务类型 if (notificationManager != null) {
.setContentText(serviceStatus) // 动态内容如“正在获取GPS位置”“已连续运行30分钟” createNotificationChannel(notificationManager);
.setContentIntent(pendingIntent) // 点击跳转至功能页 }
.setOngoing(true) // 关键:设置为“不可手动清除”(仅服务停止时能取消,符合前台服务规范)
.setPriority(NotificationCompat.PRIORITY_LOW) // 低优先级:不弹窗、不抢占通知栏焦点
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.build();
}
/** // 点击跳转Intent
* 配套工具方法更新前台服务通知的状态文本如GPS获取进度、运行时长 Intent jumpIntent = new Intent(context, LocationActivity.class);
* @param context 服务上下文 jumpIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
* @param newServiceStatus 新的状态文本如“已获取最新位置北纬30.123°”)
*/ // PendingIntentAPI 30必加IMMUTABLE
public static void updateForegroundServiceStatus(Context context, String newServiceStatus) { PendingIntent pendingIntent = PendingIntent.getActivity(
if (context == null) { context,
return; FOREGROUND_SERVICE_NOTIFICATION_ID,
} jumpIntent,
// 重新创建通知复用create方法传入新状态文本 PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
Notification updatedNotification = createForegroundServiceNotification(context, newServiceStatus); );
// 用相同ID更新通知覆盖旧通知实现状态刷新
NotificationManager notificationManager = // 构建前台服务通知(无声无震动,符合低打扰)
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); return new NotificationCompat.Builder(context, FOREGROUND_SERVICE_CHANNEL_ID)
if (notificationManager != null) { .setSmallIcon(R.mipmap.ic_launcher)
notificationManager.notify(FOREGROUND_SERVICE_NOTIFICATION_ID, updatedNotification); .setContentTitle("位置服务运行中")
} .setContentText(serviceStatus)
} .setContentIntent(pendingIntent)
.setOngoing(true) // 不可手动清除(前台服务规范)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setDefaults(0) // 禁用所有默认提醒(无声无震动)
.build();
}
// ---------------------- 前台服务通知状态更新适配API 30 ----------------------
public static void updateForegroundServiceStatus(Context context, String newServiceStatus) {
if (context == null) {
return;
}
Notification updatedNotification = createForegroundServiceNotification(context, newServiceStatus);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(FOREGROUND_SERVICE_NOTIFICATION_ID, updatedNotification);
}
}
} }

View File

@@ -3,7 +3,7 @@ package cc.winboll.studio.positions.views;
/** /**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
* @Date 2025/09/30 08:09 * @Date 2025/09/30 08:09
* @Describe 位置任务列表视图(支持简单/编辑模式,含 isBingo 红点标识 * @Describe 位置任务列表视图(适配MainService唯一数据源+同步任务状态+支持简单/编辑模式)
*/ */
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
@@ -22,8 +22,10 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.positions.R; import cc.winboll.studio.positions.R;
import cc.winboll.studio.positions.models.PositionTaskModel; import cc.winboll.studio.positions.models.PositionTaskModel;
import cc.winboll.studio.positions.services.MainService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -32,21 +34,21 @@ public class PositionTaskListView extends LinearLayout {
public static final int VIEW_MODE_SIMPLE = 1; public static final int VIEW_MODE_SIMPLE = 1;
public static final int VIEW_MODE_EDIT = 2; public static final int VIEW_MODE_EDIT = 2;
// 核心成员变量 // 核心成员变量新增MainService引用作为唯一数据源
private String mBindPositionId; private String mBindPositionId;
private ArrayList<PositionTaskModel> mTaskList; private MainService mMainService; // 持有MainService实例所有任务数据从服务获取
private int mCurrentViewMode; private int mCurrentViewMode;
private TaskListAdapter mTaskAdapter; private TaskListAdapter mTaskAdapter;
private RecyclerView mRvTasks; private RecyclerView mRvTasks;
// 任务修改回调接口 // 任务修改回调接口保留用于通知外部同步UI
public interface OnTaskUpdatedListener { public interface OnTaskUpdatedListener {
void onTaskUpdated(String positionId, ArrayList<PositionTaskModel> updatedTasks); void onTaskUpdated(String positionId, ArrayList<PositionTaskModel> updatedTasks);
} }
private OnTaskUpdatedListener mOnTaskUpdatedListener; private OnTaskUpdatedListener mOnTaskUpdatedListener;
// ---------------------- 构造函数 ---------------------- // ---------------------- 构造函数不变新增MainService空校验 ----------------------
public PositionTaskListView(Context context) { public PositionTaskListView(Context context) {
super(context); super(context);
initView(context); initView(context);
@@ -62,7 +64,7 @@ public class PositionTaskListView extends LinearLayout {
initView(context); initView(context);
} }
// 初始化视图(绑定控件+设置布局) // 初始化视图(绑定控件+设置布局Adapter初始化为空数据
private void initView(Context context) { private void initView(Context context) {
setOrientation(VERTICAL); setOrientation(VERTICAL);
LayoutInflater.from(context).inflate(R.layout.view_position_task_list, this, true); LayoutInflater.from(context).inflate(R.layout.view_position_task_list, this, true);
@@ -70,94 +72,204 @@ public class PositionTaskListView extends LinearLayout {
mRvTasks = (RecyclerView) findViewById(R.id.rv_position_tasks); mRvTasks = (RecyclerView) findViewById(R.id.rv_position_tasks);
mRvTasks.setLayoutManager(new LinearLayoutManager(context)); mRvTasks.setLayoutManager(new LinearLayoutManager(context));
mTaskList = new ArrayList<PositionTaskModel>(); // 初始化为空列表数据后续从MainService同步
mTaskAdapter = new TaskListAdapter(mTaskList); mTaskAdapter = new TaskListAdapter(new ArrayList<PositionTaskModel>());
mRvTasks.setAdapter(mTaskAdapter); mRvTasks.setAdapter(mTaskAdapter);
mCurrentViewMode = VIEW_MODE_SIMPLE; mCurrentViewMode = VIEW_MODE_SIMPLE;
LogUtils.d(TAG, "视图初始化完成等待绑定MainService和位置ID");
} }
// ---------------------- 对外API ---------------------- // ---------------------- 对外API核心调整绑定MainService+从服务同步数据) ----------------------
public void init(ArrayList<PositionTaskModel> taskList, String positionId) { /**
* 初始化绑定MainService+关联位置ID必须先调用此方法否则无数据
* @param mainService MainService实例从Activity传入确保唯一数据源
* @param positionId 关联的位置ID只加载该位置下的任务
*/
public void init(MainService mainService, String positionId) {
if (mainService == null) {
LogUtils.e(TAG, "init失败MainService实例为空需从Activity传入有效服务实例");
showToast("任务列表初始化失败:服务未就绪");
return;
}
if (positionId == null || positionId.trim().isEmpty()) {
LogUtils.e(TAG, "init失败位置ID为空需关联有效位置");
showToast("任务列表初始化失败:未关联位置");
return;
}
// 绑定服务实例+位置ID
this.mMainService = mainService;
this.mBindPositionId = positionId; this.mBindPositionId = positionId;
if (this.mTaskList.isEmpty()) { LogUtils.d(TAG, "已绑定MainService和位置ID" + positionId);
ArrayList<PositionTaskModel> matchedTasks = new ArrayList<PositionTaskModel>();
if (taskList != null && !taskList.isEmpty()) { // 从MainService同步当前位置的任务核心数据来源改为服务
for (PositionTaskModel task : taskList) { syncTasksFromMainService();
if (task != null && positionId.equals(task.getPositionId())) { }
matchedTasks.add(task);
/**
* 从MainService同步当前位置的任务核心方法所有数据加载入口
* 作用1. 清空本地缓存→2. 从服务获取全量任务→3. 筛选当前位置任务→4. 刷新Adapter
*/
public void syncTasksFromMainService() {
// 安全校验(服务未绑定/位置ID为空不执行同步
if (mMainService == null || mBindPositionId == null || mBindPositionId.trim().isEmpty()) {
LogUtils.w(TAG, "同步任务失败MainService未绑定或位置ID无效");
return;
}
try {
// 1. 从MainService获取全量任务服务是唯一数据源避免本地缓存不一致
ArrayList<PositionTaskModel> allServiceTasks = mMainService.getAllTasks();
LogUtils.d(TAG, "从MainService获取全量任务数" + (allServiceTasks == null ? 0 : allServiceTasks.size()));
// 2. 筛选当前位置关联的任务只保留与mBindPositionId匹配的任务
ArrayList<PositionTaskModel> currentPosTasks = new ArrayList<PositionTaskModel>();
if (allServiceTasks != null && !allServiceTasks.isEmpty()) {
for (PositionTaskModel task : allServiceTasks) {
if (isTaskMatchedWithPosition(task)) {
currentPosTasks.add(task);
} }
} }
} }
mTaskList.clear(); LogUtils.d(TAG, "筛选后当前位置任务数:" + currentPosTasks.size());
mTaskList.addAll(matchedTasks);
// 3. 更新Adapter数据直接替换数据源避免本地缓存
mTaskAdapter.updateData(currentPosTasks);
LogUtils.d(TAG, "从MainService同步任务完成Adapter已刷新");
} catch (Exception e) {
LogUtils.d(TAG, "同步任务失败MainService调用异常" + e.getMessage());
showToast("任务同步失败,请重试");
} }
mTaskAdapter.notifyDataSetChanged();
} }
// 视图模式切换不变刷新Adapter触发视图类型变更
public void setViewStatus(int viewMode) { public void setViewStatus(int viewMode) {
if (viewMode != VIEW_MODE_SIMPLE && viewMode != VIEW_MODE_EDIT) { if (viewMode != VIEW_MODE_SIMPLE && viewMode != VIEW_MODE_EDIT) {
LogUtils.w(TAG, "设置视图模式失败:无效模式(仅支持简单/编辑模式)");
return; return;
} }
mCurrentViewMode = viewMode; mCurrentViewMode = viewMode;
mTaskAdapter.notifyDataSetChanged(); mTaskAdapter.notifyDataSetChanged();
LogUtils.d(TAG, "已切换视图模式:" + (viewMode == VIEW_MODE_SIMPLE ? "简单模式" : "编辑模式"));
} }
// 保留回调接口用于通知外部UI刷新如Activity更新列表
public void setOnTaskUpdatedListener(OnTaskUpdatedListener listener) { public void setOnTaskUpdatedListener(OnTaskUpdatedListener listener) {
this.mOnTaskUpdatedListener = listener; this.mOnTaskUpdatedListener = listener;
LogUtils.d(TAG, "已设置任务更新回调监听");
} }
public ArrayList<PositionTaskModel> getAllTasks() { /**
return new ArrayList<PositionTaskModel>(mTaskList); * 获取当前位置的任务从Adapter数据源获取而非本地缓存
* @return 当前位置任务列表(新集合,避免外部修改数据源)
*/
public ArrayList<PositionTaskModel> getCurrentPosTasks() {
return new ArrayList<PositionTaskModel>(mTaskAdapter.getAdapterData());
} }
/**
* 清空数据(解绑服务+清空位置ID+重置Adapter
* 场景:视图销毁/切换位置时调用,避免数据残留
*/
public void clearData() { public void clearData() {
mTaskList.clear(); // 1. 清空Adapter数据源
if (mTaskAdapter != null && mTaskAdapter.mData != null) { mTaskAdapter.updateData(new ArrayList<PositionTaskModel>());
mTaskAdapter.mData.clear(); // 2. 解绑服务+位置ID避免下次使用时引用旧数据
} this.mMainService = null;
mTaskAdapter.notifyDataSetChanged(); this.mBindPositionId = null;
mBindPositionId = null; // 3. 重置视图模式
mCurrentViewMode = VIEW_MODE_SIMPLE;
LogUtils.d(TAG, "数据已清空(解绑服务+重置视图)");
} }
/**
* 主动触发任务同步(强制从服务拉取最新数据,刷新视图)
* 场景:外部操作后(如新增任务),调用此方法更新列表
*/
public void triggerTaskSync() { public void triggerTaskSync() {
LogUtils.d(TAG, "主动触发任务同步从MainService拉取最新数据");
syncTasksFromMainService();
// 通知外部如Activity任务已更新可选根据业务需求
if (mOnTaskUpdatedListener != null && mBindPositionId != null) { if (mOnTaskUpdatedListener != null && mBindPositionId != null) {
mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mTaskList)); mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, getCurrentPosTasks());
} }
} }
// ---------------------- 内部工具方法 ---------------------- // ---------------------- 内部工具方法(新增服务空校验) ----------------------
private static final String TAG = "PositionTaskListView";
/**
* 校验任务是否与当前绑定的位置匹配
* @param task 待校验的任务
* @return true=匹配任务位置ID=当前绑定位置IDfalse=不匹配
*/
private boolean isTaskMatchedWithPosition(PositionTaskModel task) { private boolean isTaskMatchedWithPosition(PositionTaskModel task) {
if (task == null || mBindPositionId == null || mBindPositionId.trim().isEmpty()) { if (task == null || mBindPositionId == null || mBindPositionId.trim().isEmpty()) {
return false; return false;
} }
// 严格匹配任务的位置ID确保只加载当前位置的任务
return mBindPositionId.equals(task.getPositionId()); return mBindPositionId.equals(task.getPositionId());
} }
// ---------------------- 内部Adapter适配 isBingo 红点(核心调整) ---------------------- /**
private class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.TaskViewHolder> { * 显示Toast简化调用避免重复代码
private final List<PositionTaskModel> mData; */
private void showToast(String content) {
if (getContext() == null) return;
Toast.makeText(getContext(), content, Toast.LENGTH_SHORT).show();
}
// ---------------------- 内部Adapter适配MainService数据源核心调整 ----------------------
private class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.TaskViewHolder> {
// Adapter数据源仅保留一份直接从MainService同步无本地冗余
private List<PositionTaskModel> mAdapterData;
// 初始化Adapter空数据源
public TaskListAdapter(List<PositionTaskModel> data) { public TaskListAdapter(List<PositionTaskModel> data) {
this.mData = data; this.mAdapterData = new ArrayList<PositionTaskModel>(data); // 防御性拷贝,避免外部修改
} }
/**
* 更新Adapter数据源核心从MainService同步后调用替换数据源并刷新
* @param newData 从MainService筛选后的当前位置任务列表
*/
public void updateData(List<PositionTaskModel> newData) {
if (newData == null) {
this.mAdapterData.clear();
} else {
this.mAdapterData = new ArrayList<PositionTaskModel>(newData); // 防御性拷贝
}
notifyDataSetChanged(); // 刷新列表(数据源已替换,确保显示最新数据)
}
/**
* 获取Adapter当前数据源对外提供避免直接操作mAdapterData
* @return 当前数据源(新集合,避免外部修改)
*/
public List<PositionTaskModel> getAdapterData() {
return new ArrayList<PositionTaskModel>(mAdapterData);
}
// getItemCount空列表显示1个“空提示”项非空显示任务数
@Override @Override
public int getItemCount() { public int getItemCount() {
return mData.isEmpty() ? 1 : mData.size(); return mAdapterData.isEmpty() ? 1 : mAdapterData.size();
} }
// 调整:根据“是否空列表”+“视图模式”区分视图类型(确保简单/编辑模式加载对应布局 // getItemViewType按“空列表/简单模式/编辑模式”区分视图类型(不变
@Override @Override
public int getItemViewType(int position) { public int getItemViewType(int position) {
if (mData.isEmpty()) { if (mAdapterData.isEmpty()) {
return 0; // 0=空提示 return 0; // 0=空提示视图
} else { } else {
return mCurrentViewMode; // 1=简单模式2=编辑模式(复用视图模式常量) return mCurrentViewMode; // 1=简单模式视图2=编辑模式视图
} }
} }
// 调整:按视图类型加载布局(简单模式加载带红点的布局,编辑模式加载原有布局 // onCreateViewHolder:按视图类型加载对应布局(不变,确保布局与模式匹配
@NonNull @NonNull
@Override @Override
public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@@ -165,150 +277,219 @@ public class PositionTaskListView extends LinearLayout {
LayoutInflater inflater = LayoutInflater.from(context); LayoutInflater inflater = LayoutInflater.from(context);
if (viewType == 0) { if (viewType == 0) {
// 空提示布局 // 空提示布局(无任务时显示)
View emptyView = inflater.inflate(R.layout.item_task_empty, parent, false); View emptyView = inflater.inflate(R.layout.item_task_empty, parent, false);
return new EmptyViewHolder(emptyView); return new EmptyViewHolder(emptyView);
} else if (viewType == VIEW_MODE_SIMPLE) { } else if (viewType == VIEW_MODE_SIMPLE) {
// 简单模式布局(带 isBingo 红点) // 简单模式布局带isBingo红点,仅展示
View simpleTaskView = inflater.inflate(R.layout.item_position_task_simple, parent, false); View simpleTaskView = inflater.inflate(R.layout.item_position_task_simple, parent, false);
return new SimpleTaskViewHolder(simpleTaskView); return new SimpleTaskViewHolder(simpleTaskView);
} else { } else {
// 编辑模式布局(原有布局不变 // 编辑模式布局(带编辑/删除按钮+启用开关,支持修改
View editTaskView = inflater.inflate(R.layout.item_task_content, parent, false); View editTaskView = inflater.inflate(R.layout.item_task_content, parent, false);
return new TaskContentViewHolder(editTaskView); return new TaskContentViewHolder(editTaskView);
} }
} }
// 调整:按视图类型绑定数据(简单模式绑定红点+文本,编辑模式绑定原有逻辑 // onBindViewHolder按视图类型绑定数据核心调整操作后同步MainService
@Override @Override
public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) { public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
// 空提示处理(不变 // 1. 空提示视图绑定(根据模式显示不同提示文案
if (holder instanceof EmptyViewHolder) { if (holder instanceof EmptyViewHolder) {
EmptyViewHolder emptyHolder = (EmptyViewHolder) holder; EmptyViewHolder emptyHolder = (EmptyViewHolder) holder;
TextView tvEmptyTip = (TextView) emptyHolder.itemView.findViewById(R.id.tv_task_empty_tip); TextView tvEmptyTip = emptyHolder.itemView.findViewById(R.id.tv_task_empty_tip);
tvEmptyTip.setText(mCurrentViewMode == VIEW_MODE_EDIT ? "暂无任务,点击\"添加新任务\"创建" : "暂无启用的任务"); tvEmptyTip.setText(mCurrentViewMode == VIEW_MODE_EDIT
? "暂无任务,点击\"添加新任务\"创建"
: "暂无启用的任务");
return; return;
} }
// 任务项有效性校验(不变 // 2. 任务项有效性校验(避免越界/空数据
if (position >= mData.size()) { if (position >= mAdapterData.size()) {
LogUtils.w(TAG, "绑定任务数据失败位置索引越界position=" + position + ",数据量=" + mAdapterData.size() + "");
return; return;
} }
final PositionTaskModel task = mData.get(position); final PositionTaskModel task = mAdapterData.get(position);
if (task == null) { if (task == null) {
LogUtils.w(TAG, "绑定任务数据失败:第" + position + "项任务为空");
return; return;
} }
// 简单模式绑定红点isBingo和文本数据 // 3. 简单模式绑定(仅展示,无修改操作,不变)
if (holder instanceof SimpleTaskViewHolder) { if (holder instanceof SimpleTaskViewHolder) {
SimpleTaskViewHolder simpleHolder = (SimpleTaskViewHolder) holder; SimpleTaskViewHolder simpleHolder = (SimpleTaskViewHolder) holder;
// 绑定任务描述 // 任务描述
simpleHolder.tvSimpleTaskDesc.setText(String.format("任务:%s", task.getTaskDescription())); String taskDesc = task.getTaskDescription() == null ? "未设置描述" : task.getTaskDescription();
// 绑定距离条件 simpleHolder.tvSimpleTaskDesc.setText(String.format("任务:%s", taskDesc));
// 距离条件(大于/小于+距离值)
String distanceCond = task.isGreaterThan() ? "大于" : "小于"; String distanceCond = task.isGreaterThan() ? "大于" : "小于";
simpleHolder.tvSimpleDistanceCond.setText(String.format("条件:距离 %s %d 米", distanceCond, task.getDiscussDistance())); simpleHolder.tvSimpleDistanceCond.setText(String.format("条件:距离 %s %d 米", distanceCond, task.getDiscussDistance()));
// 绑定启用状态 // 启用状态
simpleHolder.tvSimpleIsEnable.setText(task.isEnable() ? "状态:已启用" : "状态:已禁用"); simpleHolder.tvSimpleIsEnable.setText(task.isEnable() ? "状态:已启用" : "状态:已禁用");
// 核心:根据 isBingo 控制红点显示true=显示false=隐藏) // isBingo红点(任务触发时显示,未触发时隐藏)
simpleHolder.vBingoDot.setVisibility(task.isBingo() ? View.VISIBLE : View.GONE); simpleHolder.vBingoDot.setVisibility(task.isBingo() ? View.VISIBLE : View.GONE);
} }
// 编辑模式:沿用原有绑定逻辑(核心修复在此处)
// 4. 编辑模式绑定核心调整所有修改操作后同步MainService
else if (holder instanceof TaskContentViewHolder) { else if (holder instanceof TaskContentViewHolder) {
TaskContentViewHolder contentHolder = (TaskContentViewHolder) holder; TaskContentViewHolder contentHolder = (TaskContentViewHolder) holder;
bindTaskData(contentHolder, task, position); bindEditModeTask(contentHolder, task, position);
} }
} }
// ---------------------- 核心修复:编辑模式绑定逻辑(解决布局中通知异常) ---------------------- /**
private void bindTaskData(final TaskContentViewHolder holder, final PositionTaskModel task, final int position) { * 编辑模式任务绑定核心修改操作→更新MainService→刷新Adapter
String taskDesc = (task.getTaskDescription() == null) ? "未设置描述" : task.getTaskDescription(); */
private void bindEditModeTask(final TaskContentViewHolder holder, final PositionTaskModel task, final int position) {
// 4.1 绑定基础数据(描述+距离条件)
String taskDesc = task.getTaskDescription() == null ? "未设置描述" : task.getTaskDescription();
holder.tvTaskDesc.setText(String.format("任务:%s", taskDesc)); holder.tvTaskDesc.setText(String.format("任务:%s", taskDesc));
String distanceCond = task.isGreaterThan() ? "大于" : "小于";
holder.tvTaskDistance.setText(String.format("条件:%s %d 米", distanceCond, task.getDiscussDistance()));
String distanceCondition = task.isGreaterThan() ? "大于" : "小于"; // 4.2 绑定“启用开关”(修复:先解绑监听→设值→再绑定监听,避免设值触发回调)
holder.tvTaskDistance.setText(String.format("条件:%s %d 米", distanceCondition, task.getDiscussDistance()));
// 修复点1先移除开关监听再设置状态避免设值时触发回调导致异常
holder.cbTaskEnable.setOnCheckedChangeListener(null); holder.cbTaskEnable.setOnCheckedChangeListener(null);
holder.cbTaskEnable.setChecked(task.isEnable()); holder.cbTaskEnable.setChecked(task.isEnable());
holder.cbTaskEnable.setEnabled(mCurrentViewMode == VIEW_MODE_EDIT); holder.cbTaskEnable.setEnabled(mCurrentViewMode == VIEW_MODE_EDIT); // 编辑模式才允许操作
if (mCurrentViewMode == VIEW_MODE_EDIT) { // 4.3 编辑模式特有:显示编辑/删除按钮(仅编辑模式可见)
holder.btnEditTask.setVisibility(View.VISIBLE); holder.btnEditTask.setVisibility(View.VISIBLE);
holder.btnDeleteTask.setVisibility(View.VISIBLE); holder.btnDeleteTask.setVisibility(View.VISIBLE);
// 删除按钮逻辑(不变,本身在点击时执行,不涉及布局中通知 // 4.4 删除按钮逻辑核心删除→同步MainService→刷新Adapter
holder.btnDeleteTask.setOnClickListener(new View.OnClickListener() { holder.btnDeleteTask.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
mData.remove(position); if (mMainService == null) {
showToast("删除失败:服务未就绪");
LogUtils.e(TAG, "删除任务失败MainService实例为空");
return;
}
try {
// 步骤1调用MainService删除任务服务是唯一数据源确保数据一致性
mMainService.deleteTask(task.getTaskId()); // 需在MainService中实现deleteTask()方法(删除服务内全量任务列表中的对应项)
LogUtils.d(TAG, "调用MainService删除任务ID=" + task.getTaskId() + "位置ID=" + mBindPositionId + "");
// 步骤2从Adapter数据源移除任务避免等待同步立即反馈UI
mAdapterData.remove(position);
// 步骤3刷新Adapter局部刷新+范围通知,避免列表错乱)
notifyItemRemoved(position); notifyItemRemoved(position);
notifyItemRangeChanged(position, mData.size()); notifyItemRangeChanged(position, mAdapterData.size());
LogUtils.d(TAG, "Adapter已移除任务刷新列表位置索引=" + position + "");
// 步骤4通知外部如Activity任务已更新
if (mOnTaskUpdatedListener != null && mBindPositionId != null) { if (mOnTaskUpdatedListener != null && mBindPositionId != null) {
mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mData)); mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mAdapterData));
} }
Toast.makeText(getContext(), "任务已删除", Toast.LENGTH_SHORT).show(); showToast("任务已删除(已同步至服务)");
}
});
// 编辑按钮逻辑(不变,弹窗保存时修复通知时机) } catch (Exception e) {
holder.btnEditTask.setOnClickListener(new View.OnClickListener() { LogUtils.d(TAG, "删除任务失败(服务调用/Adapter刷新异常" + e.getMessage());
@Override showToast("删除失败,请重试");
public void onClick(View v) { // 异常时重新同步数据确保Adapter与服务一致
showTaskEditDialog(task, position); syncTasksFromMainService();
} }
}); }
});
// 修复点2开关监听-用 RecyclerView.post 延迟执行 notify避免布局中调用 // 4.5 编辑按钮逻辑核心修改后同步MainService→刷新Adapter
holder.cbTaskEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { holder.btnEditTask.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { public void onClick(View v) {
task.setIsEnable(isChecked); // 先更新数据源(必须执行) if (mMainService == null) {
// 关键:通过 mRvTasks.post 延迟通知,确保在布局计算/滚动结束后执行 showToast("编辑失败:服务未就绪");
LogUtils.e(TAG, "编辑任务失败MainService实例为空");
return;
}
// 弹出编辑弹窗(修改后同步服务)
showEditTaskDialog(task, position);
}
});
// 4.6 启用开关逻辑核心状态变更→同步MainService→刷新Adapter
holder.cbTaskEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
if (mMainService == null) {
showToast("状态修改失败:服务未就绪");
LogUtils.e(TAG, "修改任务启用状态失败MainService实例为空");
// 回滚开关状态避免UI与服务不一致
buttonView.setChecked(!isChecked);
return;
}
try {
// 步骤1更新任务状态先改内存数据确保UI反馈及时
task.setIsEnable(isChecked);
LogUtils.d(TAG, "更新任务启用状态ID=" + task.getTaskId() + ",新状态=" + (isChecked ? "启用" : "禁用"));
// 步骤2调用MainService同步状态服务是唯一数据源持久化变更
mMainService.updateTaskStatus(task); // 需在MainService中实现updateTaskStatus()方法更新服务内任务的isEnable字段
LogUtils.d(TAG, "调用MainService同步任务状态" + (isChecked ? "启用" : "禁用") + "");
// 步骤3延迟刷新Adapter避免列表滚动/布局计算时异常)
mRvTasks.post(new Runnable() { mRvTasks.post(new Runnable() {
@Override @Override
public void run() { public void run() {
notifyItemChanged(position); notifyItemChanged(position);
// 通知外部任务已更新
if (mOnTaskUpdatedListener != null && mBindPositionId != null) { if (mOnTaskUpdatedListener != null && mBindPositionId != null) {
mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mData)); mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mAdapterData));
} }
} }
}); });
} catch (Exception e) {
LogUtils.d(TAG, "修改任务启用状态失败:" + e.getMessage());
showToast("状态修改失败,请重试");
// 回滚状态UI与服务保持一致
buttonView.setChecked(!isChecked);
task.setIsEnable(!isChecked);
// 重新同步数据(修复可能的不一致)
syncTasksFromMainService();
} }
}); }
} else { });
holder.btnEditTask.setVisibility(View.GONE);
holder.btnDeleteTask.setVisibility(View.GONE);
holder.cbTaskEnable.setOnCheckedChangeListener(null);
}
} }
// ---------------------- 修复:编辑弹窗保存逻辑(延迟通知,避免极端场景异常) ---------------------- /**
private void showTaskEditDialog(final PositionTaskModel task, final int position) { * 编辑任务弹窗核心保存修改→同步MainService→刷新Adapter
final Context context = getContext(); */
private void showEditTaskDialog(final PositionTaskModel task, final int position) {
Context context = getContext();
if (context == null) {
LogUtils.w(TAG, "编辑弹窗无法显示:上下文为空");
return;
}
// 加载弹窗布局
View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_edit_task, null); View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_edit_task, null);
final EditText etEditDesc = dialogView.findViewById(R.id.et_edit_task_desc);
final RadioGroup rgDistanceCondition = dialogView.findViewById(R.id.rg_distance_condition);
final EditText etEditDistance = dialogView.findViewById(R.id.et_edit_distance);
Button btnCancel = dialogView.findViewById(R.id.btn_dialog_cancel);
Button btnSave = dialogView.findViewById(R.id.btn_dialog_save);
final EditText etEditDesc = (EditText) dialogView.findViewById(R.id.et_edit_task_desc); // 初始化弹窗数据(填充当前任务信息)
final RadioGroup rgDistanceCondition = (RadioGroup) dialogView.findViewById(R.id.rg_distance_condition); etEditDesc.setText(task.getTaskDescription() == null ? "" : task.getTaskDescription());
final EditText etEditDistance = (EditText) dialogView.findViewById(R.id.et_edit_distance); etEditDesc.setSelection(etEditDesc.getText().length()); // 光标定位到末尾
Button btnCancel = (Button) dialogView.findViewById(R.id.btn_dialog_cancel); // 初始化距离条件(大于/小于)
Button btnSave = (Button) dialogView.findViewById(R.id.btn_dialog_save);
etEditDesc.setText(task.getTaskDescription());
etEditDesc.setSelection(etEditDesc.getText().length());
if (task.isGreaterThan()) { if (task.isGreaterThan()) {
rgDistanceCondition.check(R.id.rb_greater_than); rgDistanceCondition.check(R.id.rb_greater_than);
} else { } else {
rgDistanceCondition.check(R.id.rb_less_than); rgDistanceCondition.check(R.id.rb_less_than);
} }
etEditDistance.setText(String.valueOf(task.getDiscussDistance())); // 填充当前距离
etEditDistance.setText(String.valueOf(task.getDiscussDistance())); // 创建并显示弹窗
final android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(context) final android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(context)
.setView(dialogView) .setView(dialogView)
.setCancelable(false) // 不允许点击外部关闭(避免未保存退出)
.create(); .create();
dialog.show(); dialog.show();
// 取消按钮:关闭弹窗(不做操作)
btnCancel.setOnClickListener(new View.OnClickListener() { btnCancel.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
@@ -316,14 +497,17 @@ public class PositionTaskListView extends LinearLayout {
} }
}); });
// 保存按钮校验输入→更新任务→同步服务→刷新UI
btnSave.setOnClickListener(new View.OnClickListener() { btnSave.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
// 1. 输入校验(避免无效数据)
String newDesc = etEditDesc.getText().toString().trim(); String newDesc = etEditDesc.getText().toString().trim();
String distanceStr = etEditDistance.getText().toString().trim(); String distanceStr = etEditDistance.getText().toString().trim();
if (distanceStr.isEmpty()) { if (distanceStr.isEmpty()) {
Toast.makeText(context, "请输入有效距离", Toast.LENGTH_SHORT).show(); showToast("请输入有效距离1米及以上");
etEditDistance.requestFocus();
return; return;
} }
@@ -331,62 +515,80 @@ public class PositionTaskListView extends LinearLayout {
try { try {
newDistance = Integer.parseInt(distanceStr); newDistance = Integer.parseInt(distanceStr);
if (newDistance < 1) { if (newDistance < 1) {
Toast.makeText(context, "距离不能小于1米", Toast.LENGTH_SHORT).show(); showToast("距离不能小于1米");
etEditDistance.requestFocus();
return; return;
} }
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Toast.makeText(context, "距离请输入数字", Toast.LENGTH_SHORT).show(); showToast("距离请输入数字");
etEditDistance.requestFocus();
return; return;
} }
task.setTaskDescription(newDesc); // 2. 收集新数据(更新任务对象)
task.setDiscussDistance(newDistance); task.setTaskDescription(newDesc); // 新描述
task.setDiscussDistance(newDistance); // 新距离
boolean isGreater = rgDistanceCondition.getCheckedRadioButtonId() == R.id.rb_greater_than; boolean isGreater = rgDistanceCondition.getCheckedRadioButtonId() == R.id.rb_greater_than;
task.setIsGreaterThan(isGreater); task.setIsGreaterThan(isGreater); // 新距离条件(大于/小于)
task.setPositionId(mBindPositionId); task.setPositionId(mBindPositionId); // 确保位置ID不变防止错位
// 修复点3弹窗保存后延迟通知同开关逻辑避免列表滚动时异常 try {
mRvTasks.post(new Runnable() { // 3. 调用MainService同步修改服务是唯一数据源持久化变更
@Override mMainService.updateTask(task); // 需在MainService中实现updateTask()方法(更新服务内任务的字段)
public void run() { LogUtils.d(TAG, "调用MainService更新任务ID=" + task.getTaskId() + "(描述=" + newDesc + ",距离=" + newDistance + "米)");
notifyItemChanged(position);
if (mOnTaskUpdatedListener != null && mBindPositionId != null) { // 4. 更新Adapter数据源立即反馈UI
mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mData)); mAdapterData.set(position, task);
// 5. 延迟刷新Adapter避免弹窗未关闭时布局异常
mRvTasks.post(new Runnable() {
@Override
public void run() {
notifyItemChanged(position);
// 通知外部任务已更新
if (mOnTaskUpdatedListener != null && mBindPositionId != null) {
mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mAdapterData));
}
} }
} });
});
dialog.dismiss(); dialog.dismiss();
Toast.makeText(context, "任务已更新", Toast.LENGTH_SHORT).show(); showToast("任务已更新(已同步至服务)");
} catch (Exception e) {
LogUtils.d(TAG, "保存任务修改失败:" + e.getMessage());
showToast("保存失败,请重试");
// 重新同步数据(修复可能的不一致)
syncTasksFromMainService();
}
} }
}); });
} }
// ---------------------- ViewHolder 定义(完全不变 ---------------------- // ---------------------- ViewHolder 定义(完全适配布局,无修改 ----------------------
// 基础抽象 ViewHolder不变 // 基础抽象ViewHolder统一父类,适配多视图类型
public abstract class TaskViewHolder extends RecyclerView.ViewHolder { public abstract class TaskViewHolder extends RecyclerView.ViewHolder {
public TaskViewHolder(@NonNull View itemView) { public TaskViewHolder(@NonNull View itemView) {
super(itemView); super(itemView);
} }
} }
// 空提示 Holder不变 // 空提示ViewHolder对应 item_task_empty.xml
public class EmptyViewHolder extends TaskViewHolder { public class EmptyViewHolder extends TaskViewHolder {
public EmptyViewHolder(@NonNull View itemView) { public EmptyViewHolder(@NonNull View itemView) {
super(itemView); super(itemView);
} }
} }
// 新增:简单模式 Holder绑定带红点的布局控件 // 简单模式ViewHolder对应 item_position_task_simple.xml带isBingo红点
public class SimpleTaskViewHolder extends TaskViewHolder { public class SimpleTaskViewHolder extends TaskViewHolder {
TextView tvSimpleTaskDesc; // 任务描述 TextView tvSimpleTaskDesc; // 任务描述
TextView tvSimpleDistanceCond;// 距离条件 TextView tvSimpleDistanceCond;// 距离条件(大于/小于+距离)
TextView tvSimpleIsEnable; // 启用状态 TextView tvSimpleIsEnable; // 启用状态(已启用/已禁用)
View vBingoDot; // isBingo 红点控件 View vBingoDot; // isBingo红点(任务触发时显示)
public SimpleTaskViewHolder(@NonNull View itemView) { public SimpleTaskViewHolder(@NonNull View itemView) {
super(itemView); super(itemView);
// 绑定简单模式布局中的控件(与 item_task_simple.xml 完全对应) // 绑定简单模式布局控件(与XML控件ID严格对应)
tvSimpleTaskDesc = itemView.findViewById(R.id.tv_simple_task_desc); tvSimpleTaskDesc = itemView.findViewById(R.id.tv_simple_task_desc);
tvSimpleDistanceCond = itemView.findViewById(R.id.tv_simple_distance_cond); tvSimpleDistanceCond = itemView.findViewById(R.id.tv_simple_distance_cond);
tvSimpleIsEnable = itemView.findViewById(R.id.tv_simple_is_enable); tvSimpleIsEnable = itemView.findViewById(R.id.tv_simple_is_enable);
@@ -394,23 +596,69 @@ public class PositionTaskListView extends LinearLayout {
} }
} }
// 编辑模式 Holder原有逻辑,完全不变 // 编辑模式ViewHolder对应 item_task_content.xml带编辑/删除/开关
public class TaskContentViewHolder extends TaskViewHolder { public class TaskContentViewHolder extends TaskViewHolder {
TextView tvTaskDesc; TextView tvTaskDesc; // 任务描述
TextView tvTaskDistance; TextView tvTaskDistance; // 距离条件
CompoundButton cbTaskEnable; CompoundButton cbTaskEnable; // 启用开关
Button btnEditTask; Button btnEditTask; // 编辑按钮
Button btnDeleteTask; Button btnDeleteTask; // 删除按钮
public TaskContentViewHolder(@NonNull View itemView) { public TaskContentViewHolder(@NonNull View itemView) {
super(itemView); super(itemView);
tvTaskDesc = (TextView) itemView.findViewById(R.id.tv_task_desc); // 绑定编辑模式布局控件与XML控件ID严格对应
tvTaskDistance = (TextView) itemView.findViewById(R.id.tv_task_distance); tvTaskDesc = itemView.findViewById(R.id.tv_task_desc);
cbTaskEnable = (CompoundButton) itemView.findViewById(R.id.cb_task_enable); tvTaskDistance = itemView.findViewById(R.id.tv_task_distance);
btnEditTask = (Button) itemView.findViewById(R.id.btn_edit_task); cbTaskEnable = itemView.findViewById(R.id.cb_task_enable);
btnDeleteTask = (Button) itemView.findViewById(R.id.btn_delete_task); btnEditTask = itemView.findViewById(R.id.btn_edit_task);
btnDeleteTask = itemView.findViewById(R.id.btn_delete_task);
} }
} }
} }
// ---------------------- 新增外部调用“新增任务”方法适配MainService ----------------------
/**
* 新增任务对外提供如Activity调用添加任务
* @param newTask 待新增的任务需关联当前位置ID
*/
public void addNewTask(PositionTaskModel newTask) {
if (mMainService == null) {
showToast("新增任务失败:服务未就绪");
LogUtils.e(TAG, "新增任务失败MainService实例为空");
return;
}
if (newTask == null) {
showToast("新增任务失败:任务数据为空");
LogUtils.e(TAG, "新增任务失败:待新增任务对象为空");
return;
}
if (mBindPositionId == null || mBindPositionId.trim().isEmpty()) {
showToast("新增任务失败:未关联位置");
LogUtils.e(TAG, "新增任务失败未绑定位置ID需先调用init()方法)");
return;
}
try {
// 1. 关联任务到当前位置(确保任务属于当前位置)
newTask.setPositionId(mBindPositionId);
// 2. 调用MainService新增任务服务是唯一数据源持久化数据
mMainService.addTask(newTask); // 需在MainService中实现addTask()方法(添加到服务内全量任务列表)
LogUtils.d(TAG, "调用MainService新增任务ID=" + newTask.getTaskId() + "位置ID=" + mBindPositionId + "");
// 3. 重新同步数据(从服务拉取最新列表,避免本地计算错误)
syncTasksFromMainService();
// 4. 通知外部任务已更新
if (mOnTaskUpdatedListener != null) {
mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, getCurrentPosTasks());
}
showToast("新增任务成功(已同步至服务)");
} catch (Exception e) {
LogUtils.d(TAG, "新增任务失败:" + e.getMessage());
showToast("新增失败,请重试");
// 重新同步数据(修复可能的不一致)
syncTasksFromMainService();
}
}
} }