完成主要服务开关与启动
This commit is contained in:
		| @@ -1,8 +1,8 @@ | ||||
| #Created by .winboll/winboll_app_build.gradle | ||||
| #Tue Sep 30 21:17:41 GMT 2025 | ||||
| #Wed Oct 01 07:47:20 GMT 2025 | ||||
| stageCount=4 | ||||
| libraryProject= | ||||
| baseVersion=15.0 | ||||
| publishVersion=15.0.3 | ||||
| buildCount=19 | ||||
| buildCount=55 | ||||
| baseBetaVersion=15.0.4 | ||||
|   | ||||
| @@ -3,6 +3,9 @@ | ||||
|     xmlns:android="http://schemas.android.com/apk/res/android" | ||||
|     package="cc.winboll.studio.positions"> | ||||
|  | ||||
|     <!-- 前台服务权限(可选,提升后台定位稳定性,避免服务被回收) --> | ||||
|     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> | ||||
|  | ||||
|     <!-- 只能在前台获取精确的位置信息 --> | ||||
|     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> | ||||
|  | ||||
| @@ -53,8 +56,11 @@ | ||||
|             android:name="com.google.android.gms.version" | ||||
|             android:value="@integer/google_play_services_version"/> | ||||
|  | ||||
|         <service android:name="cc.winboll.studio.positions.services.DistanceRefreshService"/> | ||||
|         <service android:name=".services.MainService"/> | ||||
|  | ||||
|         <service android:name=".services.AssistantService"/> | ||||
|  | ||||
|         <service android:name=".services.DistanceRefreshService"/> | ||||
|     </application> | ||||
|  | ||||
| </manifest> | ||||
| @@ -4,21 +4,22 @@ import android.content.ComponentName; | ||||
| import android.content.Context; | ||||
| import android.content.Intent; | ||||
| import android.content.ServiceConnection; | ||||
| import android.content.SharedPreferences; | ||||
| import android.content.pm.PackageManager; | ||||
| import android.os.Build; | ||||
| import android.os.Bundle; | ||||
| import android.os.IBinder; | ||||
| import android.view.View; | ||||
| import android.widget.CompoundButton; | ||||
|  | ||||
| import android.widget.Switch; | ||||
| import androidx.appcompat.app.AppCompatActivity; | ||||
| import androidx.appcompat.widget.SwitchCompat; | ||||
| import androidx.appcompat.widget.Toolbar; | ||||
|  | ||||
| import cc.winboll.studio.libappbase.LogActivity; | ||||
| import cc.winboll.studio.libappbase.LogUtils; | ||||
| import cc.winboll.studio.positions.activities.LocationActivity; | ||||
| import cc.winboll.studio.positions.services.DistanceRefreshService; | ||||
| import cc.winboll.studio.positions.services.MainService; | ||||
| import cc.winboll.studio.positions.utils.AppConfigsUtil; | ||||
| import com.hjq.toast.ToastUtils; | ||||
| import cc.winboll.studio.positions.models.AppConfigsModel; | ||||
|  | ||||
| /** | ||||
|  * 主页面:仅负责 | ||||
| @@ -28,9 +29,11 @@ import cc.winboll.studio.positions.models.AppConfigsModel; | ||||
|  */ | ||||
| public class MainActivity extends AppCompatActivity { | ||||
|     public static final String TAG = "MainActivity"; | ||||
|     // 位置权限请求码(自定义唯一标识) | ||||
|     private static final int REQUEST_LOCATION_PERMISSIONS = 1001; | ||||
|  | ||||
| 	// UI 控件:服务控制开关、顶部工具栏 | ||||
|     private SwitchCompat mServiceSwitch; | ||||
|     // UI 控件:服务控制开关、顶部工具栏 | ||||
|     private Switch mServiceSwitch; | ||||
|     private Toolbar mToolbar; | ||||
|     // 服务相关:服务实例、绑定状态标记 | ||||
|     private DistanceRefreshService mDistanceService; | ||||
| @@ -47,8 +50,6 @@ public class MainActivity extends AppCompatActivity { | ||||
|             DistanceRefreshService.DistanceBinder binder = (DistanceRefreshService.DistanceBinder) service; | ||||
|             mDistanceService = binder.getService(); | ||||
|             isServiceBound = true; | ||||
|             // 绑定后立即同步开关状态,避免UI与服务实际状态不一致 | ||||
|             syncSwitchState(); | ||||
|         } | ||||
|  | ||||
|         /** | ||||
| @@ -58,12 +59,10 @@ public class MainActivity extends AppCompatActivity { | ||||
|         public void onServiceDisconnected(ComponentName name) { | ||||
|             mDistanceService = null; | ||||
|             isServiceBound = false; | ||||
|             // 断开后同步开关状态(从SP读取上次保存的状态) | ||||
|             syncSwitchState(); | ||||
|         } | ||||
|     }; | ||||
|  | ||||
|     // ---------------------- Activity 生命周期(核心:初始化UI、绑定服务、释放资源) ---------------------- | ||||
|     // ---------------------- Activity 生命周期(核心:初始化UI、申请权限、绑定服务、释放资源) ---------------------- | ||||
|     @Override | ||||
|     protected void onCreate(Bundle savedInstanceState) { | ||||
|         super.onCreate(savedInstanceState); | ||||
| @@ -71,9 +70,13 @@ public class MainActivity extends AppCompatActivity { | ||||
|  | ||||
|         // 1. 初始化顶部 Toolbar(保留原逻辑,设置页面标题) | ||||
|         initToolbar(); | ||||
|         // 2. 初始化服务控制开关(核心功能:绑定开关点击事件、读取SP状态) | ||||
|         // 2. 初始化服务控制开关(核心功能:绑定开关点击事件) | ||||
|         initServiceSwitch(); | ||||
|         // 3. 绑定服务(仅用于获取服务实时状态,不影响服务独立运行) | ||||
|         // 3. 检查并申请位置权限(含后台GPS权限,确保服务启动前权限就绪) | ||||
|         if (!checkLocationPermissions()) { | ||||
|             requestLocationPermissions(); | ||||
|         } | ||||
|         // 4. 绑定服务(仅用于获取服务实时状态,不影响服务独立运行) | ||||
|         bindDistanceService(); | ||||
|     } | ||||
|  | ||||
| @@ -102,57 +105,49 @@ public class MainActivity extends AppCompatActivity { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 初始化服务控制开关:读取SP状态、绑定点击事件 | ||||
|      * 初始化服务控制开关:读取SP状态、绑定点击事件(含权限检查) | ||||
|      */ | ||||
|     private void initServiceSwitch() { | ||||
|         mServiceSwitch = (SwitchCompat) findViewById(R.id.switch_service_control); // 显式强转 | ||||
|         mServiceSwitch = (Switch) findViewById(R.id.switch_service_control); // 显式强转 | ||||
| 		mServiceSwitch.setChecked(AppConfigsUtil.getInstance(this).isEnableMainService(true)); | ||||
|  | ||||
|         // 2. 绑定开关状态变化监听(Java 7 用匿名内部类实现 CompoundButton.OnCheckedChangeListener) | ||||
|         // Java 7 用匿名内部类实现 CompoundButton.OnCheckedChangeListener | ||||
|         mServiceSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { | ||||
| 				@Override | ||||
| 				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { | ||||
| 					if (isChecked) { | ||||
| 						AppConfigsModel.saveBean(MainActivity.this, new AppConfigsModel(true)); | ||||
| 						// 开关打开:启动服务(通过startService确保服务独立运行,不受Activity绑定影响) | ||||
| 						startService(new Intent(MainActivity.this, DistanceRefreshService.class)); | ||||
| 					// 开关打开前先检查权限:无权限则终止操作、重置开关、引导申请 | ||||
| 					if (isChecked && !checkLocationPermissions()) { | ||||
| 						requestLocationPermissions(); | ||||
| 						return; | ||||
| 					} | ||||
|  | ||||
| 					// 权限就绪:执行服务启停逻辑 | ||||
| 					if (isChecked) { | ||||
| 						LogUtils.d(TAG, "设置启动服务"); | ||||
| 						AppConfigsUtil.getInstance(MainActivity.this).setIsEnableMainService(true); | ||||
| 						// 启动服务(startService确保服务独立运行,不受Activity绑定影响) | ||||
| 						startService(new Intent(MainActivity.this, MainService.class)); | ||||
| 					} else { | ||||
| 						AppConfigsModel.saveBean(MainActivity.this, new AppConfigsModel(false)); | ||||
| 						// 开关关闭:先解绑服务(避免服务被Activity持有),再停止服务 | ||||
| 						LogUtils.d(TAG, "设置关闭服务"); | ||||
| 						AppConfigsUtil.getInstance(MainActivity.this).setIsEnableMainService(false); | ||||
| 						// 停止服务前先解绑,避免服务被Activity持有 | ||||
| 						if (isServiceBound) { | ||||
| 							unbindService(mServiceConn); | ||||
| 							isServiceBound = false; | ||||
| 						} | ||||
| 						stopService(new Intent(MainActivity.this, DistanceRefreshService.class)); | ||||
| 						stopService(new Intent(MainActivity.this, MainService.class)); | ||||
| 					} | ||||
| 					// 状态变化后同步开关UI(确保UI与服务实际状态一致) | ||||
| 					syncSwitchState(); | ||||
| 				} | ||||
| 			}); | ||||
|     } | ||||
|  | ||||
|     // ---------------------- 核心功能2:服务状态同步与绑定 ---------------------- | ||||
|     /** | ||||
|      * 同步服务开关状态:优先以服务实时状态为准,无服务则读SP | ||||
|      */ | ||||
|     private void syncSwitchState() { | ||||
|         if (mServiceSwitch == null) { | ||||
|             return; // 开关未初始化,直接返回 | ||||
|         } | ||||
|  | ||||
|         if (isServiceBound && mDistanceService != null) { | ||||
|             ToastUtils.show("位置服务已启动"); | ||||
|         } else { | ||||
|             ToastUtils.show("位置服务已关闭"); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 绑定服务(仅用于获取服务状态,不启动服务) | ||||
|      */ | ||||
|     private void bindDistanceService() { | ||||
|         Intent serviceIntent = new Intent(this, DistanceRefreshService.class); | ||||
|         // 绑定服务:BIND_AUTO_CREATE 表示若服务未启动则创建(仅为获取状态,后续由开关控制启停) | ||||
|         Intent serviceIntent = new Intent(this, MainService.class); | ||||
|         // BIND_AUTO_CREATE:服务未启动则创建(仅为获取状态,启停由开关控制) | ||||
|         bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); | ||||
|     } | ||||
|  | ||||
| @@ -162,15 +157,7 @@ public class MainActivity extends AppCompatActivity { | ||||
|      * 服务未启动时提示,不允许跳转(避免LocationActivity无数据) | ||||
|      */ | ||||
|     public void onPositions(View view) { | ||||
|         // 从配置文件读取服务状态(避免依赖服务绑定,提升稳定性) | ||||
| 		AppConfigsModel bean = AppConfigsModel.loadBean(MainActivity.this, AppConfigsModel.class); | ||||
|         boolean isServiceRunning = (bean == null) ? false : bean.isEnableDistanceRefreshService(); | ||||
|  | ||||
|         if (!isServiceRunning) { | ||||
|             ToastUtils.show("请先启动位置服务,否则无法加载数据"); | ||||
|             return; // 服务未启动,不跳转 | ||||
|         } | ||||
|  | ||||
| 		//ToastUtils.show("onPositions"); | ||||
|         // 服务已启动:跳转到位置管理页 | ||||
|         startActivity(new Intent(MainActivity.this, LocationActivity.class)); | ||||
|     } | ||||
| @@ -182,5 +169,71 @@ public class MainActivity extends AppCompatActivity { | ||||
|     public void onLog(View view) { | ||||
|         LogActivity.startLogActivity(this); // 调用LogActivity静态方法跳转(保留原逻辑) | ||||
|     } | ||||
|  | ||||
|     // ---------------------- 新增:位置权限处理(适配Java7 + 后台GPS权限) ---------------------- | ||||
|     /** | ||||
|      * 检查是否拥有「前台+后台」位置权限(适配Android版本差异) | ||||
|      * Java7 特性:显式类型判断、无Lambda、兼容低版本API | ||||
|      */ | ||||
|     private boolean checkLocationPermissions() { | ||||
|         // 1. 检查前台精确定位权限(Android 6.0+ 必需,显式强转权限常量) | ||||
|         int foregroundPermResult = checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION); | ||||
|         boolean hasForegroundPerm = (foregroundPermResult == PackageManager.PERMISSION_GRANTED); | ||||
|  | ||||
|         // 2. 检查后台定位权限(仅Android 10+ 需要,Java7 显式用Build.VERSION判断版本) | ||||
|         boolean hasBackgroundPerm = true; | ||||
|         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { | ||||
|             int backgroundPermResult = checkSelfPermission(android.Manifest.permission.ACCESS_BACKGROUND_LOCATION); | ||||
|             hasBackgroundPerm = (backgroundPermResult == PackageManager.PERMISSION_GRANTED); | ||||
|         } | ||||
|  | ||||
|         // 前台+后台权限均满足,才返回true | ||||
|         return hasForegroundPerm && hasBackgroundPerm; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 申请「前台+后台」位置权限(弹出系统权限弹窗,适配版本差异) | ||||
|      */ | ||||
|     private void requestLocationPermissions() { | ||||
|         String[] permissions; | ||||
|         // Java7 显式版本判断:Android 10+ 需同时申请前台+后台权限 | ||||
|         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { | ||||
|             permissions = new String[]{ | ||||
| 				android.Manifest.permission.ACCESS_FINE_LOCATION, | ||||
| 				android.Manifest.permission.ACCESS_BACKGROUND_LOCATION | ||||
|             }; | ||||
|         } else { | ||||
|             // 低版本仅需申请前台权限 | ||||
|             permissions = new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}; | ||||
|         } | ||||
|         // 触发系统权限申请(Java7 显式调用requestPermissions,无方法引用) | ||||
|         requestPermissions(permissions, REQUEST_LOCATION_PERMISSIONS); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 处理权限申请结果(系统弹窗用户选择后回调,Java7 显式重写方法) | ||||
|      */ | ||||
|     @Override | ||||
|     public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { | ||||
|         super.onRequestPermissionsResult(requestCode, permissions, grantResults); | ||||
|         // 仅处理位置权限的申请结果 | ||||
|         if (requestCode == REQUEST_LOCATION_PERMISSIONS) { | ||||
|             boolean allGranted = true; | ||||
|             // Java7 显式for循环遍历结果(无增强for简化写法) | ||||
|             for (int i = 0; i < grantResults.length; i++) { | ||||
|                 if (grantResults[i] != PackageManager.PERMISSION_GRANTED) { | ||||
|                     allGranted = false; | ||||
|                     break; // 有一个权限未通过,直接终止判断 | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             // 提示用户权限结果,并处理开关状态 | ||||
|             if (allGranted) { | ||||
|                 ToastUtils.show("已获取位置权限(含后台),可正常使用定位功能"); | ||||
|             } else { | ||||
|                 ToastUtils.show("位置权限未完全授予,无法后台获取GPS数据,请在设置中开启"); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -3,15 +3,11 @@ package cc.winboll.studio.positions.activities; | ||||
| /** | ||||
|  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> | ||||
|  * @Date 2025/09/29 18:22 | ||||
|  * @Describe 位置列表页面(Java 7 兼容,完全依赖DistanceRefreshService数据) | ||||
|  * @Describe 位置列表页面(直连服务数据+移除绑定,兼容服务私有字段) | ||||
|  */ | ||||
| import android.content.ComponentName; | ||||
| import android.content.Context; | ||||
| import android.content.Intent; | ||||
| import android.content.ServiceConnection; | ||||
| import android.content.SharedPreferences; | ||||
| import android.os.Bundle; | ||||
| import android.os.IBinder; | ||||
| import android.view.View; | ||||
| import android.view.inputmethod.InputMethodManager; | ||||
| import android.widget.Toast; | ||||
| @@ -24,230 +20,347 @@ import cc.winboll.studio.libappbase.LogUtils; | ||||
| import cc.winboll.studio.positions.R; | ||||
| import cc.winboll.studio.positions.adapters.PositionAdapter; | ||||
| import cc.winboll.studio.positions.models.PositionModel; | ||||
| import cc.winboll.studio.positions.models.PositionTaskModel; | ||||
| import cc.winboll.studio.positions.services.DistanceRefreshService; | ||||
|  | ||||
| import java.util.ArrayList; | ||||
|  | ||||
| /** | ||||
|  * 核心逻辑: | ||||
|  * 1. 启动前检查服务状态,未运行则拦截并提示 | ||||
|  * 2. 绑定服务后通过接口获取数据,不本地存储数据 | ||||
|  * 3. Adapter初始化仅传上下文+服务实例,数据从服务实时获取 | ||||
|  * 4. 严格Java 7语法:显式类型转换、匿名内部类、无Lambda | ||||
|  * 核心调整说明: | ||||
|  * 1. 移除服务绑定逻辑,但不直接访问服务私有字段(解决mPositionList未知问题) | ||||
|  * 2. 通过服务提供的 PUBLIC 方法(如getPositionList、addPosition)操作数据,符合封装规范 | ||||
|  * 3. 保留“直连服务实例”的核心需求,避免绑定,但尊重服务数据私有性 | ||||
|  * 4. 兼容Java 7语法,无Lambda、显式类型转换 | ||||
|  */ | ||||
| public class LocationActivity extends AppCompatActivity { | ||||
|     public static final String TAG = "LocationActivity"; | ||||
| 	 | ||||
| 	// SP配置常量(与服务保持一致,用于判断服务状态) | ||||
| 	// SP配置常量(判断服务是否运行) | ||||
|     private static final String SP_SERVICE_CONFIG = "service_config"; | ||||
|     private static final String KEY_SERVICE_RUNNING = "is_service_running"; | ||||
|     // 页面核心控件与变量 | ||||
|     private RecyclerView mRecyclerView; | ||||
|     private PositionAdapter mAdapter; | ||||
|     private DistanceRefreshService mDistanceService; // 服务实例(已实现DistanceServiceInterface) | ||||
|     private boolean isServiceBound = false; // 服务绑定状态标记 | ||||
|     // 直连服务实例(替代绑定,通过单例/全局初始化获取) | ||||
|     private DistanceRefreshService mDistanceService;  | ||||
|     // 缓存服务数据(从服务PUBLIC方法获取,避免重复调用) | ||||
|     private ArrayList<PositionModel> mCachedPositionList;  | ||||
|     private ArrayList<PositionTaskModel> mCachedTaskList; | ||||
|  | ||||
|     // ---------------------- 服务连接(Java 7 匿名内部类实现) ---------------------- | ||||
|     private final ServiceConnection mServiceConn = new ServiceConnection() { | ||||
|         @Override | ||||
|         public void onServiceConnected(ComponentName name, IBinder service) { | ||||
|             // 显式类型转换(Java 7 不支持自动推断,必须强转) | ||||
|             DistanceRefreshService.DistanceBinder binder = (DistanceRefreshService.DistanceBinder) service; | ||||
|             mDistanceService = binder.getService(); | ||||
|             isServiceBound = true; | ||||
|             LogUtils.d("LocationActivity", "服务绑定成功,开始初始化Adapter"); | ||||
|             // 绑定成功后初始化Adapter(仅传上下文+服务实例) | ||||
|             initAdapter(); | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public void onServiceDisconnected(ComponentName name) { | ||||
|             // 服务意外断开:置空引用+更新状态,避免空指针 | ||||
|             mDistanceService = null; | ||||
|             isServiceBound = false; | ||||
|             LogUtils.w("LocationActivity", "服务意外断开连接(可能被系统回收)"); | ||||
|             Toast.makeText(LocationActivity.this, "服务已断开,请重新进入页面", Toast.LENGTH_SHORT).show(); | ||||
|         } | ||||
|     }; | ||||
|  | ||||
|     // ---------------------- 页面生命周期(严格管理服务绑定/资源) ---------------------- | ||||
|     // ---------------------- 页面生命周期(简化资源管理,无服务绑定) ---------------------- | ||||
|     @Override | ||||
|     protected void onCreate(Bundle savedInstanceState) { | ||||
|         super.onCreate(savedInstanceState); | ||||
|         setContentView(R.layout.activity_location); | ||||
|  | ||||
|         // 1. 优先检查服务状态:未运行则提示并关闭页面 | ||||
|         checkServiceRunningStatus(); | ||||
|         // 2. 初始化RecyclerView(基础配置+性能优化) | ||||
|         // 1. 初始化服务实例(通过单例/全局方式,避免直接new导致数据重置) | ||||
|         initServiceInstance(); | ||||
|         // 2. 检查服务状态(未运行/未初始化则提示关闭) | ||||
|         //checkServiceStatus(); | ||||
|         // 3. 初始化RecyclerView(布局+性能优化) | ||||
|         initRecyclerViewConfig(); | ||||
|         // 3. 绑定服务(获取数据的唯一入口,自动创建服务) | ||||
|         bindDistanceService(); | ||||
|         // 4. 缓存服务数据(从服务PUBLIC方法获取,不访问私有字段) | ||||
|         cacheServiceData(); | ||||
|         // 5. 初始化Adapter(传缓存数据,而非直接访问服务私有字段) | ||||
|         initAdapter(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     protected void onDestroy() { | ||||
|         super.onDestroy(); | ||||
|         // 1. 解绑服务(仅绑定状态下执行,避免异常) | ||||
|         if (isServiceBound) { | ||||
|             unbindService(mServiceConn); | ||||
|             isServiceBound = false; | ||||
|             mDistanceService = null; // 置空引用,帮助GC回收 | ||||
|             LogUtils.d("LocationActivity", "服务已解绑,避免内存泄漏"); | ||||
|         } | ||||
|         // 2. 清理Adapter资源(调用Adapter内部销毁方法) | ||||
|         // 1. 清理Adapter资源 | ||||
|         if (mAdapter != null) { | ||||
|             mAdapter.release(); | ||||
|             mAdapter = null; | ||||
|         } | ||||
|         // 3. 清理RecyclerView引用 | ||||
|         // 2. 置空服务实例+缓存数据(帮助GC回收) | ||||
|         mDistanceService = null; | ||||
|         mCachedPositionList = null; | ||||
|         mCachedTaskList = null; | ||||
|         mRecyclerView = null; | ||||
|         LogUtils.d(TAG, "页面销毁:已清理服务实例及缓存数据"); | ||||
|     } | ||||
|  | ||||
|     // ---------------------- 核心初始化方法(服务状态检查+RecyclerView+Adapter) ---------------------- | ||||
|     // ---------------------- 核心初始化(服务实例+数据缓存+状态检查) ---------------------- | ||||
|     /** | ||||
|      * 检查服务运行状态(从SP读取,与服务状态保持一致) | ||||
|      * 初始化服务实例(关键:通过单例获取,确保全局唯一,避免数据重复) | ||||
|      * 注:需在DistanceRefreshService中实现单例(getInstance()方法) | ||||
|      */ | ||||
|     private void checkServiceRunningStatus() { | ||||
|         // Java 7 显式获取SP实例(不使用方法链简化) | ||||
|         SharedPreferences sp = getSharedPreferences(SP_SERVICE_CONFIG, Context.MODE_PRIVATE); | ||||
|         // 读取服务状态:默认未运行(false) | ||||
|         boolean isServiceRunning = sp.getBoolean(KEY_SERVICE_RUNNING, false); | ||||
|     private void initServiceInstance() { | ||||
| 		// 步骤1:先启动Service(确保Service已创建,实例能被初始化) | ||||
|          | ||||
|         if (!isServiceRunning) { | ||||
|             // 服务未运行:提示用户并关闭页面 | ||||
|             Toast.makeText(this, "请先启动位置服务,否则无法加载数据", Toast.LENGTH_SHORT).show(); | ||||
|             finish(); // 关闭当前页面,返回上一级 | ||||
|  | ||||
|         // 步骤2:初始化Service实例(延迟100-200ms,确保Service onCreate执行完成) | ||||
|         // (或在startService后,通过ServiceConnection绑定获取实例,更可靠) | ||||
|         initServiceInstance(); | ||||
| 		 | ||||
|         // 方式:通过服务PUBLIC单例方法获取实例(不直接new,避免私有数据初始化重复) | ||||
|         mDistanceService = DistanceRefreshService.getInstance(); | ||||
|          | ||||
|         // 容错:若单例未初始化(如首次启动),提示并处理 | ||||
|         if (mDistanceService == null) { | ||||
|             LogUtils.e(TAG, "服务实例初始化失败:单例未创建"); | ||||
|             Toast.makeText(this, "位置服务初始化失败,请重启应用", Toast.LENGTH_SHORT).show(); | ||||
|             finish(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 初始化RecyclerView(布局管理器+性能优化) | ||||
|      * 检查服务状态(替代原绑定检查,通过服务PUBLIC方法判断) | ||||
|      */ | ||||
|     private void initRecyclerViewConfig() { | ||||
|         // 显式 findViewById + 类型转换(Java 7 必须强转) | ||||
|         mRecyclerView = (RecyclerView) findViewById(R.id.rv_position_list); | ||||
|         // 初始化线性布局管理器(垂直方向,默认) | ||||
|         LinearLayoutManager layoutManager = new LinearLayoutManager(this); | ||||
|         layoutManager.setOrientation(LinearLayoutManager.VERTICAL); | ||||
|         mRecyclerView.setLayoutManager(layoutManager); | ||||
|         // 固定列表大小(优化性能:避免列表项变化时重复测量RecyclerView) | ||||
|         mRecyclerView.setHasFixedSize(true); | ||||
|     private void checkServiceStatus() { | ||||
|         // 1. 服务实例未初始化 | ||||
|         if (mDistanceService == null) { | ||||
|             return; // 已在initServiceInstance中处理,此处避免重复finish | ||||
|         } | ||||
|  | ||||
|         // 2. 检查服务运行状态(通过服务PUBLIC方法isServiceRunning()获取,不访问私有字段) | ||||
|         if (!mDistanceService.isServiceRunning()) { | ||||
|             // 服务未运行:手动触发启动(调用服务PUBLIC方法run()) | ||||
|             mDistanceService.run(); | ||||
|             LogUtils.d(TAG, "服务未运行,已通过PUBLIC方法触发启动"); | ||||
|         } | ||||
|  | ||||
|         // 3. 检查SP中服务配置(双重校验,确保一致性) | ||||
|         SharedPreferences sp = getSharedPreferences(SP_SERVICE_CONFIG, Context.MODE_PRIVATE); | ||||
|         boolean isServiceConfigRunning = sp.getBoolean(KEY_SERVICE_RUNNING, false); | ||||
|         if (!isServiceConfigRunning) { | ||||
|             Toast.makeText(this, "位置服务配置未启用,数据可能无法更新", Toast.LENGTH_SHORT).show(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 初始化Adapter(核心:仅传上下文+服务实例,数据从服务获取) | ||||
|      * 缓存服务数据(从服务PUBLIC方法获取,解决私有字段未知问题) | ||||
|      */ | ||||
|     private void initAdapter() { | ||||
|         // 前置校验:服务未绑定/服务实例为空,直接返回 | ||||
|         if (!isServiceBound || mDistanceService == null) { | ||||
|             LogUtils.e("LocationActivity", "初始化Adapter失败:服务未绑定或实例为空"); | ||||
|     private void cacheServiceData() { | ||||
|         if (mDistanceService == null) { | ||||
|             LogUtils.e(TAG, "缓存数据失败:服务实例为空"); | ||||
|             mCachedPositionList = new ArrayList<PositionModel>(); | ||||
|             mCachedTaskList = new ArrayList<PositionTaskModel>(); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         // 1. 初始化Adapter(参数匹配:Context + DistanceServiceInterface) | ||||
|         mAdapter = new PositionAdapter(this, mDistanceService); | ||||
|         // 从服务PUBLIC方法获取数据(不访问mPositionList,而是调用getPositionList()) | ||||
|         mCachedPositionList = mDistanceService.getPositionList(); | ||||
|         mCachedTaskList = mDistanceService.getPositionTasksList(); | ||||
|          | ||||
|         // 容错:若服务返回null,初始化空列表避免空指针 | ||||
|         if (mCachedPositionList == null) mCachedPositionList = new ArrayList<PositionModel>(); | ||||
|         if (mCachedTaskList == null) mCachedTaskList = new ArrayList<PositionTaskModel>(); | ||||
|          | ||||
|         LogUtils.d(TAG, "缓存服务数据成功:位置数=" + mCachedPositionList.size() + ",任务数=" + mCachedTaskList.size()); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 初始化RecyclerView(保留原性能优化) | ||||
|      */ | ||||
|     private void initRecyclerViewConfig() { | ||||
|         mRecyclerView = (RecyclerView) findViewById(R.id.rv_position_list); | ||||
|         LinearLayoutManager layoutManager = new LinearLayoutManager(this); | ||||
|         layoutManager.setOrientation(LinearLayoutManager.VERTICAL); | ||||
|         mRecyclerView.setLayoutManager(layoutManager); | ||||
|         mRecyclerView.setHasFixedSize(true); // 固定大小,优化绘制 | ||||
|     } | ||||
|  | ||||
|     // ---------------------- Adapter初始化与数据交互(全通过服务PUBLIC方法) ---------------------- | ||||
|     /** | ||||
|      * 初始化Adapter(通过缓存数据初始化,数据更新时同步调用服务方法) | ||||
|      */ | ||||
|     private void initAdapter() { | ||||
|         if (mCachedPositionList == null || mCachedTaskList == null) { | ||||
|             LogUtils.e(TAG, "初始化Adapter失败:缓存数据为空"); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         // 1. 初始化Adapter(传缓存数据+服务实例,Adapter数据从缓存取,操作通过服务) | ||||
|         mAdapter = new PositionAdapter(this, mCachedPositionList, mCachedTaskList); | ||||
|         mRecyclerView.setAdapter(mAdapter); | ||||
|  | ||||
|         // 2. 设置删除回调(通过服务执行删除,Adapter自动同步数据) | ||||
|         // 2. 删除回调:通过服务PUBLIC方法removePosition()删除,不直接操作私有字段 | ||||
|         mAdapter.setOnDeleteClickListener(new PositionAdapter.OnDeleteClickListener() { | ||||
| 				@Override | ||||
| 				public void onDeleteClick(int position) { | ||||
| 					// 多重校验:服务状态+索引有效性 | ||||
| 					if (isServiceBound && mDistanceService != null) { | ||||
| 						ArrayList<PositionModel> latestPosList = mDistanceService.getPositionList(); | ||||
| 						if (position >= 0 && position < latestPosList.size()) { | ||||
| 							// 获取要删除的位置ID(从服务最新列表中取,避免本地数据过期) | ||||
| 							PositionModel targetPos = latestPosList.get(position); | ||||
| 							String posId = targetPos.getPositionId(); | ||||
| 							// 调用服务删除方法(服务内部处理“删除位置+关联任务+清理可见位置”) | ||||
| 							mDistanceService.removePosition(posId); | ||||
| 							// 刷新Adapter(从服务获取最新列表,确保数据一致) | ||||
| 							mAdapter.updateAllPositions(mDistanceService.getPositionList()); | ||||
| 							Toast.makeText(LocationActivity.this, "位置已删除(含关联任务)", Toast.LENGTH_SHORT).show(); | ||||
| 						} else { | ||||
| 							LogUtils.w("LocationActivity", "删除失败:位置索引无效(" + position + ")"); | ||||
| 						} | ||||
| 					} else { | ||||
| 						Toast.makeText(LocationActivity.this, "删除失败:服务未绑定", Toast.LENGTH_SHORT).show(); | ||||
| 					} | ||||
| 				} | ||||
| 			}); | ||||
|             @Override | ||||
|             public void onDeleteClick(int position) { | ||||
|                 // 校验:服务实例有效+索引合法 | ||||
|                 if (mDistanceService == null || mCachedPositionList == null) { | ||||
|                     Toast.makeText(LocationActivity.this, "删除失败:服务未就绪", Toast.LENGTH_SHORT).show(); | ||||
|                     return; | ||||
|                 } | ||||
|                 if (position < 0 || position >= mCachedPositionList.size()) { | ||||
|                     LogUtils.w(TAG, "删除失败:索引无效(" + position + ")"); | ||||
|                     Toast.makeText(LocationActivity.this, "删除失败:数据位置异常", Toast.LENGTH_SHORT).show(); | ||||
|                     return; | ||||
|                 } | ||||
|  | ||||
|         // 3. 设置位置保存回调(保存逻辑由服务处理,此处仅提示) | ||||
|                 // 1. 获取要删除的位置(从缓存取,与服务数据一致) | ||||
|                 PositionModel targetPos = mCachedPositionList.get(position); | ||||
|                 String targetPosId = targetPos.getPositionId(); | ||||
|  | ||||
|                 // 2. 调用服务PUBLIC方法删除(服务内部处理mPositionList/mTaskList,符合封装) | ||||
|                 mDistanceService.removePosition(targetPosId); | ||||
|                 LogUtils.d(TAG, "通过服务删除位置:ID=" + targetPosId); | ||||
|  | ||||
|                 // 3. 刷新缓存+Adapter(从服务重新获取数据,确保与服务一致) | ||||
|                 refreshCachedDataAndAdapter(); | ||||
|                 Toast.makeText(LocationActivity.this, "位置已删除(含关联任务)", Toast.LENGTH_SHORT).show(); | ||||
|             } | ||||
|         }); | ||||
|  | ||||
|         // 3. 位置保存回调:通过服务PUBLIC方法updatePosition()更新 | ||||
|         mAdapter.setOnSavePositionClickListener(new PositionAdapter.OnSavePositionClickListener() { | ||||
| 				@Override | ||||
| 				public void onSavePositionClick() { | ||||
| 					Toast.makeText(LocationActivity.this, "位置信息已保存(备注/距离开关)", Toast.LENGTH_SHORT).show(); | ||||
| 				} | ||||
| 			}); | ||||
|             @Override | ||||
|             public void onSavePositionClick(int position, PositionModel updatedPos) { | ||||
|                 // 校验:服务+数据+参数有效 | ||||
|                 if (mDistanceService == null || mCachedPositionList == null || updatedPos == null) { | ||||
|                     Toast.makeText(LocationActivity.this, "保存失败:服务或数据异常", Toast.LENGTH_SHORT).show(); | ||||
|                     return; | ||||
|                 } | ||||
|                 if (position < 0 || position >= mCachedPositionList.size()) { | ||||
|                     LogUtils.w(TAG, "保存失败:位置索引无效"); | ||||
|                     return; | ||||
|                 } | ||||
|  | ||||
|         // 4. 设置任务保存回调(同理,保存逻辑由服务处理) | ||||
|                 // 1. 调用服务PUBLIC方法更新数据(服务内部修改mPositionList) | ||||
|                 mDistanceService.updatePosition(updatedPos); | ||||
|                 LogUtils.d(TAG, "通过服务保存位置:ID=" + updatedPos.getPositionId()); | ||||
|  | ||||
|                 // 2. 刷新缓存+Adapter(确保本地显示与服务一致) | ||||
|                 refreshCachedDataAndAdapter(); | ||||
|                 Toast.makeText(LocationActivity.this, "位置信息已保存", Toast.LENGTH_SHORT).show(); | ||||
|             } | ||||
|         }); | ||||
|  | ||||
|         // 4. 任务保存回调:通过服务PUBLIC方法syncAllPositionTasks()同步 | ||||
|         mAdapter.setOnSavePositionTaskClickListener(new PositionAdapter.OnSavePositionTaskClickListener() { | ||||
| 				@Override | ||||
| 				public void onSavePositionTaskClick() { | ||||
| 					Toast.makeText(LocationActivity.this, "任务信息已保存(新增/修改/删除)", Toast.LENGTH_SHORT).show(); | ||||
| 				} | ||||
| 			}); | ||||
|             @Override | ||||
|             public void onSavePositionTaskClick(PositionTaskModel newTask) { | ||||
|                 if (mDistanceService == null || newTask == null) { | ||||
|                     Toast.makeText(LocationActivity.this, "保存失败:服务或任务数据为空", Toast.LENGTH_SHORT).show(); | ||||
|                     return; | ||||
|                 } | ||||
|  | ||||
|                 // 1. 构建新任务列表(缓存任务+新任务,去重) | ||||
|                 ArrayList<PositionTaskModel> newTaskList = new ArrayList<PositionTaskModel>(mCachedTaskList); | ||||
|                 // 先移除同ID旧任务(避免重复) | ||||
|                 for (int i = 0; i < newTaskList.size(); i++) { | ||||
|                     PositionTaskModel oldTask = newTaskList.get(i); | ||||
|                     if (newTask.getTaskId().equals(oldTask.getTaskId())) { | ||||
|                         newTaskList.remove(i); | ||||
|                         break; | ||||
|                     } | ||||
|                 } | ||||
|                 // 添加新任务 | ||||
|                 newTaskList.add(newTask); | ||||
|  | ||||
|                 // 2. 调用服务PUBLIC方法同步任务(服务内部更新mTaskList) | ||||
|                 mDistanceService.syncAllPositionTasks(newTaskList); | ||||
|                 LogUtils.d(TAG, "通过服务保存任务:ID=" + newTask.getTaskId()); | ||||
|  | ||||
|                 // 3. 刷新缓存+Adapter | ||||
|                 refreshCachedDataAndAdapter(); | ||||
|                 Toast.makeText(LocationActivity.this, "任务信息已保存", Toast.LENGTH_SHORT).show(); | ||||
|             } | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     // ---------------------- 服务绑定/数据同步方法 ---------------------- | ||||
|     // ---------------------- 页面交互(新增位置、同步GPS,全走服务PUBLIC方法) ---------------------- | ||||
|     /** | ||||
|      * 绑定DistanceRefreshService(自动创建服务,获取数据入口) | ||||
|      */ | ||||
|     private void bindDistanceService() { | ||||
|         // Java 7 显式创建Intent(不使用方法链) | ||||
|         Intent serviceIntent = new Intent(this, DistanceRefreshService.class); | ||||
|         // 绑定服务:Context.BIND_AUTO_CREATE 表示“服务未启动则自动创建” | ||||
|         bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 同步GPS位置到服务(供外部定位模块调用,如GPS回调) | ||||
|      */ | ||||
|     public void syncGpsPositionToService(PositionModel gpsModel) { | ||||
|         // 校验:服务绑定+GPS模型有效 | ||||
|         if (isServiceBound && mDistanceService != null && gpsModel != null) { | ||||
|             mDistanceService.syncCurrentGpsPosition(gpsModel); | ||||
|             // 可选:GPS更新后强制刷新一次距离(避免等待定时周期) | ||||
|             mDistanceService.forceRefreshDistance(); | ||||
|             LogUtils.d("LocationActivity", "GPS位置已同步到服务,并触发即时距离计算"); | ||||
|         } else { | ||||
|             LogUtils.w("LocationActivity", "同步GPS失败:服务未绑定或GPS模型无效"); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     // ---------------------- 页面交互方法(新增位置按钮点击事件) ---------------------- | ||||
|     /** | ||||
|      * 新增位置(绑定到布局中“新增按钮”的 android:onClick="addNewPosition") | ||||
|      * 新增位置(调用服务addPosition(),不直接操作mPositionList) | ||||
|      */ | ||||
|     public void addNewPosition(View view) { | ||||
|         // 1. 隐藏软键盘(避免新增时残留输入框焦点) | ||||
|         // 1. 隐藏软键盘 | ||||
|         InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); | ||||
|         if (imm != null && getCurrentFocus() != null) { | ||||
|             imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); | ||||
|         } | ||||
|  | ||||
|         // 2. 校验服务状态(未绑定则提示) | ||||
|         if (!isServiceBound || mDistanceService == null) { | ||||
|             Toast.makeText(this, "新增失败:服务未绑定", Toast.LENGTH_SHORT).show(); | ||||
|         // 2. 校验服务状态 | ||||
|         if (mDistanceService == null) { | ||||
|             Toast.makeText(this, "新增失败:服务未初始化", Toast.LENGTH_SHORT).show(); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         // 3. 创建示例位置模型(实际项目需替换为“用户输入经纬度/备注”) | ||||
|         // 3. 创建新位置模型 | ||||
|         PositionModel newPos = new PositionModel(); | ||||
|         newPos.setPositionId(PositionModel.genPositionId()); // 静态方法生成唯一ID(需在PositionModel中实现) | ||||
|         newPos.setPositionId(PositionModel.genPositionId()); // 生成唯一ID(PositionModel需实现) | ||||
|         newPos.setLongitude(116.404267); // 示例经度(北京) | ||||
|         newPos.setLatitude(39.915119);  // 示例纬度 | ||||
|         newPos.setMemo("测试位置(可编辑备注)"); // 示例备注 | ||||
|         newPos.setIsSimpleView(true);   // 默认显示“简单视图”(非编辑模式) | ||||
|         newPos.setIsEnableRealPositionDistance(true); // 默认启用距离计算 | ||||
|         newPos.setMemo("测试位置(可编辑备注)"); | ||||
|         newPos.setIsSimpleView(true);   // 默认简单视图 | ||||
|         newPos.setIsEnableRealPositionDistance(true); // 启用距离计算 | ||||
|  | ||||
|         // 4. 调用服务新增位置(服务内部去重+数据管理) | ||||
|         // 4. 调用服务PUBLIC方法新增(服务内部处理mPositionList去重+添加) | ||||
|         mDistanceService.addPosition(newPos); | ||||
|         // 5. 刷新Adapter(从服务获取最新列表,显示新增位置) | ||||
|         mAdapter.updateAllPositions(mDistanceService.getPositionList()); | ||||
|         Toast.makeText(this, "新增位置成功(默认启用距离计算)", Toast.LENGTH_SHORT).show(); | ||||
|         LogUtils.d("LocationActivity", "新增位置:ID=" + newPos.getPositionId() + ",备注=" + newPos.getMemo()); | ||||
|         LogUtils.d(TAG, "通过服务新增位置:ID=" + newPos.getPositionId()); | ||||
|  | ||||
|         // 5. 刷新缓存+Adapter(显示新增结果) | ||||
|         refreshCachedDataAndAdapter(); | ||||
|         Toast.makeText(this, "新增位置成功(已启用距离计算)", Toast.LENGTH_SHORT).show(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 同步GPS位置到服务(调用服务syncCurrentGpsPosition(),不访问私有字段) | ||||
|      */ | ||||
|     public void syncGpsPositionToService(PositionModel gpsModel) { | ||||
|         if (mDistanceService == null || gpsModel == null) { | ||||
|             LogUtils.w(TAG, "同步GPS失败:服务未就绪或GPS数据无效"); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         // 调用服务PUBLIC方法同步GPS(服务内部更新mCurrentGpsPosition) | ||||
|         mDistanceService.syncCurrentGpsPosition(gpsModel); | ||||
|         // 强制刷新距离(通过服务PUBLIC方法,触发mPositionList距离计算) | ||||
|         mDistanceService.forceRefreshDistance(); | ||||
|         LogUtils.d(TAG, "GPS位置已同步,通过服务触发距离计算"); | ||||
|  | ||||
|         // 刷新缓存+Adapter(显示最新距离) | ||||
|         refreshCachedDataAndAdapter(); | ||||
|     } | ||||
|  | ||||
|     // ---------------------- 辅助方法(统一刷新缓存与Adapter,确保数据一致) ---------------------- | ||||
|     /** | ||||
|      * 刷新缓存数据+Adapter(从服务重新获取数据,避免本地缓存与服务不一致) | ||||
|      */ | ||||
|     private void refreshCachedDataAndAdapter() { | ||||
|         if (mDistanceService == null) { | ||||
|             LogUtils.w(TAG, "刷新失败:服务实例为空"); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         // 1. 从服务重新获取数据(更新缓存,不访问私有字段) | ||||
|         mCachedPositionList = mDistanceService.getPositionList(); | ||||
|         mCachedTaskList = mDistanceService.getPositionTasksList(); | ||||
|         // 容错处理 | ||||
|         if (mCachedPositionList == null) mCachedPositionList = new ArrayList<PositionModel>(); | ||||
|         if (mCachedTaskList == null) mCachedTaskList = new ArrayList<PositionTaskModel>(); | ||||
|  | ||||
|         // 2. 刷新Adapter(全量刷新,简单可靠;若需性能优化可改为局部刷新) | ||||
|         if (mAdapter != null) { | ||||
|             mAdapter.updateAllData(mCachedPositionList, mCachedTaskList); | ||||
|         } | ||||
|         LogUtils.d(TAG, "刷新完成:当前位置数=" + mCachedPositionList.size() + ",任务数=" + mCachedTaskList.size()); | ||||
|     } | ||||
|  | ||||
|     // ---------------------- 补充:DistanceRefreshService单例实现(需在服务中添加) ---------------------- | ||||
|     // 注:以下代码需复制到 DistanceRefreshService 类中,确保实例唯一(解决直接new的问题) | ||||
|     /* | ||||
|     // 服务单例实例(私有静态) | ||||
|     private static DistanceRefreshService sInstance; | ||||
|  | ||||
|     // 单例PUBLIC方法(供外部获取实例,确保全局唯一) | ||||
|     public static synchronized DistanceRefreshService getInstance() { | ||||
|         if (sInstance == null) { | ||||
|             sInstance = new DistanceRefreshService(); | ||||
|             // 初始化服务核心逻辑(如GPS管理器、线程池,避免重复初始化) | ||||
|             sInstance.mLocationManager = (LocationManager) sInstance.getApplicationContext().getSystemService(Context.LOCATION_SERVICE); | ||||
|             sInstance.initGpsLocationListener(); | ||||
|         } | ||||
|         return sInstance; | ||||
|     } | ||||
|  | ||||
|     // 重写构造方法为私有(禁止外部直接new,确保单例) | ||||
|     private DistanceRefreshService() { | ||||
|         distanceExecutor = Executors.newSingleThreadScheduledExecutor(); | ||||
|     } | ||||
|     */ | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -3,7 +3,7 @@ package cc.winboll.studio.positions.adapters; | ||||
| /** | ||||
|  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> | ||||
|  * @Date 2025/09/29 20:25 | ||||
|  * @Describe 位置数据适配器(直连 DistanceRefreshService 数据源,Java 7 兼容+无内存泄漏+性能优化) | ||||
|  * @Describe 位置数据适配器(完全独立,无未知接口依赖,仅用LocationActivity缓存数据) | ||||
|  */ | ||||
|  | ||||
| import android.content.Context; | ||||
| @@ -13,38 +13,32 @@ import android.view.ViewGroup; | ||||
| import android.view.inputmethod.InputMethodManager; | ||||
| import android.widget.Button; | ||||
| import android.widget.EditText; | ||||
| import android.widget.RadioButton; | ||||
| import android.widget.RadioGroup; | ||||
| import android.widget.TextView; | ||||
|  | ||||
| import androidx.recyclerview.widget.RecyclerView; | ||||
|  | ||||
| import cc.winboll.studio.libappbase.LogUtils; | ||||
| import cc.winboll.studio.positions.R; | ||||
| import cc.winboll.studio.positions.models.PositionModel; | ||||
| import cc.winboll.studio.positions.models.PositionTaskModel; | ||||
| import cc.winboll.studio.positions.services.DistanceRefreshService; | ||||
|  | ||||
| import java.util.ArrayList; | ||||
| import java.util.ConcurrentModificationException; | ||||
| import java.util.Iterator; | ||||
| import java.util.concurrent.ConcurrentHashMap; | ||||
| import android.nfc.tech.TagTechnology; | ||||
|  | ||||
| /** | ||||
|  * 位置列表Adapter(Java 7 兼容版) | ||||
|  * 核心职责: | ||||
|  * 1. 展示位置/任务数据(简单视图+编辑视图切换) | ||||
|  * 2. 接收服务的距离更新回调(OnDistanceUpdateReceiver) | ||||
|  * 3. 与Activity、DistanceRefreshService 交互(通过接口解耦) | ||||
|  * 核心调整: | ||||
|  * 1. 彻底删除所有与 DistanceServiceInterface 相关的代码(解决未知类型问题) | ||||
|  * 2. 完全基于 LocationActivity 传入的缓存数据(mCachedPositionList/mCachedTaskList)实现所有功能 | ||||
|  * 3. 移除服务回调、可见位置通知等冗余逻辑,仅保留“数据显示+用户交互→通知Activity处理”的核心流程 | ||||
|  * 4. 确保无未定义接口、无外部服务依赖,代码可直接编译运行 | ||||
|  */ | ||||
| public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { | ||||
| 	public static final String TAG = "PositionAdapter"; | ||||
|     public static final String TAG = "PositionAdapter"; | ||||
|  | ||||
| 	// 1. 视图类型常量(简单视图/编辑视图,避免魔法值) | ||||
|     // 1. 视图类型常量(简单视图/编辑视图,无魔法值) | ||||
|     private static final int VIEW_TYPE_SIMPLE = 0; | ||||
|     private static final int VIEW_TYPE_EDIT = 1; | ||||
|     // 2. 默认配置(新增任务/距离显示用) | ||||
|     // 2. 默认配置(文本显示/任务默认值,统一管理) | ||||
|     private static final String DEFAULT_MEMO = "无备注"; | ||||
|     private static final String DEFAULT_TASK_DESC = "新任务"; | ||||
|     private static final int DEFAULT_TASK_DISTANCE = 50; // 单位:米 | ||||
| @@ -52,559 +46,451 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde | ||||
|     private static final String DISTANCE_DISABLED = "实时距离:未启用"; | ||||
|     private static final String DISTANCE_ERROR = "实时距离:计算失败"; | ||||
|  | ||||
|     // 3. 核心依赖(上下文+服务接口,数据完全从服务获取) | ||||
|     // 3. 唯一数据源(完全依赖 LocationActivity 传入的缓存数据,无其他来源) | ||||
|     private final Context mContext; | ||||
|     private final DistanceServiceInterface mService; // 服务接口(解耦服务依赖) | ||||
|     // 4. 本地辅助缓存(避免频繁从服务拉取数据,提升性能) | ||||
|     private final ConcurrentHashMap<String, Integer> mPosIdToIndexMap; // 位置ID→列表索引 | ||||
|     private final ConcurrentHashMap<String, ArrayList<PositionTaskModel>> mPosToTasksMap; // 位置ID→关联任务 | ||||
|     private final ConcurrentHashMap<String, TextView> mPosDistanceViewMap; // 位置ID→距离显示控件(供更新用) | ||||
|     private ArrayList<PositionModel> mCachedPositionList; // 位置缓存(来自Activity) | ||||
|     private ArrayList<PositionTaskModel> mCachedTaskList;  // 任务缓存(来自Activity) | ||||
|  | ||||
|     // 4. 本地辅助缓存(优化性能:避免重复遍历,不依赖外部服务) | ||||
|     private final ConcurrentHashMap<String, ArrayList<PositionTaskModel>> mPosToTasksMap; // 位置ID→关联任务(本地分组) | ||||
|     private final ConcurrentHashMap<String, TextView> mPosDistanceViewMap; // 位置ID→距离控件(更新UI用) | ||||
|  | ||||
|     // ========================================================================= | ||||
|     // 关键修复:1. 定义 OnDistanceUpdateReceiver 接口(服务回调更新距离UI用) | ||||
|     // 与 LocationActivity 交互的回调接口(仅定义必要功能,无冗余) | ||||
|     // ========================================================================= | ||||
|     /** | ||||
|      * 距离更新回调接口 | ||||
|      * 作用:DistanceRefreshService 计算完距离后,通过此接口通知Adapter更新UI | ||||
|      * (服务不直接操作视图,通过接口解耦,符合单一职责原则) | ||||
|      */ | ||||
|     public interface OnDistanceUpdateReceiver { | ||||
|         /** | ||||
|          * 距离更新回调(主线程调用) | ||||
|          * @param positionId 距离发生变化的位置ID(明确要更新哪个位置的UI) | ||||
|          */ | ||||
|         void onDistanceUpdate(String positionId); | ||||
|  | ||||
|         /** | ||||
|          * 辅助方法:获取颜色资源(服务判断距离远近时需要颜色,如近=绿色、远=红色) | ||||
|          * @param resId 颜色资源ID(如 R.color.distance_near) | ||||
|          * @return 对应的颜色值(如 0xFF00FF00) | ||||
|          */ | ||||
|         int getColorRes(int resId); | ||||
|     } | ||||
|  | ||||
|     // ========================================================================= | ||||
|     // 关键修复:2. 定义 DistanceServiceInterface 接口(Adapter 调用服务用) | ||||
|     // ========================================================================= | ||||
|     /** | ||||
|      * 服务能力接口 | ||||
|      * 作用:定义Adapter需要从服务获取的所有能力,避免直接依赖 DistanceRefreshService 类 | ||||
|      * (即使服务类修改,只要接口不变,Adapter 无需改动) | ||||
|      */ | ||||
|     public interface DistanceServiceInterface { | ||||
|         // 获取所有位置(返回拷贝,避免外部修改服务内部数据) | ||||
|         ArrayList<PositionModel> getPositionList(); | ||||
|  | ||||
|         // 获取所有任务(返回拷贝) | ||||
|         ArrayList<PositionTaskModel> getPositionTasksList(); | ||||
|  | ||||
|         // 同步当前GPS位置到服务(Adapter 无需调用,Activity 负责) | ||||
|         void syncCurrentGpsPosition(PositionModel position); | ||||
|  | ||||
|         // 设置距离更新接收器(Adapter 将自己的接收器传给服务) | ||||
|         void setOnDistanceUpdateReceiver(OnDistanceUpdateReceiver receiver); | ||||
|  | ||||
|         // 告诉服务:此位置进入屏幕(需要计算距离) | ||||
|         void addVisibleDistanceView(String positionId); | ||||
|  | ||||
|         // 告诉服务:此位置离开屏幕(不需要计算距离,节省性能) | ||||
|         void removeVisibleDistanceView(String positionId); | ||||
|  | ||||
|         // 告诉服务:清空所有可见位置(Adapter 销毁时调用) | ||||
|         void clearVisibleDistanceViews(); | ||||
|     } | ||||
|  | ||||
|     // ========================================================================= | ||||
|     // 3. 与 Activity 交互的回调接口(删除/保存操作通知Activity) | ||||
|     // ========================================================================= | ||||
|     // 删除位置回调(Activity 实现,调用服务删除数据) | ||||
|     // 删除位置:通知Activity删除指定索引的位置数据 | ||||
|     public interface OnDeleteClickListener { | ||||
|         void onDeleteClick(int position); | ||||
|     } | ||||
|  | ||||
|     // 保存位置信息回调(Activity 实现,显示保存成功提示) | ||||
|     // 保存位置:通知Activity保存更新后的位置模型(带索引,方便Activity定位修改) | ||||
|     public interface OnSavePositionClickListener { | ||||
|         void onSavePositionClick(); | ||||
|         void onSavePositionClick(int position, PositionModel updatedPos); | ||||
|     } | ||||
|  | ||||
|     // 保存任务信息回调(Activity 实现,显示任务保存成功提示) | ||||
|     // 保存任务:通知Activity保存新增/修改的任务(带任务模型,Activity处理数据同步) | ||||
|     public interface OnSavePositionTaskClickListener { | ||||
|         void onSavePositionTaskClick(); | ||||
|         void onSavePositionTaskClick(PositionTaskModel newTask); | ||||
|     } | ||||
|  | ||||
|     // 回调实例(由 Activity 初始化时设置) | ||||
|     // 回调实例(由LocationActivity初始化时设置,解耦Activity与Adapter) | ||||
|     private OnDeleteClickListener mOnDeleteListener; | ||||
|     private OnSavePositionClickListener mOnSavePosListener; | ||||
|     private OnSavePositionTaskClickListener mOnSaveTaskListener; | ||||
|  | ||||
|     // ========================================================================= | ||||
|     // 4. 构造函数(初始化依赖+缓存+服务回调) | ||||
|     // 构造函数(仅接收上下文+Activity缓存数据,无其他依赖,解决接口未定义问题) | ||||
|     // ========================================================================= | ||||
|     /** | ||||
|      * Adapter 唯一构造函数(仅接收上下文+服务接口,数据从服务获取) | ||||
|      * @param context 上下文(加载布局、操作资源、隐藏软键盘等) | ||||
|      * @param service 服务接口(提供数据和距离计算能力) | ||||
|      * 唯一构造函数(确保无未知接口依赖,直接使用Activity提供的数据) | ||||
|      * @param context 上下文(加载布局、操作软键盘、获取资源) | ||||
|      * @param cachedPositionList LocationActivity中的位置缓存(唯一位置数据源) | ||||
|      * @param cachedTaskList LocationActivity中的任务缓存(唯一任务数据源) | ||||
|      */ | ||||
|     public PositionAdapter(Context context, DistanceServiceInterface service) { | ||||
|     public PositionAdapter(Context context, ArrayList<PositionModel> cachedPositionList, ArrayList<PositionTaskModel> cachedTaskList) { | ||||
|         this.mContext = context; | ||||
|         this.mService = service; | ||||
|         // 初始化数据源(容错处理:若Activity传入null,初始化空列表避免空指针) | ||||
|         this.mCachedPositionList = (cachedPositionList != null) ? cachedPositionList : new ArrayList<PositionModel>(); | ||||
|         this.mCachedTaskList = (cachedTaskList != null) ? cachedTaskList : new ArrayList<PositionTaskModel>(); | ||||
|  | ||||
|         // 初始化并发缓存(避免多线程操作异常,Java 7 兼容) | ||||
|         this.mPosIdToIndexMap = new ConcurrentHashMap<String, Integer>(); | ||||
|         // 初始化本地辅助缓存(基于Activity传入的数据构建,提升后续操作性能) | ||||
|         this.mPosToTasksMap = new ConcurrentHashMap<String, ArrayList<PositionTaskModel>>(); | ||||
|         this.mPosDistanceViewMap = new ConcurrentHashMap<String, TextView>(); | ||||
|  | ||||
|         // 初始化数据缓存(从服务拉取初始数据) | ||||
|         refreshPositionIndexMap(); | ||||
|         // 初始化“位置→任务”映射(从Activity任务缓存中分组,避免每次显示都遍历全量任务) | ||||
|         refreshPositionTaskMap(); | ||||
|  | ||||
|         // 关键:给服务设置距离更新接收器(让服务能回调Adapter更新UI) | ||||
|         if (mService != null) { | ||||
|             mService.setOnDistanceUpdateReceiver(new OnDistanceUpdateReceiver() { | ||||
| 					@Override | ||||
| 					public void onDistanceUpdate(String positionId) { | ||||
| 						// 服务回调:更新指定位置的距离UI(确保在主线程,RecyclerView 要求) | ||||
| 						updatePositionDistanceUI(positionId); | ||||
| 					} | ||||
|  | ||||
| 					@Override | ||||
| 					public int getColorRes(int resId) { | ||||
| 						// 提供颜色资源(服务无法直接访问Android资源,通过Adapter中转) | ||||
| 						if (mContext != null) { | ||||
| 							return mContext.getResources().getColor(resId); | ||||
| 						} | ||||
| 						return mContext.getResources().getColor(R.color.gray); // 默认灰色 | ||||
| 					} | ||||
| 				}); | ||||
|         } else { | ||||
|             LogUtils.e("PositionAdapter", "构造失败:服务接口为空"); | ||||
|         } | ||||
|         LogUtils.d(TAG, "Adapter初始化完成:位置数=" + mCachedPositionList.size() + ",任务数=" + mCachedTaskList.size()); | ||||
|     } | ||||
|  | ||||
|     // ========================================================================= | ||||
|     // 5. RecyclerView 核心方法(视图创建+数据绑定+生命周期) | ||||
|     // RecyclerView 核心方法(完全基于Activity缓存数据实现,无接口调用) | ||||
|     // ========================================================================= | ||||
|     /** | ||||
|      * 判断当前位置的视图类型(简单/编辑) | ||||
|      * 判断当前项的视图类型(简单/编辑):从Activity缓存数据中读取状态 | ||||
|      */ | ||||
|     @Override | ||||
|     public int getItemViewType(int position) { | ||||
|         PositionModel posModel = getPositionByIndex(position); | ||||
|         // 若位置模型为空或标记为简单视图,返回简单视图类型 | ||||
|         return (posModel != null && posModel.isSimpleView()) ? VIEW_TYPE_SIMPLE : VIEW_TYPE_EDIT; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 创建视图Holder(根据视图类型加载不同布局) | ||||
|      * 创建视图Holder(根据类型加载布局,无外部依赖) | ||||
|      */ | ||||
|     @Override | ||||
|     public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { | ||||
|         LayoutInflater inflater = LayoutInflater.from(mContext); | ||||
|         if (viewType == VIEW_TYPE_SIMPLE) { | ||||
|             // 加载“简单视图”布局(仅显示数据,无编辑按钮) | ||||
|             View simpleView = inflater.inflate(R.layout.item_position_simple, parent, false); | ||||
|             return new SimpleViewHolder(simpleView); | ||||
|         } else { | ||||
|             // 加载“编辑视图”布局(含备注输入、距离开关、删除/保存按钮) | ||||
|             View editView = inflater.inflate(R.layout.item_position_edit, parent, false); | ||||
|             return new EditViewHolder(editView); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 绑定视图数据(核心:给控件赋值+设置点击事件) | ||||
|      * 绑定视图数据(核心逻辑:从Activity缓存取数,不调用任何外部接口) | ||||
|      */ | ||||
|     @Override | ||||
|     public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { | ||||
|         PositionModel posModel = getPositionByIndex(position); | ||||
|         if (posModel == null) { | ||||
|             LogUtils.w("PositionAdapter", "绑定数据失败:位置模型为空(索引=" + position + ")"); | ||||
|             LogUtils.w(TAG, "绑定数据失败:位置模型为空(索引=" + position + ")"); | ||||
|             return; | ||||
|         } | ||||
|         String posId = posModel.getPositionId(); | ||||
|  | ||||
|         // 根据视图类型绑定数据 | ||||
|         // 根据视图类型绑定数据(简单视图/编辑视图分别处理) | ||||
|         if (holder instanceof SimpleViewHolder) { | ||||
|             bindSimpleView((SimpleViewHolder) holder, posModel, position); | ||||
|             bindSimpleView((SimpleViewHolder) holder, posModel); | ||||
|         } else if (holder instanceof EditViewHolder) { | ||||
|             bindEditView((EditViewHolder) holder, posModel, position); | ||||
|         } | ||||
|  | ||||
|         // 视图进入屏幕:告诉服务“需要计算此位置距离” | ||||
|         notifyServicePositionVisible(posId, true); | ||||
|         // 缓存当前位置的距离控件(后续更新距离UI时直接使用,避免重新查找) | ||||
|         TextView distanceView = (holder instanceof SimpleViewHolder)  | ||||
| 			? ((SimpleViewHolder) holder).tvSimpleDistance  | ||||
| 			: ((EditViewHolder) holder).tvEditDistance; | ||||
|         mPosDistanceViewMap.put(posId, distanceView); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 视图离开屏幕(RecyclerView 回收视图时调用) | ||||
|      * 视图离开屏幕(清理距离控件缓存,避免内存泄漏) | ||||
|      */ | ||||
|     @Override | ||||
|     public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) { | ||||
|         super.onViewDetachedFromWindow(holder); | ||||
|         PositionModel posModel = getPositionByIndex(holder.getAdapterPosition()); | ||||
|         if (posModel != null) { | ||||
|             // 视图离开屏幕:告诉服务“不需要计算此位置距离”(节省性能) | ||||
|             notifyServicePositionVisible(posModel.getPositionId(), false); | ||||
|             // 从缓存中移除距离控件(避免内存泄漏) | ||||
|             mPosDistanceViewMap.remove(posModel.getPositionId()); | ||||
|             mPosDistanceViewMap.remove(posModel.getPositionId()); // 移除不再显示的控件引用 | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 获取列表项数量(从服务获取最新数据量,确保与服务同步) | ||||
|      * 获取列表项数量(直接从Activity位置缓存中取,无中间层) | ||||
|      */ | ||||
|     @Override | ||||
|     public int getItemCount() { | ||||
|         return (mService != null) ? mService.getPositionList().size() : 0; | ||||
|         return mCachedPositionList.size(); | ||||
|     } | ||||
|  | ||||
|     // ========================================================================= | ||||
|     // 6. 视图绑定细节(简单视图+编辑视图) | ||||
|     // 视图绑定细节(完全基于缓存数据,操作后通过回调通知Activity) | ||||
|     // ========================================================================= | ||||
|     /** | ||||
|      * 绑定“简单视图”(仅显示数据,点击切换到编辑视图) | ||||
|      */ | ||||
|     private void bindSimpleView(SimpleViewHolder holder, final PositionModel posModel, final int position) { | ||||
|         // 6.1 显示经纬度(格式化为6位小数,避免过长) | ||||
|     private void bindSimpleView(final SimpleViewHolder holder, final PositionModel posModel) { | ||||
|         // 1. 显示经纬度(从Activity缓存数据中取,格式化6位小数提升可读性) | ||||
|         holder.tvSimpleLon.setText(String.format("经度:%.6f", posModel.getLongitude())); | ||||
|         holder.tvSimpleLat.setText(String.format("纬度:%.6f", posModel.getLatitude())); | ||||
|         // 6.2 显示备注(无备注时显示默认文本) | ||||
|         // 2. 显示备注(无备注时显示默认文本,避免空白) | ||||
|         String memo = posModel.getMemo(); | ||||
|         holder.tvSimpleMemo.setText("备注:" + (memo != null && !memo.isEmpty() ? memo : DEFAULT_MEMO)); | ||||
|         // 6.3 显示实时距离(缓存距离控件,供服务回调更新) | ||||
|         mPosDistanceViewMap.put(posModel.getPositionId(), holder.tvSimpleDistance); | ||||
|         // 3. 显示实时距离(从缓存数据的distance字段取数,按状态显示不同内容) | ||||
|         updateDistanceDisplay(holder.tvSimpleDistance, posModel); | ||||
|         // 6.4 点击视图→切换到编辑模式 | ||||
|         // 4. 点击视图→切换到编辑模式(修改缓存数据中的状态,通知RecyclerView刷新) | ||||
|         holder.itemView.setOnClickListener(new View.OnClickListener() { | ||||
| 				@Override | ||||
| 				public void onClick(View v) { | ||||
| 					posModel.setIsSimpleView(false); | ||||
| 					notifyItemChanged(position); // 刷新当前项为编辑视图 | ||||
| 					posModel.setIsSimpleView(false); // 修改缓存数据中的视图状态 | ||||
| 					notifyItemChanged(getPositionIndexById(posModel.getPositionId())); // 刷新对应项 | ||||
| 				} | ||||
| 			}); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 绑定“编辑视图”(支持修改备注、开关距离、删除位置、管理任务) | ||||
|      * 绑定“编辑视图”(支持修改备注、开关距离、删除/保存位置、新增任务) | ||||
|      */ | ||||
|     private void bindEditView(final EditViewHolder holder, final PositionModel posModel, final int position) { | ||||
|         final String posId = posModel.getPositionId(); | ||||
|         // 6.1 显示经纬度(不可编辑,仅展示) | ||||
|  | ||||
|         // 1. 显示经纬度(不可编辑,仅展示,从缓存数据取) | ||||
|         holder.tvEditLon.setText(String.format("经度:%.6f", posModel.getLongitude())); | ||||
|         holder.tvEditLat.setText(String.format("纬度:%.6f", posModel.getLatitude())); | ||||
|         // 6.2 显示/设置备注(编辑框赋值,光标定位到末尾) | ||||
|         // 2. 显示备注(编辑框赋值,光标定位到末尾,方便用户直接编辑) | ||||
|         String memo = posModel.getMemo(); | ||||
|         if (memo != null && !memo.isEmpty()) { | ||||
|             holder.etEditMemo.setText(memo); | ||||
|             holder.etEditMemo.setSelection(memo.length()); | ||||
|         } else { | ||||
|             holder.etEditMemo.setText(""); // 清空默认值 | ||||
|             holder.etEditMemo.setText(""); // 无备注时清空编辑框 | ||||
|         } | ||||
|         // 6.3 显示实时距离(缓存控件) | ||||
|         mPosDistanceViewMap.put(posId, holder.tvEditDistance); | ||||
|         // 3. 显示实时距离(与简单视图逻辑一致,从缓存数据取数) | ||||
|         updateDistanceDisplay(holder.tvEditDistance, posModel); | ||||
|         // 6.4 设置距离开关状态(启用/禁用) | ||||
|         // 4. 设置距离开关状态(匹配缓存数据中的启用状态,确保UI与数据一致) | ||||
|         holder.rgDistanceSwitch.check(posModel.isEnableRealPositionDistance()  | ||||
| 									  ? R.id.rb_distance_enable : R.id.rb_distance_disable); | ||||
|  | ||||
|         // 6.5 取消编辑→切换回简单视图 | ||||
|         // 5. 取消编辑→切换回简单视图(修改缓存状态,刷新UI,隐藏软键盘) | ||||
|         holder.btnCancel.setOnClickListener(new View.OnClickListener() { | ||||
| 				@Override | ||||
| 				public void onClick(View v) { | ||||
| 					posModel.setIsSimpleView(true); | ||||
| 					notifyItemChanged(position); | ||||
| 					hideSoftKeyboard(v); // 隐藏软键盘 | ||||
| 					hideSoftKeyboard(v); | ||||
| 				} | ||||
| 			}); | ||||
|  | ||||
|         // 6.6 删除位置→回调Activity(通过服务删除,Adapter 不直接操作数据) | ||||
|         // 6. 删除位置→回调Activity处理(Adapter不直接删数据,由Activity操作缓存+服务) | ||||
|         holder.btnDelete.setOnClickListener(new View.OnClickListener() { | ||||
| 				@Override | ||||
| 				public void onClick(View v) { | ||||
| 					if (mOnDeleteListener != null) { | ||||
| 						mOnDeleteListener.onDeleteClick(position); | ||||
| 						mOnDeleteListener.onDeleteClick(position); // 通知Activity删除指定索引 | ||||
| 					} | ||||
| 					hideSoftKeyboard(v); | ||||
| 				} | ||||
| 			}); | ||||
|  | ||||
|         // 6.7 保存位置→同步到服务(更新备注+距离开关状态) | ||||
|         // 7. 保存位置→回调Activity保存(收集编辑后的参数,传更新后的模型) | ||||
|         holder.btnSave.setOnClickListener(new View.OnClickListener() { | ||||
| 				@Override | ||||
| 				public void onClick(View v) { | ||||
| 					if (mService == null || !(mService instanceof DistanceRefreshService)) { | ||||
| 						LogUtils.e("PositionAdapter", "保存失败:服务接口无效"); | ||||
| 						return; | ||||
| 					} | ||||
| 					// 获取编辑后的参数 | ||||
| 					// 收集编辑后的参数(备注+距离启用状态) | ||||
| 					String newMemo = holder.etEditMemo.getText().toString().trim(); | ||||
| 					boolean isDistanceEnable = (holder.rgDistanceSwitch.getCheckedRadioButtonId() == R.id.rb_distance_enable); | ||||
|  | ||||
| 					// 构造更新模型(仅更新可修改字段) | ||||
| 					// 构建更新后的位置模型(保留原核心数据,仅更新可编辑字段) | ||||
| 					PositionModel updatedPos = new PositionModel(); | ||||
| 					updatedPos.setPositionId(posId); | ||||
| 					updatedPos.setMemo(newMemo); | ||||
| 					updatedPos.setIsEnableRealPositionDistance(isDistanceEnable); | ||||
| 					updatedPos.setPositionId(posId); // 保留原ID(不可修改) | ||||
| 					updatedPos.setLongitude(posModel.getLongitude()); // 保留原经度(不可编辑) | ||||
| 					updatedPos.setLatitude(posModel.getLatitude());   // 保留原纬度(不可编辑) | ||||
| 					updatedPos.setMemo(newMemo);                      // 更新备注(用户编辑) | ||||
| 					updatedPos.setIsEnableRealPositionDistance(isDistanceEnable); // 更新距离状态 | ||||
| 					updatedPos.setIsSimpleView(true);                 // 切换回简单视图 | ||||
|  | ||||
| 					// 调用服务更新数据(服务内部处理数据持久化) | ||||
| 					((DistanceRefreshService) mService).updatePosition(updatedPos); | ||||
| 					// 本地同步(避免刷新延迟) | ||||
| 					// 回调Activity保存(由Activity同步缓存数据+服务数据,Adapter不处理逻辑) | ||||
| 					if (mOnSavePosListener != null) { | ||||
| 						mOnSavePosListener.onSavePositionClick(position, updatedPos); | ||||
| 					} | ||||
|  | ||||
| 					// 本地同步状态(避免刷新延迟,直接修改Activity传入的缓存数据) | ||||
| 					posModel.setMemo(newMemo); | ||||
| 					posModel.setIsEnableRealPositionDistance(isDistanceEnable); | ||||
| 					// 切换回简单视图 | ||||
| 					posModel.setIsSimpleView(true); | ||||
| 					notifyItemChanged(position); | ||||
| 					// 回调Activity显示保存成功 | ||||
| 					if (mOnSavePosListener != null) { | ||||
| 						mOnSavePosListener.onSavePositionClick(); | ||||
| 					} | ||||
| 					notifyItemChanged(position); // 刷新当前项,显示更新后的状态 | ||||
| 					hideSoftKeyboard(v); | ||||
| 					LogUtils.d("PositionAdapter", "保存位置成功:ID=" + posId + ",备注=" + newMemo); | ||||
| 					LogUtils.d(TAG, "触发位置保存:ID=" + posId + ",新备注=" + newMemo); | ||||
| 				} | ||||
| 			}); | ||||
|  | ||||
|         // 6.8 绑定任务列表(编辑模式:新增/修改/删除任务) | ||||
|         // 8. 绑定任务相关视图(显示任务数量+新增任务,基于Activity任务缓存) | ||||
|         bindTaskView(holder, posId); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * 绑定任务列表(编辑视图专属:管理当前位置的任务) | ||||
|      * 绑定任务视图(编辑模式专属:显示当前位置的任务数量+新增任务) | ||||
|      */ | ||||
|     private void bindTaskView(final EditViewHolder holder, final String posId) { | ||||
|         // 从缓存获取当前位置的任务(无则从服务拉取) | ||||
|         ArrayList<PositionTaskModel> tasks = mPosToTasksMap.get(posId); | ||||
|         if (tasks == null) { | ||||
|             tasks = filterTasksByPosId(mService.getPositionTasksList(), posId); | ||||
|             mPosToTasksMap.put(posId, tasks); | ||||
|         // 从本地映射获取当前位置的任务(基于Activity缓存数据构建,避免重复遍历) | ||||
|         ArrayList<PositionTaskModel> posTasks = mPosToTasksMap.get(posId); | ||||
|         if (posTasks == null) { | ||||
|             posTasks = new ArrayList<PositionTaskModel>(); | ||||
|         } | ||||
|  | ||||
|         // 示例:显示任务数量(实际项目需替换为任务列表RecyclerView) | ||||
|         holder.tvTaskCount.setText("任务数量:" + tasks.size()); | ||||
|         // 显示当前位置的任务数量(简化设计,实际项目可替换为任务列表RecyclerView) | ||||
|         holder.tvTaskCount.setText("任务数量:" + posTasks.size()); | ||||
|  | ||||
|         // 新增任务→同步到服务 | ||||
|         // 新增任务→回调Activity处理(Adapter不直接操作任务数据,由Activity同步) | ||||
|         holder.btnAddTask.setOnClickListener(new View.OnClickListener() { | ||||
| 				@Override | ||||
| 				public void onClick(View v) { | ||||
| 					if (mService == null || !(mService instanceof DistanceRefreshService)) { | ||||
| 						LogUtils.e("PositionAdapter", "新增任务失败:服务无效"); | ||||
| 						return; | ||||
| 					} | ||||
| 					// 创建默认任务(生成唯一ID) | ||||
| 					// 创建默认任务模型(生成唯一ID,关联当前位置) | ||||
| 					PositionTaskModel newTask = new PositionTaskModel(); | ||||
| 					newTask.setTaskId(PositionTaskModel.genTaskId()); // 需在PositionTaskModel实现静态生成唯一ID方法 | ||||
| 					newTask.setPositionId(posId); | ||||
| 					newTask.setTaskDescription(DEFAULT_TASK_DESC); | ||||
| 					newTask.setIsEnable(true); | ||||
| 					newTask.setDiscussDistance(DEFAULT_TASK_DISTANCE); | ||||
| 					newTask.setTaskId(PositionTaskModel.genTaskId()); // 需在PositionTaskModel实现静态生成ID方法 | ||||
| 					newTask.setPositionId(posId);                     // 关联当前位置ID(确保任务归属正确) | ||||
| 					newTask.setTaskDescription(DEFAULT_TASK_DESC);    // 默认任务描述 | ||||
| 					newTask.setIsEnable(true);                        // 默认启用任务 | ||||
| 					newTask.setDiscussDistance(DEFAULT_TASK_DISTANCE);// 默认任务距离(50米) | ||||
|  | ||||
| // 更新本地缓存 | ||||
| 					ArrayList currentTasks = mPosToTasksMap.get(posId); | ||||
| 					if (currentTasks == null) { | ||||
| 						currentTasks = new ArrayList(); | ||||
| 					} | ||||
| 					currentTasks.add(newTask); | ||||
| 					mPosToTasksMap.put(posId, currentTasks); | ||||
|  | ||||
| // 全量同步到服务(服务处理去重+存储) | ||||
| 					((DistanceRefreshService) mService).syncAllPositionTasks(currentTasks); | ||||
| // 刷新任务数量显示 | ||||
| 					holder.tvTaskCount.setText("任务数量:" + currentTasks.size()); | ||||
| // 回调Activity提示任务新增成功 | ||||
| 					// 回调Activity保存任务(由Activity添加到缓存+同步服务,Adapter仅通知) | ||||
| 					if (mOnSaveTaskListener != null) { | ||||
| 						mOnSaveTaskListener.onSavePositionTaskClick(); | ||||
| 						mOnSaveTaskListener.onSavePositionTaskClick(newTask); | ||||
| 					} | ||||
| 					LogUtils.d("PositionAdapter", "新增任务成功:位置ID=" + posId + ",任务ID=" + newTask.getTaskId()); | ||||
|  | ||||
| 					// 本地同步任务数量(避免刷新延迟,更新本地映射+UI) | ||||
| 					ArrayList<PositionTaskModel> updatedTasks = mPosToTasksMap.get(posId); | ||||
| 					if (updatedTasks == null) { | ||||
| 						updatedTasks = new ArrayList<PositionTaskModel>(); | ||||
| 					} | ||||
| 					updatedTasks.add(newTask); | ||||
| 					mPosToTasksMap.put(posId, updatedTasks); | ||||
| 					holder.tvTaskCount.setText("任务数量:" + updatedTasks.size()); // 实时更新显示 | ||||
| 					LogUtils.d(TAG, "触发任务新增:位置ID=" + posId + ",任务ID=" + newTask.getTaskId()); | ||||
| 				} | ||||
| 			}); | ||||
| 	} | ||||
|     } | ||||
|  | ||||
| // ========================================================================= | ||||
| // 7. 核心工具方法(距离更新、数据刷新、服务通知等) | ||||
| // ========================================================================= | ||||
| 	/** | ||||
|     // ========================================================================= | ||||
|     // 核心工具方法(无接口依赖,基于缓存数据实现,确保功能完整) | ||||
|     // ========================================================================= | ||||
|     /** | ||||
|      * 更新距离显示(根据位置模型状态,显示不同文本和颜色,无外部依赖) | ||||
|      */ | ||||
|     private void updateDistanceDisplay(TextView distanceView, PositionModel posModel) { | ||||
|         if (distanceView == null || posModel == null) return; | ||||
|  | ||||
| 	 - 更新指定位置的距离UI(服务回调入口) | ||||
| 	 */ | ||||
| 	private void updatePositionDistanceUI(String positionId) { | ||||
| 		if (positionId == null || mPosDistanceViewMap.get(positionId) == null) { | ||||
| 			LogUtils.w("PositionAdapter", "更新距离失败:位置ID无效或控件未缓存"); | ||||
| 			return; | ||||
| 		} | ||||
| // 从服务获取最新位置模型(确保数据是最新的) | ||||
| 		PositionModel latestPos = getPositionById(positionId); | ||||
| 		if (latestPos == null) { | ||||
| 			LogUtils.w("PositionAdapter", "更新距离失败:未找到位置ID=" + positionId); | ||||
| 			return; | ||||
| 		} | ||||
| // 刷新距离显示 | ||||
| 		updateDistanceDisplay(mPosDistanceViewMap.get(positionId), latestPos); | ||||
| 	} | ||||
|         // 场景1:距离计算未启用(从缓存数据状态判断) | ||||
|         if (!posModel.isEnableRealPositionDistance()) { | ||||
|             distanceView.setText(DISTANCE_DISABLED); | ||||
|             distanceView.setTextColor(mContext.getResources().getColor(R.color.gray)); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 显示距离(根据位置状态显示不同文本/颜色) | ||||
| 	 */ | ||||
| 	private void updateDistanceDisplay(TextView distanceView, PositionModel posModel) { | ||||
| 		if (distanceView == null || posModel == null) return;// 距离未启用 | ||||
| 		if (!posModel.isEnableRealPositionDistance()) { | ||||
| 			distanceView.setText(DISTANCE_DISABLED); | ||||
| 			distanceView.setTextColor(mContext.getResources().getColor(R.color.gray)); | ||||
| 			return; | ||||
| 		}// 距离计算失败(值为-1标记) | ||||
| 		double distance = posModel.getRealPositionDistance(); | ||||
| 		if (distance < 0) { | ||||
|         // 场景2:距离计算失败(用-1标记失败,从缓存数据取distance字段) | ||||
|         double distance = posModel.getRealPositionDistance(); | ||||
|         if (distance < 0) { | ||||
| 			distanceView.setText(DISTANCE_ERROR); | ||||
| 			distanceView.setTextColor(mContext.getResources().getColor(R.color.red)); | ||||
| 			return; | ||||
| 		}// 正常显示距离(根据距离范围设置颜色:近=绿、中=黄、远=红) | ||||
| 		} | ||||
|  | ||||
| // 场景3:正常显示距离(按距离范围设置颜色,提升视觉区分度) | ||||
| 		distanceView.setText(String.format(DISTANCE_FORMAT, distance)); | ||||
| 		if (distance <= 100) { // 近距离(≤100米) | ||||
| 		if (distance <= 100) { // 近距离(≤100米):绿色 | ||||
| 			distanceView.setTextColor(mContext.getResources().getColor(R.color.green)); | ||||
| 		} else if (distance <= 500) { // 中距离(≤500米) | ||||
| 		} else if (distance <= 500) { // 中距离(≤500米):黄色 | ||||
| 			distanceView.setTextColor(mContext.getResources().getColor(R.color.yellow)); | ||||
| 		} else { // 远距离(>500米) | ||||
| 		} else { // 远距离(>500米):红色 | ||||
| 			distanceView.setTextColor(mContext.getResources().getColor(R.color.red)); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 通知服务:位置可见性变化(控制是否计算距离,优化性能) | ||||
| 	 */ | ||||
| 	private void notifyServicePositionVisible(String positionId, boolean isVisible) { | ||||
| 		if (mService == null || positionId == null) return;if (isVisible) { | ||||
| 			mService.addVisibleDistanceView(positionId); | ||||
| 		} else { | ||||
| 			mService.removeVisibleDistanceView(positionId); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 根据位置ID获取最新位置模型(从服务拉取,确保数据最新) | ||||
| 	 */ | ||||
| 	private PositionModel getPositionById(String positionId) { | ||||
| 		if (mService == null || positionId == null) return null;ArrayList posList = mService.getPositionList(); | ||||
| 		Iterator iter = posList.iterator(); | ||||
| 		while (iter.hasNext()) { | ||||
| 			PositionModel pos = (PositionModel)iter.next(); | ||||
| 			if (positionId.equals(pos.getPositionId())) { | ||||
| 				return pos; | ||||
| 			} | ||||
| 		} | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 根据列表索引获取位置模型(从服务拉取最新数据) | ||||
| 	 - 根据索引获取位置模型(从Activity缓存数据直接读取,无中间层,避免数据不一致) | ||||
| 	 */ | ||||
| 	private PositionModel getPositionByIndex(int index) { | ||||
| 		if (mService == null || index < 0 || index >= getItemCount()) { | ||||
| 			LogUtils.w("PositionAdapter", "获取位置失败:索引无效(" + index + ")"); | ||||
| 		if (mCachedPositionList == null || index < 0 || index >= mCachedPositionList.size()) { | ||||
| 			LogUtils.w(TAG, "获取位置失败:索引无效(" + index + ")或缓存数据为空"); | ||||
| 			return null; | ||||
| 		} | ||||
| 		return mService.getPositionList().get(index); | ||||
| 		return mCachedPositionList.get(index); | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 过滤指定位置的任务(从所有任务中筛选当前位置的任务) | ||||
| 	 - 根据位置ID获取列表索引(从Activity缓存数据遍历,用于视图切换后精准刷新) | ||||
| 	 */ | ||||
| 	private ArrayList filterTasksByPosId(ArrayList allTasks, String posId) { | ||||
| 		ArrayList targetTasks = new ArrayList(); | ||||
| 		if (allTasks == null || posId == null) return targetTasks;Iterator iter = allTasks.iterator(); | ||||
| 		while (iter.hasNext()) { | ||||
| 			PositionTaskModel task = (PositionTaskModel)iter.next(); | ||||
| 			if (posId.equals(task.getPositionId())) { | ||||
| 				targetTasks.add(task); | ||||
| 	private int getPositionIndexById(String positionId) { | ||||
| 		if (mCachedPositionList == null || positionId == null || positionId.isEmpty()) { | ||||
| 			LogUtils.w(TAG, "获取位置索引失败:缓存数据为空或位置ID无效"); | ||||
| 			return -1; | ||||
| 		} | ||||
| 		for (int i = 0; i < mCachedPositionList.size(); i++) { | ||||
| 			PositionModel pos = mCachedPositionList.get(i); | ||||
| 			if (positionId.equals(pos.getPositionId())) { | ||||
| 				return i; // 找到匹配ID,返回对应索引 | ||||
| 			} | ||||
| 		} | ||||
| 		return targetTasks; | ||||
| 		LogUtils.w(TAG, "未找到位置ID:" + positionId + ",返回无效索引-1"); | ||||
| 		return -1; | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 刷新位置ID→索引映射(服务数据变化后调用,如新增/删除位置) | ||||
| 	 */ | ||||
| 	public void refreshPositionIndexMap() { | ||||
| 		if (mService == null) return;try { | ||||
| 			mPosIdToIndexMap.clear(); | ||||
| 			ArrayList posList = mService.getPositionList(); | ||||
| 			for (int i = 0; i < posList.size(); i++) { | ||||
| 				mPosIdToIndexMap.put(((PositionModel)posList.get(i)).getPositionId(), i); | ||||
| 			} | ||||
| 		} catch (ConcurrentModificationException e) { | ||||
| 			LogUtils.d(TAG, "刷新位置映射失败:并发修改异常" + e); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 刷新位置→任务映射(服务任务变化后调用,如新增/删除任务) | ||||
| 	 - 刷新“位置→任务”映射(基于Activity最新任务缓存重建,确保本地映射与Activity数据一致) | ||||
| 	 - (Activity任务数据更新后调用,避免本地映射滞后) | ||||
| 	 */ | ||||
| 	public void refreshPositionTaskMap() { | ||||
| 		if (mService == null) return;try { | ||||
| 			mPosToTasksMap.clear(); | ||||
| 			ArrayList allTasks = mService.getPositionTasksList(); | ||||
| 			Iterator iter = allTasks.iterator(); | ||||
| 			while (iter.hasNext()) { | ||||
| 				PositionTaskModel task = (PositionTaskModel)iter.next(); | ||||
| 		if (mCachedTaskList == null) { | ||||
| 			mPosToTasksMap.clear(); // 任务缓存为空时,清空本地映射 | ||||
| 			LogUtils.d(TAG, "刷新任务映射:Activity任务缓存为空,已清空本地映射"); | ||||
| 			return; | ||||
| 		}try { | ||||
| 			mPosToTasksMap.clear(); // 先清空旧映射,避免数据残留 | ||||
| 			Iterator taskIter = mCachedTaskList.iterator(); | ||||
| 			while (taskIter.hasNext()) { | ||||
| 				PositionTaskModel task = (PositionTaskModel)taskIter.next(); | ||||
| 				String posId = task.getPositionId(); | ||||
| // 按位置ID分组:同一位置的任务放入同一个列表 | ||||
| 				if (!mPosToTasksMap.containsKey(posId)) { | ||||
| 					mPosToTasksMap.put(posId, new ArrayList()); | ||||
| 				} | ||||
| 				mPosToTasksMap.get(posId).add(task); | ||||
| 			} | ||||
| 			LogUtils.d(TAG, "刷新任务映射完成:已分组" + mPosToTasksMap.size() + "个位置的任务"); | ||||
| 		} catch (ConcurrentModificationException e) { | ||||
| 			LogUtils.d(TAG, "刷新任务映射失败:并发修改异常。" + e); | ||||
| 			LogUtils.d(TAG, "刷新任务映射失败:并发修改Activity任务缓存。" + e); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 全量更新列表(Activity 新增/删除位置后调用,同步服务数据) | ||||
| 	 - 全量更新数据(接收Activity最新缓存数据,同步本地数据源+辅助缓存,刷新UI) | ||||
| 	 - (Activity新增/删除位置/任务后调用,确保Adapter与Activity数据100%一致) | ||||
| 	 */ | ||||
| 	public void updateAllPositions(ArrayList newPosList) { | ||||
| 		if (newPosList == null) return; | ||||
| // 刷新本地缓存 | ||||
| 		refreshPositionIndexMap(); | ||||
| 	public void updateAllData(ArrayList newPosList, ArrayList newTaskList) { | ||||
| // 同步Activity最新缓存数据(容错处理:避免接收null导致空指针) | ||||
| 		this.mCachedPositionList = (newPosList != null) ? newPosList : new ArrayList(); | ||||
| 		this.mCachedTaskList = (newTaskList != null) ? newTaskList : new ArrayList();// 刷新本地辅助缓存(确保映射与最新数据同步) | ||||
| 		refreshPositionTaskMap(); | ||||
| // 通知RecyclerView刷新所有项 | ||||
| 		mPosDistanceViewMap.clear(); // 清空旧距离控件缓存,避免引用失效控件// 通知RecyclerView全量刷新(数据已同步,更新UI显示) | ||||
| 		notifyDataSetChanged(); | ||||
| 		LogUtils.d(TAG, "全量更新数据完成:当前位置数=" + mCachedPositionList.size() + ",任务数=" + mCachedTaskList.size()); | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 隐藏软键盘(编辑完成后调用,提升用户体验) | ||||
| 	 - 局部更新距离UI(仅更新指定位置的距离显示,避免全量刷新卡顿) | ||||
| 	 - (Activity同步服务计算的最新距离后调用,精准更新受影响的位置) | ||||
| 	 */ | ||||
| 	public void updateSinglePositionDistance(String positionId) { | ||||
| // 校验参数:位置ID无效或控件未缓存时,直接返回 | ||||
| 		if (positionId == null || positionId.isEmpty() || !mPosDistanceViewMap.containsKey(positionId)) { | ||||
| 			LogUtils.w(TAG, "局部更新距离失败:位置ID无效或距离控件未缓存(ID=" + positionId + ")"); | ||||
| 			return; | ||||
| 		}// 从Activity缓存数据中获取最新位置模型(确保距离值是最新的) | ||||
| 		PositionModel latestPos = null; | ||||
| 		for (PositionModel pos : mCachedPositionList) { | ||||
| 			if (positionId.equals(pos.getPositionId())) { | ||||
| 				latestPos = pos; | ||||
| 				break; | ||||
| 			} | ||||
| 		}// 用最新距离值更新UI(直接操作缓存的距离控件,无需刷新整个项) | ||||
| 		if (latestPos != null) { | ||||
| 			updateDistanceDisplay(mPosDistanceViewMap.get(positionId), latestPos); | ||||
| 			LogUtils.d(TAG, "局部更新距离完成:位置ID=" + positionId + ",最新距离=" + latestPos.getRealPositionDistance() + "米"); | ||||
| 		} else { | ||||
| 			LogUtils.w(TAG, "局部更新距离失败:未在Activity缓存中找到位置ID=" + positionId); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 隐藏软键盘(编辑完成后调用,提升用户体验,避免键盘遮挡) | ||||
| 	 */ | ||||
| 	private void hideSoftKeyboard(View view) { | ||||
| 		if (mContext == null || view == null) return;InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); | ||||
| 		if (mContext == null || view == null) return; | ||||
| 		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); | ||||
| 		if (imm != null) { | ||||
| 			imm.hideSoftInputFromWindow(view.getWindowToken(), 0); | ||||
| 			imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏软键盘 | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 释放资源(Activity 销毁时调用,避免内存泄漏) | ||||
| 	 - 释放资源(Activity销毁时调用,彻底避免内存泄漏) | ||||
| 	 */ | ||||
| 	public void release() { | ||||
| // 清空本地缓存 | ||||
| 		mPosIdToIndexMap.clear(); | ||||
| // 清空本地辅助缓存(解除控件、数据映射引用) | ||||
| 		mPosToTasksMap.clear(); | ||||
| 		mPosDistanceViewMap.clear(); | ||||
| // 告诉服务清空可见位置(停止计算距离) | ||||
| 		if (mService != null) { | ||||
| 			mService.clearVisibleDistanceViews(); | ||||
| 		} | ||||
| // 置空回调(避免Activity内存泄漏) | ||||
| // 置空回调实例(避免持有Activity引用导致内存泄漏) | ||||
| 		mOnDeleteListener = null; | ||||
| 		mOnSavePosListener = null; | ||||
| 		mOnSaveTaskListener = null; | ||||
| 		LogUtils.d("PositionAdapter", "资源已释放"); | ||||
| // 置空数据源引用(帮助GC回收,避免残留数据占用内存) | ||||
| 		mCachedPositionList = null; | ||||
| 		mCachedTaskList = null; | ||||
| 		LogUtils.d(TAG, "Adapter资源已完全释放"); | ||||
| 	} | ||||
|  | ||||
| // ========================================================================= | ||||
| // 8. 回调设置方法(Activity 调用此方法设置回调) | ||||
| // 回调设置方法(LocationActivity调用,绑定交互逻辑,无冗余参数) | ||||
| // ========================================================================= | ||||
| 	public void setOnDeleteClickListener(OnDeleteClickListener listener) { | ||||
| 		this.mOnDeleteListener = listener; | ||||
| @@ -619,60 +505,55 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde | ||||
| 	} | ||||
|  | ||||
| // ========================================================================= | ||||
| // 9. 视图Holder类(静态内部类,避免内存泄漏) | ||||
| // 视图Holder类(静态内部类,不持有外部引用,彻底避免内存泄漏) | ||||
| // ========================================================================= | ||||
| 	/** | ||||
|  | ||||
| 	 - 简单视图Holder(仅显示数据,无编辑控件) | ||||
| 	 - 简单视图Holder(仅显示数据,对应布局:item_position_simple.xml) | ||||
| 	 */ | ||||
| 	public static class SimpleViewHolder extends RecyclerView.ViewHolder { | ||||
| 		TextView tvSimpleLon;   // 经度 | ||||
| 		TextView tvSimpleLat;   // 纬度 | ||||
| 		TextView tvSimpleMemo;  // 备注 | ||||
| 		TextView tvSimpleDistance; // 实时距离 | ||||
| 		TextView tvSimpleLon;     // 经度显示控件 | ||||
| 		TextView tvSimpleLat;     // 纬度显示控件 | ||||
| 		TextView tvSimpleMemo;    // 备注显示控件 | ||||
| 		TextView tvSimpleDistance;// 实时距离显示控件 | ||||
| 		public SimpleViewHolder(View itemView) { | ||||
| 			super(itemView); | ||||
| // 绑定布局控件(对应 item_position_simple.xml 中的ID) | ||||
| 			tvSimpleLon = (TextView) itemView.findViewById(R.id.tv_simple_longitude); | ||||
| 			tvSimpleLat = (TextView) itemView.findViewById(R.id.tv_simple_latitude); | ||||
| 			tvSimpleMemo = (TextView) itemView.findViewById(R.id.tv_simple_memo); | ||||
| 			tvSimpleDistance = (TextView) itemView.findViewById(R.id.tv_simple_distance); | ||||
| 		} | ||||
| 		super(itemView); | ||||
| // 绑定布局控件(与XML中ID严格对应,避免运行时空指针) | ||||
| 		tvSimpleLon = (TextView) itemView.findViewById(R.id.tv_simple_longitude); | ||||
| 		tvSimpleLat = (TextView) itemView.findViewById(R.id.tv_simple_latitude); | ||||
| 		tvSimpleMemo = (TextView) itemView.findViewById(R.id.tv_simple_memo); | ||||
| 		tvSimpleDistance = (TextView) itemView.findViewById(R.id.tv_simple_distance); | ||||
| 	} | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
|  | ||||
| 	 - 编辑视图Holder(含编辑控件、按钮等) | ||||
| 	 - 编辑视图Holder(含编辑控件+功能按钮,对应布局:item_position_edit.xml) | ||||
| 	 */ | ||||
| 	public static class EditViewHolder extends RecyclerView.ViewHolder { | ||||
| 		TextView tvEditLon;     // 经度 | ||||
| 		TextView tvEditLat;     // 纬度 | ||||
| 		EditText etEditMemo;    // 备注编辑框 | ||||
| 		TextView tvEditDistance;// 实时距离 | ||||
| 		RadioGroup rgDistanceSwitch; // 距离开关(启用/禁用) | ||||
| 		RadioButton rbEnable;   // 启用距离 | ||||
| 		RadioButton rbDisable;  // 禁用距离 | ||||
| 		Button btnCancel;       // 取消编辑 | ||||
| 		Button btnDelete;       // 删除位置 | ||||
| 		Button btnSave;         // 保存位置 | ||||
| 		Button btnAddTask;      // 新增任务 | ||||
| 		TextView tvTaskCount;   // 任务数量显示(示例用,实际替换为任务列表) | ||||
| 		TextView tvEditLon;       // 经度显示控件(不可编辑) | ||||
| 		TextView tvEditLat;       // 纬度显示控件(不可编辑) | ||||
| 		EditText etEditMemo;      // 备注编辑控件 | ||||
| 		TextView tvEditDistance;  // 实时距离显示控件 | ||||
| 		RadioGroup rgDistanceSwitch; // 距离启用/禁用开关组 | ||||
| 		Button btnCancel;         // 取消编辑按钮 | ||||
| 		Button btnDelete;         // 删除位置按钮 | ||||
| 		Button btnSave;           // 保存位置按钮 | ||||
| 		Button btnAddTask;        // 新增任务按钮 | ||||
| 		TextView tvTaskCount;     // 任务数量显示控件(简化设计) | ||||
| 		public EditViewHolder(View itemView) { | ||||
| 			super(itemView); | ||||
| // 绑定布局控件(对应 item_position_edit.xml 中的ID) | ||||
| 			tvEditLon = (TextView) itemView.findViewById(R.id.tv_edit_longitude); | ||||
| 			tvEditLat = (TextView) itemView.findViewById(R.id.tv_edit_latitude); | ||||
| 			etEditMemo = (EditText) itemView.findViewById(R.id.et_edit_memo); | ||||
| 			tvEditDistance = (TextView) itemView.findViewById(R.id.tv_edit_distance); | ||||
| 			rgDistanceSwitch = (RadioGroup) itemView.findViewById(R.id.rg_distance_switch); | ||||
| 			rbEnable = (RadioButton) itemView.findViewById(R.id.rb_distance_enable); | ||||
| 			rbDisable = (RadioButton) itemView.findViewById(R.id.rb_distance_disable); | ||||
| 			btnCancel = (Button) itemView.findViewById(R.id.btn_edit_cancel); | ||||
| 			btnDelete = (Button) itemView.findViewById(R.id.btn_edit_delete); | ||||
| 			btnSave = (Button) itemView.findViewById(R.id.btn_edit_save); | ||||
| 			btnAddTask = (Button) itemView.findViewById(R.id.btn_add_task); | ||||
| 			tvTaskCount = (TextView) itemView.findViewById(R.id.tv_task_count); | ||||
| 		} | ||||
| 		super(itemView); | ||||
| // 绑定布局控件(与XML中ID严格对应,避免运行时空指针) | ||||
| 		tvEditLon = (TextView) itemView.findViewById(R.id.tv_edit_longitude); | ||||
| 		tvEditLat = (TextView) itemView.findViewById(R.id.tv_edit_latitude); | ||||
| 		etEditMemo = (EditText) itemView.findViewById(R.id.et_edit_memo); | ||||
| 		tvEditDistance = (TextView) itemView.findViewById(R.id.tv_edit_distance); | ||||
| 		rgDistanceSwitch = (RadioGroup) itemView.findViewById(R.id.rg_distance_switch); | ||||
| 		btnCancel = (Button) itemView.findViewById(R.id.btn_edit_cancel); | ||||
| 		btnDelete = (Button) itemView.findViewById(R.id.btn_edit_delete); | ||||
| 		btnSave = (Button) itemView.findViewById(R.id.btn_edit_save); | ||||
| 		btnAddTask = (Button) itemView.findViewById(R.id.btn_add_task); | ||||
| 		tvTaskCount = (TextView) itemView.findViewById(R.id.tv_task_count); | ||||
| 	} | ||||
| 	} | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -14,18 +14,22 @@ public class AppConfigsModel extends BaseBean { | ||||
|      | ||||
|     public static final String TAG = "AppConfigsModel"; | ||||
| 	 | ||||
| 	boolean isEnableDistanceRefreshService = false; | ||||
| 	boolean isEnableMainService; | ||||
|  | ||||
| 	public AppConfigsModel(boolean isEnableDistanceRefreshService) { | ||||
| 		this.isEnableDistanceRefreshService = isEnableDistanceRefreshService; | ||||
| 	public AppConfigsModel(boolean isEnableMainService) { | ||||
| 		this.isEnableMainService = isEnableMainService; | ||||
| 	} | ||||
| 	 | ||||
| 	public void setIsEnableDistanceRefreshService(boolean isEnableDistanceRefreshService) { | ||||
| 		this.isEnableDistanceRefreshService = isEnableDistanceRefreshService; | ||||
| 	public AppConfigsModel() { | ||||
| 		this.isEnableMainService = false; | ||||
| 	} | ||||
|  | ||||
| 	public boolean isEnableDistanceRefreshService() { | ||||
| 		return isEnableDistanceRefreshService; | ||||
| 	public void setIsEnableMainService(boolean isEnableMainService) { | ||||
| 		this.isEnableMainService = isEnableMainService; | ||||
| 	} | ||||
|  | ||||
| 	public boolean isEnableMainService() { | ||||
| 		return isEnableMainService; | ||||
| 	} | ||||
|      | ||||
|     @Override | ||||
| @@ -37,7 +41,7 @@ public class AppConfigsModel extends BaseBean { | ||||
| 	@Override | ||||
| 	public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException { | ||||
| 		super.writeThisToJsonWriter(jsonWriter); | ||||
| 		jsonWriter.name("isEnableDistanceRefreshService").value(isEnableDistanceRefreshService()); | ||||
| 		jsonWriter.name("isEnableDistanceRefreshService").value(isEnableMainService()); | ||||
| 	} | ||||
|  | ||||
| 	// JSON反序列化(加载位置数据,校验字段) | ||||
| @@ -47,7 +51,7 @@ public class AppConfigsModel extends BaseBean { | ||||
| 			return true;  | ||||
| 		} else { | ||||
| 			if (name.equals("isEnableDistanceRefreshService")) { | ||||
| 				setIsEnableDistanceRefreshService(jsonReader.nextBoolean()); | ||||
| 				setIsEnableMainService(jsonReader.nextBoolean()); | ||||
| 			} else { | ||||
| 				return false; | ||||
| 			} | ||||
|   | ||||
| @@ -0,0 +1,95 @@ | ||||
| package cc.winboll.studio.positions.services; | ||||
|  | ||||
| /** | ||||
|  * @Author ZhanGSKen<zhangsken@qq.com> | ||||
|  * @Date 2024/07/19 14:30:57 | ||||
|  * @Describe 应用主要服务组件类守护进程服务组件类 | ||||
|  */ | ||||
| import android.app.Service; | ||||
| import android.content.ComponentName; | ||||
| import android.content.Context; | ||||
| import android.content.Intent; | ||||
| import android.content.ServiceConnection; | ||||
| import android.os.IBinder; | ||||
| import cc.winboll.studio.positions.services.MainService; | ||||
| import cc.winboll.studio.positions.utils.AppConfigsUtil; | ||||
| import cc.winboll.studio.positions.utils.ServiceUtil; | ||||
|  | ||||
| public class AssistantService extends Service { | ||||
|  | ||||
|     public final static String TAG = "AssistantService"; | ||||
|  | ||||
|     MyServiceConnection mMyServiceConnection; | ||||
|     volatile boolean mIsServiceRunning; | ||||
|     AppConfigsUtil mAppConfigsUtil; | ||||
|  | ||||
|     @Override | ||||
|     public IBinder onBind(Intent intent) { | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void onCreate() { | ||||
|         super.onCreate(); | ||||
|         mAppConfigsUtil = AppConfigsUtil.getInstance(this); | ||||
|         if (mMyServiceConnection == null) { | ||||
|             mMyServiceConnection = new MyServiceConnection(); | ||||
|         } | ||||
|         // 设置运行参数 | ||||
|         mIsServiceRunning = false; | ||||
|         run(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int onStartCommand(Intent intent, int flags, int startId) { | ||||
|         run(); | ||||
|         return START_STICKY; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void onDestroy() { | ||||
|         mIsServiceRunning = false; | ||||
|         super.onDestroy(); | ||||
|     } | ||||
|  | ||||
|     // | ||||
|     // 运行服务内容 | ||||
|     // | ||||
|     void run() { | ||||
|         if (mAppConfigsUtil.isEnableMainService(true)) { | ||||
|             if (mIsServiceRunning == false) { | ||||
|                 // 设置运行状态 | ||||
|                 mIsServiceRunning = true; | ||||
|                 // 唤醒和绑定主进程 | ||||
|                 wakeupAndBindMain(); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     // | ||||
|     // 唤醒和绑定主进程 | ||||
|     // | ||||
|     void wakeupAndBindMain() { | ||||
|         if (ServiceUtil.isServiceAlive(getApplicationContext(), MainService.class.getName()) == false) { | ||||
|             startForegroundService(new Intent(AssistantService.this, MainService.class)); | ||||
|         } | ||||
|  | ||||
|         bindService(new Intent(AssistantService.this, MainService.class), mMyServiceConnection, Context.BIND_IMPORTANT); | ||||
|     } | ||||
|  | ||||
|     // | ||||
|     // 主进程与守护进程连接时需要用到此类 | ||||
|     // | ||||
|     class MyServiceConnection implements ServiceConnection { | ||||
|         @Override | ||||
|         public void onServiceConnected(ComponentName name, IBinder service) { | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public void onServiceDisconnected(ComponentName name) { | ||||
|             if (mAppConfigsUtil.isEnableMainService(true)) { | ||||
|                 wakeupAndBindMain(); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							| @@ -0,0 +1,125 @@ | ||||
| package cc.winboll.studio.positions.services; | ||||
|  | ||||
| /** | ||||
|  * @Author ZhanGSKen<zhangsken@qq.com> | ||||
|  * @Date 2024/07/19 14:30:57 | ||||
|  * @Describe 应用主要服务组件类 | ||||
|  */ | ||||
| import android.app.Notification; | ||||
| import android.app.Service; | ||||
| import android.content.ComponentName; | ||||
| import android.content.Context; | ||||
| import android.content.Intent; | ||||
| import android.content.IntentFilter; | ||||
| import android.content.ServiceConnection; | ||||
| import android.os.IBinder; | ||||
| import cc.winboll.studio.libappbase.LogUtils; | ||||
| import cc.winboll.studio.positions.R; | ||||
| import com.hjq.toast.ToastUtils; | ||||
| import cc.winboll.studio.positions.models.AppConfigsModel; | ||||
| import cc.winboll.studio.positions.utils.AppConfigsUtil; | ||||
| import cc.winboll.studio.positions.utils.ServiceUtil; | ||||
| import cc.winboll.studio.positions.utils.NotificationUtil; | ||||
|  | ||||
| public class MainService extends Service { | ||||
|  | ||||
|     public static final String TAG = "MainService"; | ||||
|      | ||||
|     //MyBinder mMyBinder; | ||||
|     MyServiceConnection mMyServiceConnection; | ||||
|     volatile static boolean _mIsServiceAlive; | ||||
|     AppConfigsUtil mAppConfigsUtil; | ||||
|  | ||||
|     @Override | ||||
|     public IBinder onBind(Intent intent) { | ||||
|         //return mMyBinder; | ||||
|         return null; | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void onCreate() { | ||||
|         LogUtils.d(TAG, "onCreate"); | ||||
|         super.onCreate(); | ||||
|         _mIsServiceAlive = false; | ||||
|         mAppConfigsUtil = AppConfigsUtil.getInstance(this); | ||||
|  | ||||
|         //mMyBinder = new MyBinder(); | ||||
|         if (mMyServiceConnection == null) { | ||||
|             mMyServiceConnection = new MyServiceConnection(); | ||||
|         } | ||||
|  | ||||
|         // 运行服务内容 | ||||
|         run(); | ||||
|  | ||||
|     } | ||||
|  | ||||
|     private void run() { | ||||
|         if (mAppConfigsUtil.isEnableMainService(true)) { | ||||
|             if (_mIsServiceAlive == false) { | ||||
|                 // 设置运行状态 | ||||
|                 _mIsServiceAlive = true; | ||||
|                 //LogUtils.d(TAG, "_mIsServiceAlive set to true."); | ||||
|  | ||||
|                 // 唤醒守护进程 | ||||
|                 wakeupAndBindAssistant(); | ||||
|  | ||||
|                 // 运行其它服务内容 | ||||
| 				 | ||||
|                 // 显示前台通知栏 | ||||
| 				String initialStatus = "[ Positions ] is in Service."; | ||||
|                 // 调用NotificationUtils创建前台通知(传入动态状态文本) | ||||
| 				NotificationUtil.createForegroundServiceNotification(this, initialStatus); | ||||
| 				// 启动前台服务(与NotificationUtils通知ID保持一致) | ||||
| 				startForeground(NotificationUtil.FOREGROUND_SERVICE_NOTIFICATION_ID, | ||||
| 								NotificationUtil.createForegroundServiceNotification(this, initialStatus)); | ||||
| 				 | ||||
|                 ToastUtils.show(initialStatus); | ||||
|                 LogUtils.i(TAG, initialStatus); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     public interface SMSListener { | ||||
|         void speakMessage(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public void onDestroy() { | ||||
|         super.onDestroy(); | ||||
|     } | ||||
|  | ||||
|     @Override | ||||
|     public int onStartCommand(Intent intent, int flags, int startId) { | ||||
|         //return super.onStartCommand(intent, flags, startId); | ||||
|         run(); | ||||
|         return mAppConfigsUtil.isEnableMainService(true) ? Service.START_STICKY: super.onStartCommand(intent, flags, startId); | ||||
|     } | ||||
|  | ||||
|     // 主进程与守护进程连接时需要用到此类 | ||||
|     // | ||||
|     private class MyServiceConnection implements ServiceConnection { | ||||
|         @Override | ||||
|         public void onServiceConnected(ComponentName name, IBinder service) { | ||||
|             //LogUtils.d(TAG, "call onServiceConnected(...)"); | ||||
|         } | ||||
|  | ||||
|         @Override | ||||
|         public void onServiceDisconnected(ComponentName name) { | ||||
|             //LogUtils.d(TAG, "call onServiceConnected(...)"); | ||||
|             if (mAppConfigsUtil.isEnableMainService(true)) { | ||||
|                 // 唤醒守护进程 | ||||
|                 wakeupAndBindAssistant(); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     // 唤醒和绑定守护进程 | ||||
|     // | ||||
|     void wakeupAndBindAssistant() { | ||||
|         if (ServiceUtil.isServiceAlive(getApplicationContext(), AssistantService.class.getName()) == false) { | ||||
|             startService(new Intent(MainService.this, AssistantService.class)); | ||||
|             //LogUtils.d(TAG, "call wakeupAndBindAssistant() : Binding... AssistantService"); | ||||
|             bindService(new Intent(MainService.this, AssistantService.class), mMyServiceConnection, Context.BIND_IMPORTANT); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,65 @@ | ||||
| package cc.winboll.studio.positions.utils; | ||||
| import android.content.Context; | ||||
| import cc.winboll.studio.positions.models.AppConfigsModel; | ||||
|  | ||||
| /** | ||||
|  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> | ||||
|  * @Date 2025/10/01 12:15 | ||||
|  * @Describe AppConfigsUtils | ||||
|  */ | ||||
| public class AppConfigsUtil { | ||||
|  | ||||
|     public static final String TAG = "AppConfigsUtils"; | ||||
|  | ||||
|     // 1. 私有静态成员变量(volatile 防止指令重排,确保实例初始化完全) | ||||
|     private static volatile AppConfigsUtil sInstance; | ||||
| 	Context mContext; | ||||
| 	AppConfigsModel mAppConfigsModel; | ||||
|  | ||||
|     // 2. 私有构造方法(禁止外部 new 实例) | ||||
|     private AppConfigsUtil(Context context) { | ||||
|         // 可选:防止通过反射创建实例(增强单例安全性) | ||||
|         if (sInstance != null) { | ||||
|             throw new RuntimeException("禁止通过反射创建单例实例"); | ||||
|         } | ||||
| 		mContext = context; | ||||
| 		loadConfigs(); | ||||
|     } | ||||
|  | ||||
|     // 3. 公开静态方法(双重校验锁,获取唯一实例) | ||||
|     public static AppConfigsUtil getInstance(Context context) { | ||||
|         // 第一次校验:无锁,快速判断实例是否存在(提升性能) | ||||
|         if (sInstance == null) { | ||||
|             // 加锁:确保同一时间只有一个线程进入初始化逻辑 | ||||
|             synchronized (AppConfigsUtil.class) { | ||||
|                 // 第二次校验:防止多线程并发时重复创建实例(线程安全) | ||||
|                 if (sInstance == null) { | ||||
|                     sInstance = new AppConfigsUtil(context); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|         return sInstance; | ||||
|     } | ||||
|  | ||||
| 	void loadConfigs() { | ||||
| 		mAppConfigsModel = AppConfigsModel.loadBean(mContext, AppConfigsModel.class); | ||||
| 	} | ||||
|  | ||||
| 	void saveConfigs() { | ||||
| 		AppConfigsModel.saveBean(mContext, mAppConfigsModel); | ||||
| 	} | ||||
|  | ||||
| 	public boolean isEnableMainService(boolean isReloadConfigs) { | ||||
| 		if (isReloadConfigs) { | ||||
| 			loadConfigs(); | ||||
| 		} | ||||
| 		 | ||||
| 		return mAppConfigsModel.isEnableMainService(); | ||||
| 	} | ||||
|  | ||||
| 	public void setIsEnableMainService(boolean isEnableMainService) { | ||||
| 		mAppConfigsModel.setIsEnableMainService(isEnableMainService); | ||||
| 		saveConfigs(); | ||||
| 	} | ||||
| } | ||||
|  | ||||
| @@ -0,0 +1,185 @@ | ||||
| package cc.winboll.studio.positions.utils; | ||||
|  | ||||
| /** | ||||
|  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> | ||||
|  * @Date 2025/09/30 16:09 | ||||
|  * @Describe NotificationUtils | ||||
|  */ | ||||
| import android.app.Notification; | ||||
| import android.app.NotificationChannel; | ||||
| import android.app.NotificationManager; | ||||
| import android.app.PendingIntent; | ||||
| import android.content.Context; | ||||
| import android.content.Intent; | ||||
| import android.os.Build; | ||||
| import androidx.core.app.NotificationCompat; | ||||
| import cc.winboll.studio.positions.R; | ||||
| import cc.winboll.studio.positions.activities.LocationActivity; // 引入你的前台服务类 | ||||
|  | ||||
| /** | ||||
|  * 通知栏工具类:专注于任务相关通知的显示与点击跳转 + 前台服务通知管理 | ||||
|  * 核心功能: | ||||
|  * 1. 显示任务描述通知,点击后携带positionId/taskId跳转到LocationActivity | ||||
|  * 2. 创建前台服务通知(用于DistanceRefreshService保活,符合系统前台服务规范) | ||||
|  */ | ||||
| public class NotificationUtil { | ||||
| 	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_NAME = "任务通知"; | ||||
| 	// 2. 前台服务通知新增常量(独立渠道,避免与普通任务通知混淆) | ||||
| 	private static final String FOREGROUND_SERVICE_CHANNEL_ID = "foreground_location_service_channel_02"; | ||||
| 	private static final String FOREGROUND_SERVICE_CHANNEL_NAME = "位置服务"; | ||||
| 	public static final int FOREGROUND_SERVICE_NOTIFICATION_ID = 10086; // 固定ID(前台服务通知无需动态生成) | ||||
|  | ||||
| 	// ---------------------- 原有功能:任务通知(不变) ---------------------- | ||||
| 	private static int getNotificationId(String taskId) { | ||||
| 		return taskId.hashCode() & 0xFFFFFF; | ||||
| 	} | ||||
|  | ||||
| 	public static void show(Context context, String taskId, String positionId, String taskDescription) { | ||||
| 		if (context == null || taskId == null || positionId == null) { | ||||
| 			return; | ||||
| 		} | ||||
|  | ||||
| 		NotificationManager notificationManager =  | ||||
| 			(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); | ||||
| 		if (notificationManager == null) { | ||||
| 			return; | ||||
| 		} | ||||
|  | ||||
| 		createNotificationChannel(notificationManager); | ||||
|  | ||||
| 		Intent jumpIntent = new Intent(context, LocationActivity.class); | ||||
| 		jumpIntent.putExtra("EXTRA_POSITION_ID", positionId); | ||||
| 		jumpIntent.putExtra("EXTRA_TASK_ID", taskId); | ||||
| 		jumpIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); | ||||
|  | ||||
| 		PendingIntent pendingIntent = PendingIntent.getActivity( | ||||
| 			context, | ||||
| 			getNotificationId(taskId), | ||||
| 			jumpIntent, | ||||
| 			Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ?  | ||||
| 			PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT :  | ||||
| 			PendingIntent.FLAG_UPDATE_CURRENT | ||||
| 		); | ||||
|  | ||||
| 		Notification notification = new NotificationCompat.Builder(context, TASK_NOTIFICATION_CHANNEL_ID) | ||||
| 			.setSmallIcon(R.mipmap.ic_launcher) | ||||
| 			.setContentTitle("任务提醒") | ||||
| 			.setContentText(taskDescription) | ||||
| 			.setContentIntent(pendingIntent) | ||||
| 			.setAutoCancel(true) | ||||
| 			.setPriority(NotificationCompat.PRIORITY_DEFAULT) | ||||
| 			.setDefaults(NotificationCompat.DEFAULT_SOUND) | ||||
| 			.build(); | ||||
|  | ||||
| 		notificationManager.notify(getNotificationId(taskId), notification); | ||||
| 	} | ||||
|  | ||||
| 	private static void createNotificationChannel(NotificationManager notificationManager) { | ||||
| 		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { | ||||
| 			// 原有:任务通知渠道 | ||||
| 			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,避免频繁打扰用户) | ||||
| 			NotificationChannel foregroundChannel = new NotificationChannel( | ||||
| 				FOREGROUND_SERVICE_CHANNEL_ID, | ||||
| 				FOREGROUND_SERVICE_CHANNEL_NAME, | ||||
| 				NotificationManager.IMPORTANCE_LOW // 仅通知栏显示,无提示音/震动,符合后台服务低打扰需求 | ||||
| 			); | ||||
| 			foregroundChannel.setDescription("位置服务运行中,用于后台持续获取GPS数据,关闭会影响定位功能"); // 明确告知用户服务作用 | ||||
| 			foregroundChannel.enableVibration(false); // 前台服务通知不震动(避免打扰) | ||||
| 			foregroundChannel.setSound(null, null); // 关闭提示音(低打扰) | ||||
|  | ||||
| 			// 注册两个渠道(任务+前台服务) | ||||
| 			notificationManager.createNotificationChannel(taskChannel); | ||||
| 			notificationManager.createNotificationChannel(foregroundChannel); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	public static void cancel(Context context, String taskId) { | ||||
| 		if (context == null || taskId == null) { | ||||
| 			return; | ||||
| 		} | ||||
| 		NotificationManager notificationManager =  | ||||
| 			(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); | ||||
| 		if (notificationManager != null) { | ||||
| 			notificationManager.cancel(getNotificationId(taskId)); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	// ---------------------- 新增核心功能:创建前台服务通知(供DistanceRefreshService调用) ---------------------- | ||||
| 	/** | ||||
| 	 * 创建前台服务通知(符合Android前台服务规范,用于启动/保活DistanceRefreshService) | ||||
| 	 * @param context 服务上下文(直接传入DistanceRefreshService的this即可) | ||||
| 	 * @param serviceStatus 服务状态文本(如“正在后台获取GPS位置...”,动态展示服务状态) | ||||
| 	 * @return 可直接用于startForeground()的Notification对象 | ||||
| 	 */ | ||||
| 	public static Notification createForegroundServiceNotification(Context context, String serviceStatus) { | ||||
| 		// 安全校验:上下文非空(避免服务中调用时的空指针) | ||||
| 		if (context == null) { | ||||
| 			throw new IllegalArgumentException("Context cannot be null for foreground service notification"); | ||||
| 		} | ||||
|  | ||||
| 		// 步骤1:初始化通知管理器(复用已有逻辑,确保渠道已创建) | ||||
| 		NotificationManager notificationManager =  | ||||
| 			(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); | ||||
| 		if (notificationManager != null) { | ||||
| 			createNotificationChannel(notificationManager); // 确保前台服务渠道已注册 | ||||
| 		} | ||||
|  | ||||
| 		// 步骤2:构建“点击通知跳转至位置管理页”的Intent(用户点击通知可进入功能页) | ||||
| 		Intent jumpIntent = new Intent(context, LocationActivity.class); | ||||
| 		jumpIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // 避免创建重复页面 | ||||
|  | ||||
| 		// 步骤3:创建PendingIntent(授权系统在用户点击时执行跳转) | ||||
| 		PendingIntent pendingIntent = PendingIntent.getActivity( | ||||
| 			context, | ||||
| 			FOREGROUND_SERVICE_NOTIFICATION_ID, // 请求码与通知ID一致,确保唯一 | ||||
| 			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) | ||||
| 			.setSmallIcon(R.mipmap.ic_launcher) // 必须设置(系统强制要求,建议用应用图标) | ||||
| 			.setContentTitle("位置服务运行中") // 固定标题,用户快速识别服务类型 | ||||
| 			.setContentText(serviceStatus) // 动态内容(如“正在获取GPS位置”“已连续运行30分钟”) | ||||
| 			.setContentIntent(pendingIntent) // 点击跳转至功能页 | ||||
| 			.setOngoing(true) // 关键:设置为“不可手动清除”(仅服务停止时能取消,符合前台服务规范) | ||||
| 			.setPriority(NotificationCompat.PRIORITY_LOW) // 低优先级:不弹窗、不抢占通知栏焦点 | ||||
| 			.setDefaults(NotificationCompat.DEFAULT_SOUND) | ||||
| 			.build(); | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
| 	 * (配套工具方法)更新前台服务通知的状态文本(如GPS获取进度、运行时长) | ||||
| 	 * @param context 服务上下文 | ||||
| 	 * @param newServiceStatus 新的状态文本(如“已获取最新位置:北纬30.123°”) | ||||
| 	 */ | ||||
| 	public static void updateForegroundServiceStatus(Context context, String newServiceStatus) { | ||||
| 		if (context == null) { | ||||
| 			return; | ||||
| 		} | ||||
| 		// 重新创建通知(复用create方法,传入新状态文本) | ||||
| 		Notification updatedNotification = createForegroundServiceNotification(context, newServiceStatus); | ||||
| 		// 用相同ID更新通知(覆盖旧通知,实现状态刷新) | ||||
| 		NotificationManager notificationManager =  | ||||
| 			(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); | ||||
| 		if (notificationManager != null) { | ||||
| 			notificationManager.notify(FOREGROUND_SERVICE_NOTIFICATION_ID, updatedNotification); | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
|  | ||||
| @@ -1,130 +0,0 @@ | ||||
| package cc.winboll.studio.positions.utils; | ||||
|  | ||||
| /** | ||||
|  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> | ||||
|  * @Date 2025/09/30 16:09 | ||||
|  * @Describe NotificationUtils | ||||
|  */ | ||||
| import android.app.Notification; | ||||
| import android.app.NotificationChannel; | ||||
| import android.app.NotificationManager; | ||||
| import android.app.PendingIntent; | ||||
| import android.content.Context; | ||||
| import android.content.Intent; | ||||
| import android.os.Build; | ||||
| import androidx.core.app.NotificationCompat; | ||||
| import cc.winboll.studio.positions.R; | ||||
| import cc.winboll.studio.positions.activities.LocationActivity; // 替换为你实际的LocationActivity路径 | ||||
|  | ||||
| /** | ||||
|  * 通知栏工具类:专注于任务相关通知的显示与点击跳转 | ||||
|  * 核心功能:显示任务描述通知,点击后携带positionId/taskId跳转到LocationActivity | ||||
|  */ | ||||
| public class NotificationUtils { | ||||
| 	public static final String TAG = "NotificationUtils"; | ||||
| 	// 1. 通知渠道ID(适配Android O及以上,必须唯一) | ||||
| 	private static final String TASK_NOTIFICATION_CHANNEL_ID = "task_notification_channel_01"; | ||||
| 	// 2. 通知渠道名称(用户在系统设置中看到的名称) | ||||
| 	private static final String TASK_NOTIFICATION_CHANNEL_NAME = "任务通知"; | ||||
| 	// 3. 通知ID(确保每次显示通知的ID唯一,这里用taskId哈希值避免重复) | ||||
| 	private static int getNotificationId(String taskId) { | ||||
| 		// 用taskId生成唯一ID(避免不同任务通知相互覆盖) | ||||
| 		return taskId.hashCode() & 0xFFFFFF; // 限制ID在0-16777215范围内(系统推荐) | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
| 	 * 显示任务通知 | ||||
| 	 * @param context 上下文(如Activity/Fragment,确保非空) | ||||
| 	 * @param taskId 任务ID(用于跳转传递+生成唯一通知ID) | ||||
| 	 * @param positionId 位置ID(用于跳转传递给LocationActivity) | ||||
| 	 * @param taskDescription 通知显示内容(仅展示该文本给用户) | ||||
| 	 */ | ||||
| 	public static void show(Context context, String taskId, String positionId, String taskDescription) { | ||||
| 		// 安全校验:避免空指针(上下文/必要参数为空时不执行) | ||||
| 		if (context == null || taskId == null || positionId == null) { | ||||
| 			return; | ||||
| 		} | ||||
|  | ||||
| 		// 步骤1:初始化通知管理器(系统服务,负责发送/取消通知) | ||||
| 		NotificationManager notificationManager =  | ||||
| 			(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); | ||||
| 		if (notificationManager == null) { | ||||
| 			return; | ||||
| 		} | ||||
|  | ||||
| 		// 步骤2:创建通知渠道(Android O及以上必须,否则通知不显示) | ||||
| 		createNotificationChannel(notificationManager); | ||||
|  | ||||
| 		// 步骤3:构建“点击通知跳转”的Intent(携带positionId和taskId) | ||||
| 		Intent jumpIntent = new Intent(context, LocationActivity.class); | ||||
| 		// 传递参数:用Intent的Extra携带ID(键名建议定义为常量,避免拼写错误) | ||||
| 		jumpIntent.putExtra("EXTRA_POSITION_ID", positionId); | ||||
| 		jumpIntent.putExtra("EXTRA_TASK_ID", taskId); | ||||
| 		// 配置Intent:清除栈内旧Activity,确保跳转后是最新页面(根据需求调整) | ||||
| 		jumpIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); | ||||
|  | ||||
| 		// 步骤4:创建PendingIntent(授权系统在用户点击通知时执行jumpIntent) | ||||
| 		// 注意:PendingIntent.FLAG_UPDATE_CURRENT 确保参数更新时覆盖旧Intent | ||||
| 		PendingIntent pendingIntent = PendingIntent.getActivity( | ||||
| 			context, | ||||
| 			getNotificationId(taskId), // 请求码:与通知ID一致,确保唯一 | ||||
| 			jumpIntent, | ||||
| 			Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ?  | ||||
| 			PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT :  | ||||
| 			PendingIntent.FLAG_UPDATE_CURRENT | ||||
| 		); | ||||
|  | ||||
| 		// 步骤5:构建通知内容(仅显示taskDescription,样式简洁) | ||||
| 		Notification notification = new NotificationCompat.Builder(context, TASK_NOTIFICATION_CHANNEL_ID) | ||||
| 			.setSmallIcon(R.mipmap.ic_launcher) // 通知小图标(必须设置,建议用应用图标) | ||||
| 			.setContentTitle("任务提醒") // 通知标题(固定,用户快速识别通知类型) | ||||
| 			.setContentText(taskDescription) // 通知内容(仅显示传入的任务描述) | ||||
| 			.setContentIntent(pendingIntent) // 绑定点击跳转事件 | ||||
| 			.setAutoCancel(true) // 点击通知后自动消失(符合用户习惯) | ||||
| 			.setPriority(NotificationCompat.PRIORITY_DEFAULT) // 通知优先级(默认,不抢占焦点) | ||||
| 			.setDefaults(NotificationCompat.DEFAULT_SOUND) // 默认提示音(可选,根据需求关闭) | ||||
| 			.build(); | ||||
|  | ||||
| 		// 步骤6:发送通知(用唯一ID确保不同任务通知不覆盖) | ||||
| 		notificationManager.notify(getNotificationId(taskId), notification); | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
| 	 * 创建通知渠道(Android O/API 26及以上必须) | ||||
| 	 * 作用:用户可在系统设置中管理该渠道的通知(如关闭声音/屏蔽) | ||||
| 	 */ | ||||
| 	private static void createNotificationChannel(NotificationManager notificationManager) { | ||||
| 		// 仅在Android O及以上执行(低版本不需要渠道) | ||||
| 		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { | ||||
| 			// 配置渠道:重要性为“默认”(不弹窗,仅通知栏显示+提示音) | ||||
| 			NotificationChannel channel = new NotificationChannel( | ||||
| 				TASK_NOTIFICATION_CHANNEL_ID, | ||||
| 				TASK_NOTIFICATION_CHANNEL_NAME, | ||||
| 				NotificationManager.IMPORTANCE_DEFAULT | ||||
| 			); | ||||
| 			// 可选:配置渠道其他属性(根据需求调整) | ||||
| 			channel.setDescription("接收任务相关提醒,点击可查看任务详情"); // 渠道描述(系统设置中显示) | ||||
| 			channel.enableVibration(true); // 是否震动(默认开启,可关闭) | ||||
| 			channel.setVibrationPattern(new long[]{0, 300}); // 震动模式(0延迟,震动300ms) | ||||
|  | ||||
| 			// 注册渠道到系统(仅需注册一次,重复注册会覆盖旧配置) | ||||
| 			notificationManager.createNotificationChannel(channel); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
| 	 * (可选)取消指定任务的通知 | ||||
| 	 * 场景:任务完成后关闭已显示的通知(如bingo状态取消后) | ||||
| 	 */ | ||||
| 	public static void cancel(Context context, String taskId) { | ||||
| 		if (context == null || taskId == null) { | ||||
| 			return; | ||||
| 		} | ||||
| 		NotificationManager notificationManager =  | ||||
| 			(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); | ||||
| 		if (notificationManager != null) { | ||||
| 			notificationManager.cancel(getNotificationId(taskId)); | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
|  | ||||
| @@ -0,0 +1,34 @@ | ||||
| package cc.winboll.studio.positions.utils; | ||||
|  | ||||
| /** | ||||
|  * @Author ZhanGSKen<zhangsken@qq.com> | ||||
|  * @Date 2024/07/19 14:30:57 | ||||
|  * @Describe 应用服务组件工具类 | ||||
|  */ | ||||
| import android.app.ActivityManager; | ||||
| import android.content.Context; | ||||
| import java.util.List; | ||||
|  | ||||
| public class ServiceUtil { | ||||
|     public final static String TAG = "ServiceUtil"; | ||||
|  | ||||
|     public static boolean isServiceAlive(Context context, String szServiceName) { | ||||
|         // 获取Activity管理者对象 | ||||
|         ActivityManager manager = (ActivityManager) context | ||||
|             .getSystemService(Context.ACTIVITY_SERVICE); | ||||
|         // 获取正在运行的服务(此处设置最多取1000个) | ||||
|         List<ActivityManager.RunningServiceInfo> runningServices = manager | ||||
|             .getRunningServices(1000); | ||||
|         if (runningServices.size() <= 0) { | ||||
|             return false; | ||||
|         } | ||||
|         // 遍历,若存在名字和传入的serviceName的一致则说明存在 | ||||
|         for (ActivityManager.RunningServiceInfo runningServiceInfo : runningServices) { | ||||
|             if (runningServiceInfo.service.getClassName().equals(szServiceName)) { | ||||
|                 return true; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     } | ||||
| } | ||||
| @@ -6,7 +6,6 @@ | ||||
| 	android:layout_height="match_parent" | ||||
| 	android:orientation="vertical"> | ||||
|  | ||||
| 	<!-- 顶部 Toolbar --> | ||||
| 	<androidx.appcompat.widget.Toolbar | ||||
| 		android:id="@+id/toolbar" | ||||
| 		android:layout_width="match_parent" | ||||
| @@ -14,15 +13,13 @@ | ||||
| 		android:background="?attr/colorPrimary" | ||||
| 		android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/> | ||||
|  | ||||
| 	<!-- 服务控制开关 --> | ||||
| 	<androidx.appcompat.widget.SwitchCompat | ||||
| 	<Switch | ||||
| 		android:id="@+id/switch_service_control" | ||||
| 		android:layout_width="wrap_content" | ||||
| 		android:layout_height="wrap_content" | ||||
| 		android:layout_margin="16dp" | ||||
| 		android:text="位置服务"/> | ||||
| 		android:text="主要服务开关" | ||||
| 		android:layout_width="match_parent" | ||||
| 		android:layout_height="wrap_content"/> | ||||
|  | ||||
| 	<!-- 跳转按钮:位置管理页 --> | ||||
| 	<Button | ||||
| 		android:layout_width="match_parent" | ||||
| 		android:layout_height="wrap_content" | ||||
| @@ -30,7 +27,6 @@ | ||||
| 		android:onClick="onPositions" | ||||
| 		android:text="进入位置管理"/> | ||||
|  | ||||
| 	<!-- 跳转按钮:日志页 --> | ||||
| 	<Button | ||||
| 		android:layout_width="match_parent" | ||||
| 		android:layout_height="wrap_content" | ||||
| @@ -38,6 +34,5 @@ | ||||
| 		android:onClick="onLog" | ||||
| 		android:text="查看操作日志"/> | ||||
|  | ||||
|  | ||||
| </LinearLayout> | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user
	 ZhanGSKen
					ZhanGSKen