完成主要服务开关与启动
This commit is contained in:
		| @@ -1,8 +1,8 @@ | |||||||
| #Created by .winboll/winboll_app_build.gradle | #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 | stageCount=4 | ||||||
| libraryProject= | libraryProject= | ||||||
| baseVersion=15.0 | baseVersion=15.0 | ||||||
| publishVersion=15.0.3 | publishVersion=15.0.3 | ||||||
| buildCount=19 | buildCount=55 | ||||||
| baseBetaVersion=15.0.4 | baseBetaVersion=15.0.4 | ||||||
|   | |||||||
| @@ -3,6 +3,9 @@ | |||||||
|     xmlns:android="http://schemas.android.com/apk/res/android" |     xmlns:android="http://schemas.android.com/apk/res/android" | ||||||
|     package="cc.winboll.studio.positions"> |     package="cc.winboll.studio.positions"> | ||||||
|  |  | ||||||
|  |     <!-- 前台服务权限(可选,提升后台定位稳定性,避免服务被回收) --> | ||||||
|  |     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> | ||||||
|  |  | ||||||
|     <!-- 只能在前台获取精确的位置信息 --> |     <!-- 只能在前台获取精确的位置信息 --> | ||||||
|     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> |     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> | ||||||
|  |  | ||||||
| @@ -53,8 +56,11 @@ | |||||||
|             android:name="com.google.android.gms.version" |             android:name="com.google.android.gms.version" | ||||||
|             android:value="@integer/google_play_services_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> |     </application> | ||||||
|  |  | ||||||
| </manifest> | </manifest> | ||||||
| @@ -4,21 +4,22 @@ import android.content.ComponentName; | |||||||
| import android.content.Context; | import android.content.Context; | ||||||
| import android.content.Intent; | import android.content.Intent; | ||||||
| import android.content.ServiceConnection; | import android.content.ServiceConnection; | ||||||
| import android.content.SharedPreferences; | import android.content.pm.PackageManager; | ||||||
|  | import android.os.Build; | ||||||
| import android.os.Bundle; | import android.os.Bundle; | ||||||
| import android.os.IBinder; | import android.os.IBinder; | ||||||
| import android.view.View; | import android.view.View; | ||||||
| import android.widget.CompoundButton; | import android.widget.CompoundButton; | ||||||
|  | import android.widget.Switch; | ||||||
| import androidx.appcompat.app.AppCompatActivity; | import androidx.appcompat.app.AppCompatActivity; | ||||||
| import androidx.appcompat.widget.SwitchCompat; |  | ||||||
| import androidx.appcompat.widget.Toolbar; | import androidx.appcompat.widget.Toolbar; | ||||||
|  |  | ||||||
| import cc.winboll.studio.libappbase.LogActivity; | import cc.winboll.studio.libappbase.LogActivity; | ||||||
|  | import cc.winboll.studio.libappbase.LogUtils; | ||||||
| import cc.winboll.studio.positions.activities.LocationActivity; | import cc.winboll.studio.positions.activities.LocationActivity; | ||||||
| import cc.winboll.studio.positions.services.DistanceRefreshService; | 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 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 class MainActivity extends AppCompatActivity { | ||||||
|     public static final String TAG = "MainActivity"; |     public static final String TAG = "MainActivity"; | ||||||
|  |     // 位置权限请求码(自定义唯一标识) | ||||||
|  |     private static final int REQUEST_LOCATION_PERMISSIONS = 1001; | ||||||
|  |  | ||||||
|     // UI 控件:服务控制开关、顶部工具栏 |     // UI 控件:服务控制开关、顶部工具栏 | ||||||
|     private SwitchCompat mServiceSwitch; |     private Switch mServiceSwitch; | ||||||
|     private Toolbar mToolbar; |     private Toolbar mToolbar; | ||||||
|     // 服务相关:服务实例、绑定状态标记 |     // 服务相关:服务实例、绑定状态标记 | ||||||
|     private DistanceRefreshService mDistanceService; |     private DistanceRefreshService mDistanceService; | ||||||
| @@ -47,8 +50,6 @@ public class MainActivity extends AppCompatActivity { | |||||||
|             DistanceRefreshService.DistanceBinder binder = (DistanceRefreshService.DistanceBinder) service; |             DistanceRefreshService.DistanceBinder binder = (DistanceRefreshService.DistanceBinder) service; | ||||||
|             mDistanceService = binder.getService(); |             mDistanceService = binder.getService(); | ||||||
|             isServiceBound = true; |             isServiceBound = true; | ||||||
|             // 绑定后立即同步开关状态,避免UI与服务实际状态不一致 |  | ||||||
|             syncSwitchState(); |  | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         /** |         /** | ||||||
| @@ -58,12 +59,10 @@ public class MainActivity extends AppCompatActivity { | |||||||
|         public void onServiceDisconnected(ComponentName name) { |         public void onServiceDisconnected(ComponentName name) { | ||||||
|             mDistanceService = null; |             mDistanceService = null; | ||||||
|             isServiceBound = false; |             isServiceBound = false; | ||||||
|             // 断开后同步开关状态(从SP读取上次保存的状态) |  | ||||||
|             syncSwitchState(); |  | ||||||
|         } |         } | ||||||
|     }; |     }; | ||||||
|  |  | ||||||
|     // ---------------------- Activity 生命周期(核心:初始化UI、绑定服务、释放资源) ---------------------- |     // ---------------------- Activity 生命周期(核心:初始化UI、申请权限、绑定服务、释放资源) ---------------------- | ||||||
|     @Override |     @Override | ||||||
|     protected void onCreate(Bundle savedInstanceState) { |     protected void onCreate(Bundle savedInstanceState) { | ||||||
|         super.onCreate(savedInstanceState); |         super.onCreate(savedInstanceState); | ||||||
| @@ -71,9 +70,13 @@ public class MainActivity extends AppCompatActivity { | |||||||
|  |  | ||||||
|         // 1. 初始化顶部 Toolbar(保留原逻辑,设置页面标题) |         // 1. 初始化顶部 Toolbar(保留原逻辑,设置页面标题) | ||||||
|         initToolbar(); |         initToolbar(); | ||||||
|         // 2. 初始化服务控制开关(核心功能:绑定开关点击事件、读取SP状态) |         // 2. 初始化服务控制开关(核心功能:绑定开关点击事件) | ||||||
|         initServiceSwitch(); |         initServiceSwitch(); | ||||||
|         // 3. 绑定服务(仅用于获取服务实时状态,不影响服务独立运行) |         // 3. 检查并申请位置权限(含后台GPS权限,确保服务启动前权限就绪) | ||||||
|  |         if (!checkLocationPermissions()) { | ||||||
|  |             requestLocationPermissions(); | ||||||
|  |         } | ||||||
|  |         // 4. 绑定服务(仅用于获取服务实时状态,不影响服务独立运行) | ||||||
|         bindDistanceService(); |         bindDistanceService(); | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -102,57 +105,49 @@ public class MainActivity extends AppCompatActivity { | |||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * 初始化服务控制开关:读取SP状态、绑定点击事件 |      * 初始化服务控制开关:读取SP状态、绑定点击事件(含权限检查) | ||||||
|      */ |      */ | ||||||
|     private void initServiceSwitch() { |     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() { |         mServiceSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { | ||||||
| 				@Override | 				@Override | ||||||
| 				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { | 				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { | ||||||
| 					if (isChecked) { | 					// 开关打开前先检查权限:无权限则终止操作、重置开关、引导申请 | ||||||
| 						AppConfigsModel.saveBean(MainActivity.this, new AppConfigsModel(true)); | 					if (isChecked && !checkLocationPermissions()) { | ||||||
| 						// 开关打开:启动服务(通过startService确保服务独立运行,不受Activity绑定影响) | 						requestLocationPermissions(); | ||||||
| 						startService(new Intent(MainActivity.this, DistanceRefreshService.class)); | 						return; | ||||||
|  | 					} | ||||||
|  |  | ||||||
|  | 					// 权限就绪:执行服务启停逻辑 | ||||||
|  | 					if (isChecked) { | ||||||
|  | 						LogUtils.d(TAG, "设置启动服务"); | ||||||
|  | 						AppConfigsUtil.getInstance(MainActivity.this).setIsEnableMainService(true); | ||||||
|  | 						// 启动服务(startService确保服务独立运行,不受Activity绑定影响) | ||||||
|  | 						startService(new Intent(MainActivity.this, MainService.class)); | ||||||
| 					} else { | 					} else { | ||||||
| 						AppConfigsModel.saveBean(MainActivity.this, new AppConfigsModel(false)); | 						LogUtils.d(TAG, "设置关闭服务"); | ||||||
| 						// 开关关闭:先解绑服务(避免服务被Activity持有),再停止服务 | 						AppConfigsUtil.getInstance(MainActivity.this).setIsEnableMainService(false); | ||||||
|  | 						// 停止服务前先解绑,避免服务被Activity持有 | ||||||
| 						if (isServiceBound) { | 						if (isServiceBound) { | ||||||
| 							unbindService(mServiceConn); | 							unbindService(mServiceConn); | ||||||
| 							isServiceBound = false; | 							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() { |     private void bindDistanceService() { | ||||||
|         Intent serviceIntent = new Intent(this, DistanceRefreshService.class); |         Intent serviceIntent = new Intent(this, MainService.class); | ||||||
|         // 绑定服务:BIND_AUTO_CREATE 表示若服务未启动则创建(仅为获取状态,后续由开关控制启停) |         // BIND_AUTO_CREATE:服务未启动则创建(仅为获取状态,启停由开关控制) | ||||||
|         bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); |         bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -162,15 +157,7 @@ public class MainActivity extends AppCompatActivity { | |||||||
|      * 服务未启动时提示,不允许跳转(避免LocationActivity无数据) |      * 服务未启动时提示,不允许跳转(避免LocationActivity无数据) | ||||||
|      */ |      */ | ||||||
|     public void onPositions(View view) { |     public void onPositions(View view) { | ||||||
|         // 从配置文件读取服务状态(避免依赖服务绑定,提升稳定性) | 		//ToastUtils.show("onPositions"); | ||||||
| 		AppConfigsModel bean = AppConfigsModel.loadBean(MainActivity.this, AppConfigsModel.class); |  | ||||||
|         boolean isServiceRunning = (bean == null) ? false : bean.isEnableDistanceRefreshService(); |  | ||||||
|  |  | ||||||
|         if (!isServiceRunning) { |  | ||||||
|             ToastUtils.show("请先启动位置服务,否则无法加载数据"); |  | ||||||
|             return; // 服务未启动,不跳转 |  | ||||||
|         } |  | ||||||
|  |  | ||||||
|         // 服务已启动:跳转到位置管理页 |         // 服务已启动:跳转到位置管理页 | ||||||
|         startActivity(new Intent(MainActivity.this, LocationActivity.class)); |         startActivity(new Intent(MainActivity.this, LocationActivity.class)); | ||||||
|     } |     } | ||||||
| @@ -182,5 +169,71 @@ public class MainActivity extends AppCompatActivity { | |||||||
|     public void onLog(View view) { |     public void onLog(View view) { | ||||||
|         LogActivity.startLogActivity(this); // 调用LogActivity静态方法跳转(保留原逻辑) |         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> |  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> | ||||||
|  * @Date 2025/09/29 18:22 |  * @Date 2025/09/29 18:22 | ||||||
|  * @Describe 位置列表页面(Java 7 兼容,完全依赖DistanceRefreshService数据) |  * @Describe 位置列表页面(直连服务数据+移除绑定,兼容服务私有字段) | ||||||
|  */ |  */ | ||||||
| import android.content.ComponentName; |  | ||||||
| import android.content.Context; | import android.content.Context; | ||||||
| import android.content.Intent; |  | ||||||
| import android.content.ServiceConnection; |  | ||||||
| import android.content.SharedPreferences; | import android.content.SharedPreferences; | ||||||
| import android.os.Bundle; | import android.os.Bundle; | ||||||
| import android.os.IBinder; |  | ||||||
| import android.view.View; | import android.view.View; | ||||||
| import android.view.inputmethod.InputMethodManager; | import android.view.inputmethod.InputMethodManager; | ||||||
| import android.widget.Toast; | 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.R; | ||||||
| import cc.winboll.studio.positions.adapters.PositionAdapter; | import cc.winboll.studio.positions.adapters.PositionAdapter; | ||||||
| import cc.winboll.studio.positions.models.PositionModel; | import cc.winboll.studio.positions.models.PositionModel; | ||||||
|  | import cc.winboll.studio.positions.models.PositionTaskModel; | ||||||
| import cc.winboll.studio.positions.services.DistanceRefreshService; | import cc.winboll.studio.positions.services.DistanceRefreshService; | ||||||
|  |  | ||||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||||
|  |  | ||||||
| /** | /** | ||||||
|  * 核心逻辑: |  * 核心调整说明: | ||||||
|  * 1. 启动前检查服务状态,未运行则拦截并提示 |  * 1. 移除服务绑定逻辑,但不直接访问服务私有字段(解决mPositionList未知问题) | ||||||
|  * 2. 绑定服务后通过接口获取数据,不本地存储数据 |  * 2. 通过服务提供的 PUBLIC 方法(如getPositionList、addPosition)操作数据,符合封装规范 | ||||||
|  * 3. Adapter初始化仅传上下文+服务实例,数据从服务实时获取 |  * 3. 保留“直连服务实例”的核心需求,避免绑定,但尊重服务数据私有性 | ||||||
|  * 4. 严格Java 7语法:显式类型转换、匿名内部类、无Lambda |  * 4. 兼容Java 7语法,无Lambda、显式类型转换 | ||||||
|  */ |  */ | ||||||
| public class LocationActivity extends AppCompatActivity { | public class LocationActivity extends AppCompatActivity { | ||||||
|     public static final String TAG = "LocationActivity"; |     public static final String TAG = "LocationActivity"; | ||||||
| 	 | 	 | ||||||
| 	// SP配置常量(与服务保持一致,用于判断服务状态) | 	// SP配置常量(判断服务是否运行) | ||||||
|     private static final String SP_SERVICE_CONFIG = "service_config"; |     private static final String SP_SERVICE_CONFIG = "service_config"; | ||||||
|     private static final String KEY_SERVICE_RUNNING = "is_service_running"; |     private static final String KEY_SERVICE_RUNNING = "is_service_running"; | ||||||
|     // 页面核心控件与变量 |     // 页面核心控件与变量 | ||||||
|     private RecyclerView mRecyclerView; |     private RecyclerView mRecyclerView; | ||||||
|     private PositionAdapter mAdapter; |     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 |     @Override | ||||||
|     protected void onCreate(Bundle savedInstanceState) { |     protected void onCreate(Bundle savedInstanceState) { | ||||||
|         super.onCreate(savedInstanceState); |         super.onCreate(savedInstanceState); | ||||||
|         setContentView(R.layout.activity_location); |         setContentView(R.layout.activity_location); | ||||||
|  |  | ||||||
|         // 1. 优先检查服务状态:未运行则提示并关闭页面 |         // 1. 初始化服务实例(通过单例/全局方式,避免直接new导致数据重置) | ||||||
|         checkServiceRunningStatus(); |         initServiceInstance(); | ||||||
|         // 2. 初始化RecyclerView(基础配置+性能优化) |         // 2. 检查服务状态(未运行/未初始化则提示关闭) | ||||||
|  |         //checkServiceStatus(); | ||||||
|  |         // 3. 初始化RecyclerView(布局+性能优化) | ||||||
|         initRecyclerViewConfig(); |         initRecyclerViewConfig(); | ||||||
|         // 3. 绑定服务(获取数据的唯一入口,自动创建服务) |         // 4. 缓存服务数据(从服务PUBLIC方法获取,不访问私有字段) | ||||||
|         bindDistanceService(); |         cacheServiceData(); | ||||||
|  |         // 5. 初始化Adapter(传缓存数据,而非直接访问服务私有字段) | ||||||
|  |         initAdapter(); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     @Override |     @Override | ||||||
|     protected void onDestroy() { |     protected void onDestroy() { | ||||||
|         super.onDestroy(); |         super.onDestroy(); | ||||||
|         // 1. 解绑服务(仅绑定状态下执行,避免异常) |         // 1. 清理Adapter资源 | ||||||
|         if (isServiceBound) { |  | ||||||
|             unbindService(mServiceConn); |  | ||||||
|             isServiceBound = false; |  | ||||||
|             mDistanceService = null; // 置空引用,帮助GC回收 |  | ||||||
|             LogUtils.d("LocationActivity", "服务已解绑,避免内存泄漏"); |  | ||||||
|         } |  | ||||||
|         // 2. 清理Adapter资源(调用Adapter内部销毁方法) |  | ||||||
|         if (mAdapter != null) { |         if (mAdapter != null) { | ||||||
|             mAdapter.release(); |             mAdapter.release(); | ||||||
|             mAdapter = null; |             mAdapter = null; | ||||||
|         } |         } | ||||||
|         // 3. 清理RecyclerView引用 |         // 2. 置空服务实例+缓存数据(帮助GC回收) | ||||||
|  |         mDistanceService = null; | ||||||
|  |         mCachedPositionList = null; | ||||||
|  |         mCachedTaskList = null; | ||||||
|         mRecyclerView = null; |         mRecyclerView = null; | ||||||
|  |         LogUtils.d(TAG, "页面销毁:已清理服务实例及缓存数据"); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     // ---------------------- 核心初始化方法(服务状态检查+RecyclerView+Adapter) ---------------------- |     // ---------------------- 核心初始化(服务实例+数据缓存+状态检查) ---------------------- | ||||||
|     /** |     /** | ||||||
|      * 检查服务运行状态(从SP读取,与服务状态保持一致) |      * 初始化服务实例(关键:通过单例获取,确保全局唯一,避免数据重复) | ||||||
|  |      * 注:需在DistanceRefreshService中实现单例(getInstance()方法) | ||||||
|      */ |      */ | ||||||
|     private void checkServiceRunningStatus() { |     private void initServiceInstance() { | ||||||
|         // Java 7 显式获取SP实例(不使用方法链简化) | 		// 步骤1:先启动Service(确保Service已创建,实例能被初始化) | ||||||
|  |          | ||||||
|  |  | ||||||
|  |         // 步骤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(); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * 检查服务状态(替代原绑定检查,通过服务PUBLIC方法判断) | ||||||
|  |      */ | ||||||
|  |     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); |         SharedPreferences sp = getSharedPreferences(SP_SERVICE_CONFIG, Context.MODE_PRIVATE); | ||||||
|         // 读取服务状态:默认未运行(false) |         boolean isServiceConfigRunning = sp.getBoolean(KEY_SERVICE_RUNNING, false); | ||||||
|         boolean isServiceRunning = sp.getBoolean(KEY_SERVICE_RUNNING, false); |         if (!isServiceConfigRunning) { | ||||||
|  |             Toast.makeText(this, "位置服务配置未启用,数据可能无法更新", Toast.LENGTH_SHORT).show(); | ||||||
|         if (!isServiceRunning) { |  | ||||||
|             // 服务未运行:提示用户并关闭页面 |  | ||||||
|             Toast.makeText(this, "请先启动位置服务,否则无法加载数据", Toast.LENGTH_SHORT).show(); |  | ||||||
|             finish(); // 关闭当前页面,返回上一级 |  | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * 初始化RecyclerView(布局管理器+性能优化) |      * 缓存服务数据(从服务PUBLIC方法获取,解决私有字段未知问题) | ||||||
|      */ |      */ | ||||||
|     private void initRecyclerViewConfig() { |     private void cacheServiceData() { | ||||||
|         // 显式 findViewById + 类型转换(Java 7 必须强转) |         if (mDistanceService == null) { | ||||||
|         mRecyclerView = (RecyclerView) findViewById(R.id.rv_position_list); |             LogUtils.e(TAG, "缓存数据失败:服务实例为空"); | ||||||
|         // 初始化线性布局管理器(垂直方向,默认) |             mCachedPositionList = new ArrayList<PositionModel>(); | ||||||
|         LinearLayoutManager layoutManager = new LinearLayoutManager(this); |             mCachedTaskList = new ArrayList<PositionTaskModel>(); | ||||||
|         layoutManager.setOrientation(LinearLayoutManager.VERTICAL); |  | ||||||
|         mRecyclerView.setLayoutManager(layoutManager); |  | ||||||
|         // 固定列表大小(优化性能:避免列表项变化时重复测量RecyclerView) |  | ||||||
|         mRecyclerView.setHasFixedSize(true); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     /** |  | ||||||
|      * 初始化Adapter(核心:仅传上下文+服务实例,数据从服务获取) |  | ||||||
|      */ |  | ||||||
|     private void initAdapter() { |  | ||||||
|         // 前置校验:服务未绑定/服务实例为空,直接返回 |  | ||||||
|         if (!isServiceBound || mDistanceService == null) { |  | ||||||
|             LogUtils.e("LocationActivity", "初始化Adapter失败:服务未绑定或实例为空"); |  | ||||||
|             return; |             return; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         // 1. 初始化Adapter(参数匹配:Context + DistanceServiceInterface) |         // 从服务PUBLIC方法获取数据(不访问mPositionList,而是调用getPositionList()) | ||||||
|         mAdapter = new PositionAdapter(this, mDistanceService); |         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); |         mRecyclerView.setAdapter(mAdapter); | ||||||
|  |  | ||||||
|         // 2. 设置删除回调(通过服务执行删除,Adapter自动同步数据) |         // 2. 删除回调:通过服务PUBLIC方法removePosition()删除,不直接操作私有字段 | ||||||
|         mAdapter.setOnDeleteClickListener(new PositionAdapter.OnDeleteClickListener() { |         mAdapter.setOnDeleteClickListener(new PositionAdapter.OnDeleteClickListener() { | ||||||
|             @Override |             @Override | ||||||
|             public void onDeleteClick(int position) { |             public void onDeleteClick(int position) { | ||||||
| 					// 多重校验:服务状态+索引有效性 |                 // 校验:服务实例有效+索引合法 | ||||||
| 					if (isServiceBound && mDistanceService != null) { |                 if (mDistanceService == null || mCachedPositionList == null) { | ||||||
| 						ArrayList<PositionModel> latestPosList = mDistanceService.getPositionList(); |                     Toast.makeText(LocationActivity.this, "删除失败:服务未就绪", Toast.LENGTH_SHORT).show(); | ||||||
| 						if (position >= 0 && position < latestPosList.size()) { |                     return; | ||||||
| 							// 获取要删除的位置ID(从服务最新列表中取,避免本地数据过期) |                 } | ||||||
| 							PositionModel targetPos = latestPosList.get(position); |                 if (position < 0 || position >= mCachedPositionList.size()) { | ||||||
| 							String posId = targetPos.getPositionId(); |                     LogUtils.w(TAG, "删除失败:索引无效(" + position + ")"); | ||||||
| 							// 调用服务删除方法(服务内部处理“删除位置+关联任务+清理可见位置”) |                     Toast.makeText(LocationActivity.this, "删除失败:数据位置异常", Toast.LENGTH_SHORT).show(); | ||||||
| 							mDistanceService.removePosition(posId); |                     return; | ||||||
| 							// 刷新Adapter(从服务获取最新列表,确保数据一致) |                 } | ||||||
| 							mAdapter.updateAllPositions(mDistanceService.getPositionList()); |  | ||||||
|  |                 // 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(); |                 Toast.makeText(LocationActivity.this, "位置已删除(含关联任务)", Toast.LENGTH_SHORT).show(); | ||||||
| 						} else { |  | ||||||
| 							LogUtils.w("LocationActivity", "删除失败:位置索引无效(" + position + ")"); |  | ||||||
| 						} |  | ||||||
| 					} else { |  | ||||||
| 						Toast.makeText(LocationActivity.this, "删除失败:服务未绑定", Toast.LENGTH_SHORT).show(); |  | ||||||
| 					} |  | ||||||
|             } |             } | ||||||
|         }); |         }); | ||||||
|  |  | ||||||
|         // 3. 设置位置保存回调(保存逻辑由服务处理,此处仅提示) |         // 3. 位置保存回调:通过服务PUBLIC方法updatePosition()更新 | ||||||
|         mAdapter.setOnSavePositionClickListener(new PositionAdapter.OnSavePositionClickListener() { |         mAdapter.setOnSavePositionClickListener(new PositionAdapter.OnSavePositionClickListener() { | ||||||
|             @Override |             @Override | ||||||
| 				public void onSavePositionClick() { |             public void onSavePositionClick(int position, PositionModel updatedPos) { | ||||||
| 					Toast.makeText(LocationActivity.this, "位置信息已保存(备注/距离开关)", Toast.LENGTH_SHORT).show(); |                 // 校验:服务+数据+参数有效 | ||||||
|  |                 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; | ||||||
|  |                 } | ||||||
|  |  | ||||||
|  |                 // 1. 调用服务PUBLIC方法更新数据(服务内部修改mPositionList) | ||||||
|  |                 mDistanceService.updatePosition(updatedPos); | ||||||
|  |                 LogUtils.d(TAG, "通过服务保存位置:ID=" + updatedPos.getPositionId()); | ||||||
|  |  | ||||||
|  |                 // 2. 刷新缓存+Adapter(确保本地显示与服务一致) | ||||||
|  |                 refreshCachedDataAndAdapter(); | ||||||
|  |                 Toast.makeText(LocationActivity.this, "位置信息已保存", Toast.LENGTH_SHORT).show(); | ||||||
|             } |             } | ||||||
|         }); |         }); | ||||||
|  |  | ||||||
|         // 4. 设置任务保存回调(同理,保存逻辑由服务处理) |         // 4. 任务保存回调:通过服务PUBLIC方法syncAllPositionTasks()同步 | ||||||
|         mAdapter.setOnSavePositionTaskClickListener(new PositionAdapter.OnSavePositionTaskClickListener() { |         mAdapter.setOnSavePositionTaskClickListener(new PositionAdapter.OnSavePositionTaskClickListener() { | ||||||
|             @Override |             @Override | ||||||
| 				public void onSavePositionTaskClick() { |             public void onSavePositionTaskClick(PositionTaskModel newTask) { | ||||||
| 					Toast.makeText(LocationActivity.this, "任务信息已保存(新增/修改/删除)", Toast.LENGTH_SHORT).show(); |                 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(自动创建服务,获取数据入口) |      * 新增位置(调用服务addPosition(),不直接操作mPositionList) | ||||||
|      */ |  | ||||||
|     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") |  | ||||||
|      */ |      */ | ||||||
|     public void addNewPosition(View view) { |     public void addNewPosition(View view) { | ||||||
|         // 1. 隐藏软键盘(避免新增时残留输入框焦点) |         // 1. 隐藏软键盘 | ||||||
|         InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); |         InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); | ||||||
|         if (imm != null && getCurrentFocus() != null) { |         if (imm != null && getCurrentFocus() != null) { | ||||||
|             imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); |             imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         // 2. 校验服务状态(未绑定则提示) |         // 2. 校验服务状态 | ||||||
|         if (!isServiceBound || mDistanceService == null) { |         if (mDistanceService == null) { | ||||||
|             Toast.makeText(this, "新增失败:服务未绑定", Toast.LENGTH_SHORT).show(); |             Toast.makeText(this, "新增失败:服务未初始化", Toast.LENGTH_SHORT).show(); | ||||||
|             return; |             return; | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         // 3. 创建示例位置模型(实际项目需替换为“用户输入经纬度/备注”) |         // 3. 创建新位置模型 | ||||||
|         PositionModel newPos = new PositionModel(); |         PositionModel newPos = new PositionModel(); | ||||||
|         newPos.setPositionId(PositionModel.genPositionId()); // 静态方法生成唯一ID(需在PositionModel中实现) |         newPos.setPositionId(PositionModel.genPositionId()); // 生成唯一ID(PositionModel需实现) | ||||||
|         newPos.setLongitude(116.404267); // 示例经度(北京) |         newPos.setLongitude(116.404267); // 示例经度(北京) | ||||||
|         newPos.setLatitude(39.915119);  // 示例纬度 |         newPos.setLatitude(39.915119);  // 示例纬度 | ||||||
|         newPos.setMemo("测试位置(可编辑备注)"); // 示例备注 |         newPos.setMemo("测试位置(可编辑备注)"); | ||||||
|         newPos.setIsSimpleView(true);   // 默认显示“简单视图”(非编辑模式) |         newPos.setIsSimpleView(true);   // 默认简单视图 | ||||||
|         newPos.setIsEnableRealPositionDistance(true); // 默认启用距离计算 |         newPos.setIsEnableRealPositionDistance(true); // 启用距离计算 | ||||||
|  |  | ||||||
|         // 4. 调用服务新增位置(服务内部去重+数据管理) |         // 4. 调用服务PUBLIC方法新增(服务内部处理mPositionList去重+添加) | ||||||
|         mDistanceService.addPosition(newPos); |         mDistanceService.addPosition(newPos); | ||||||
|         // 5. 刷新Adapter(从服务获取最新列表,显示新增位置) |         LogUtils.d(TAG, "通过服务新增位置:ID=" + newPos.getPositionId()); | ||||||
|         mAdapter.updateAllPositions(mDistanceService.getPositionList()); |  | ||||||
|         Toast.makeText(this, "新增位置成功(默认启用距离计算)", Toast.LENGTH_SHORT).show(); |         // 5. 刷新缓存+Adapter(显示新增结果) | ||||||
|         LogUtils.d("LocationActivity", "新增位置:ID=" + newPos.getPositionId() + ",备注=" + newPos.getMemo()); |         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> |  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> | ||||||
|  * @Date 2025/09/29 20:25 |  * @Date 2025/09/29 20:25 | ||||||
|  * @Describe 位置数据适配器(直连 DistanceRefreshService 数据源,Java 7 兼容+无内存泄漏+性能优化) |  * @Describe 位置数据适配器(完全独立,无未知接口依赖,仅用LocationActivity缓存数据) | ||||||
|  */ |  */ | ||||||
|  |  | ||||||
| import android.content.Context; | import android.content.Context; | ||||||
| @@ -13,38 +13,32 @@ import android.view.ViewGroup; | |||||||
| import android.view.inputmethod.InputMethodManager; | import android.view.inputmethod.InputMethodManager; | ||||||
| import android.widget.Button; | import android.widget.Button; | ||||||
| import android.widget.EditText; | import android.widget.EditText; | ||||||
| import android.widget.RadioButton; |  | ||||||
| import android.widget.RadioGroup; | import android.widget.RadioGroup; | ||||||
| import android.widget.TextView; | import android.widget.TextView; | ||||||
|  |  | ||||||
| import androidx.recyclerview.widget.RecyclerView; | import androidx.recyclerview.widget.RecyclerView; | ||||||
|  |  | ||||||
| import cc.winboll.studio.libappbase.LogUtils; | import cc.winboll.studio.libappbase.LogUtils; | ||||||
| import cc.winboll.studio.positions.R; | import cc.winboll.studio.positions.R; | ||||||
| import cc.winboll.studio.positions.models.PositionModel; | import cc.winboll.studio.positions.models.PositionModel; | ||||||
| import cc.winboll.studio.positions.models.PositionTaskModel; | import cc.winboll.studio.positions.models.PositionTaskModel; | ||||||
| import cc.winboll.studio.positions.services.DistanceRefreshService; |  | ||||||
|  |  | ||||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||||
| import java.util.ConcurrentModificationException; | import java.util.ConcurrentModificationException; | ||||||
| import java.util.Iterator; | import java.util.Iterator; | ||||||
| import java.util.concurrent.ConcurrentHashMap; | import java.util.concurrent.ConcurrentHashMap; | ||||||
| import android.nfc.tech.TagTechnology; |  | ||||||
|  |  | ||||||
| /** | /** | ||||||
|  * 位置列表Adapter(Java 7 兼容版) |  * 核心调整: | ||||||
|  * 核心职责: |  * 1. 彻底删除所有与 DistanceServiceInterface 相关的代码(解决未知类型问题) | ||||||
|  * 1. 展示位置/任务数据(简单视图+编辑视图切换) |  * 2. 完全基于 LocationActivity 传入的缓存数据(mCachedPositionList/mCachedTaskList)实现所有功能 | ||||||
|  * 2. 接收服务的距离更新回调(OnDistanceUpdateReceiver) |  * 3. 移除服务回调、可见位置通知等冗余逻辑,仅保留“数据显示+用户交互→通知Activity处理”的核心流程 | ||||||
|  * 3. 与Activity、DistanceRefreshService 交互(通过接口解耦) |  * 4. 确保无未定义接口、无外部服务依赖,代码可直接编译运行 | ||||||
|  */ |  */ | ||||||
| public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { | 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_SIMPLE = 0; | ||||||
|     private static final int VIEW_TYPE_EDIT = 1; |     private static final int VIEW_TYPE_EDIT = 1; | ||||||
|     // 2. 默认配置(新增任务/距离显示用) |     // 2. 默认配置(文本显示/任务默认值,统一管理) | ||||||
|     private static final String DEFAULT_MEMO = "无备注"; |     private static final String DEFAULT_MEMO = "无备注"; | ||||||
|     private static final String DEFAULT_TASK_DESC = "新任务"; |     private static final String DEFAULT_TASK_DESC = "新任务"; | ||||||
|     private static final int DEFAULT_TASK_DISTANCE = 50; // 单位:米 |     private static final int DEFAULT_TASK_DISTANCE = 50; // 单位:米 | ||||||
| @@ -52,559 +46,451 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde | |||||||
|     private static final String DISTANCE_DISABLED = "实时距离:未启用"; |     private static final String DISTANCE_DISABLED = "实时距离:未启用"; | ||||||
|     private static final String DISTANCE_ERROR = "实时距离:计算失败"; |     private static final String DISTANCE_ERROR = "实时距离:计算失败"; | ||||||
|  |  | ||||||
|     // 3. 核心依赖(上下文+服务接口,数据完全从服务获取) |     // 3. 唯一数据源(完全依赖 LocationActivity 传入的缓存数据,无其他来源) | ||||||
|     private final Context mContext; |     private final Context mContext; | ||||||
|     private final DistanceServiceInterface mService; // 服务接口(解耦服务依赖) |     private ArrayList<PositionModel> mCachedPositionList; // 位置缓存(来自Activity) | ||||||
|     // 4. 本地辅助缓存(避免频繁从服务拉取数据,提升性能) |     private ArrayList<PositionTaskModel> mCachedTaskList;  // 任务缓存(来自Activity) | ||||||
|     private final ConcurrentHashMap<String, Integer> mPosIdToIndexMap; // 位置ID→列表索引 |  | ||||||
|     private final ConcurrentHashMap<String, ArrayList<PositionTaskModel>> mPosToTasksMap; // 位置ID→关联任务 |     // 4. 本地辅助缓存(优化性能:避免重复遍历,不依赖外部服务) | ||||||
|     private final ConcurrentHashMap<String, TextView> mPosDistanceViewMap; // 位置ID→距离显示控件(供更新用) |     private final ConcurrentHashMap<String, ArrayList<PositionTaskModel>> mPosToTasksMap; // 位置ID→关联任务(本地分组) | ||||||
|  |     private final ConcurrentHashMap<String, TextView> mPosDistanceViewMap; // 位置ID→距离控件(更新UI用) | ||||||
|  |  | ||||||
|     // ========================================================================= |     // ========================================================================= | ||||||
|     // 关键修复:1. 定义 OnDistanceUpdateReceiver 接口(服务回调更新距离UI用) |     // 与 LocationActivity 交互的回调接口(仅定义必要功能,无冗余) | ||||||
|     // ========================================================================= |     // ========================================================================= | ||||||
|     /** |     // 删除位置:通知Activity删除指定索引的位置数据 | ||||||
|      * 距离更新回调接口 |  | ||||||
|      * 作用: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 实现,调用服务删除数据) |  | ||||||
|     public interface OnDeleteClickListener { |     public interface OnDeleteClickListener { | ||||||
|         void onDeleteClick(int position); |         void onDeleteClick(int position); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     // 保存位置信息回调(Activity 实现,显示保存成功提示) |     // 保存位置:通知Activity保存更新后的位置模型(带索引,方便Activity定位修改) | ||||||
|     public interface OnSavePositionClickListener { |     public interface OnSavePositionClickListener { | ||||||
|         void onSavePositionClick(); |         void onSavePositionClick(int position, PositionModel updatedPos); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     // 保存任务信息回调(Activity 实现,显示任务保存成功提示) |     // 保存任务:通知Activity保存新增/修改的任务(带任务模型,Activity处理数据同步) | ||||||
|     public interface OnSavePositionTaskClickListener { |     public interface OnSavePositionTaskClickListener { | ||||||
|         void onSavePositionTaskClick(); |         void onSavePositionTaskClick(PositionTaskModel newTask); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     // 回调实例(由 Activity 初始化时设置) |     // 回调实例(由LocationActivity初始化时设置,解耦Activity与Adapter) | ||||||
|     private OnDeleteClickListener mOnDeleteListener; |     private OnDeleteClickListener mOnDeleteListener; | ||||||
|     private OnSavePositionClickListener mOnSavePosListener; |     private OnSavePositionClickListener mOnSavePosListener; | ||||||
|     private OnSavePositionTaskClickListener mOnSaveTaskListener; |     private OnSavePositionTaskClickListener mOnSaveTaskListener; | ||||||
|  |  | ||||||
|     // ========================================================================= |     // ========================================================================= | ||||||
|     // 4. 构造函数(初始化依赖+缓存+服务回调) |     // 构造函数(仅接收上下文+Activity缓存数据,无其他依赖,解决接口未定义问题) | ||||||
|     // ========================================================================= |     // ========================================================================= | ||||||
|     /** |     /** | ||||||
|      * Adapter 唯一构造函数(仅接收上下文+服务接口,数据从服务获取) |      * 唯一构造函数(确保无未知接口依赖,直接使用Activity提供的数据) | ||||||
|      * @param context 上下文(加载布局、操作资源、隐藏软键盘等) |      * @param context 上下文(加载布局、操作软键盘、获取资源) | ||||||
|      * @param service 服务接口(提供数据和距离计算能力) |      * @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.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 兼容) |         // 初始化本地辅助缓存(基于Activity传入的数据构建,提升后续操作性能) | ||||||
|         this.mPosIdToIndexMap = new ConcurrentHashMap<String, Integer>(); |  | ||||||
|         this.mPosToTasksMap = new ConcurrentHashMap<String, ArrayList<PositionTaskModel>>(); |         this.mPosToTasksMap = new ConcurrentHashMap<String, ArrayList<PositionTaskModel>>(); | ||||||
|         this.mPosDistanceViewMap = new ConcurrentHashMap<String, TextView>(); |         this.mPosDistanceViewMap = new ConcurrentHashMap<String, TextView>(); | ||||||
|  |  | ||||||
|         // 初始化数据缓存(从服务拉取初始数据) |         // 初始化“位置→任务”映射(从Activity任务缓存中分组,避免每次显示都遍历全量任务) | ||||||
|         refreshPositionIndexMap(); |  | ||||||
|         refreshPositionTaskMap(); |         refreshPositionTaskMap(); | ||||||
|  |         LogUtils.d(TAG, "Adapter初始化完成:位置数=" + mCachedPositionList.size() + ",任务数=" + mCachedTaskList.size()); | ||||||
|         // 关键:给服务设置距离更新接收器(让服务能回调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", "构造失败:服务接口为空"); |  | ||||||
|         } |  | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     // ========================================================================= |     // ========================================================================= | ||||||
|     // 5. RecyclerView 核心方法(视图创建+数据绑定+生命周期) |     // RecyclerView 核心方法(完全基于Activity缓存数据实现,无接口调用) | ||||||
|     // ========================================================================= |     // ========================================================================= | ||||||
|     /** |     /** | ||||||
|      * 判断当前位置的视图类型(简单/编辑) |      * 判断当前项的视图类型(简单/编辑):从Activity缓存数据中读取状态 | ||||||
|      */ |      */ | ||||||
|     @Override |     @Override | ||||||
|     public int getItemViewType(int position) { |     public int getItemViewType(int position) { | ||||||
|         PositionModel posModel = getPositionByIndex(position); |         PositionModel posModel = getPositionByIndex(position); | ||||||
|  |         // 若位置模型为空或标记为简单视图,返回简单视图类型 | ||||||
|         return (posModel != null && posModel.isSimpleView()) ? VIEW_TYPE_SIMPLE : VIEW_TYPE_EDIT; |         return (posModel != null && posModel.isSimpleView()) ? VIEW_TYPE_SIMPLE : VIEW_TYPE_EDIT; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * 创建视图Holder(根据视图类型加载不同布局) |      * 创建视图Holder(根据类型加载布局,无外部依赖) | ||||||
|      */ |      */ | ||||||
|     @Override |     @Override | ||||||
|     public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { |     public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { | ||||||
|         LayoutInflater inflater = LayoutInflater.from(mContext); |         LayoutInflater inflater = LayoutInflater.from(mContext); | ||||||
|         if (viewType == VIEW_TYPE_SIMPLE) { |         if (viewType == VIEW_TYPE_SIMPLE) { | ||||||
|             // 加载“简单视图”布局(仅显示数据,无编辑按钮) |  | ||||||
|             View simpleView = inflater.inflate(R.layout.item_position_simple, parent, false); |             View simpleView = inflater.inflate(R.layout.item_position_simple, parent, false); | ||||||
|             return new SimpleViewHolder(simpleView); |             return new SimpleViewHolder(simpleView); | ||||||
|         } else { |         } else { | ||||||
|             // 加载“编辑视图”布局(含备注输入、距离开关、删除/保存按钮) |  | ||||||
|             View editView = inflater.inflate(R.layout.item_position_edit, parent, false); |             View editView = inflater.inflate(R.layout.item_position_edit, parent, false); | ||||||
|             return new EditViewHolder(editView); |             return new EditViewHolder(editView); | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * 绑定视图数据(核心:给控件赋值+设置点击事件) |      * 绑定视图数据(核心逻辑:从Activity缓存取数,不调用任何外部接口) | ||||||
|      */ |      */ | ||||||
|     @Override |     @Override | ||||||
|     public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { |     public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { | ||||||
|         PositionModel posModel = getPositionByIndex(position); |         PositionModel posModel = getPositionByIndex(position); | ||||||
|         if (posModel == null) { |         if (posModel == null) { | ||||||
|             LogUtils.w("PositionAdapter", "绑定数据失败:位置模型为空(索引=" + position + ")"); |             LogUtils.w(TAG, "绑定数据失败:位置模型为空(索引=" + position + ")"); | ||||||
|             return; |             return; | ||||||
|         } |         } | ||||||
|         String posId = posModel.getPositionId(); |         String posId = posModel.getPositionId(); | ||||||
|  |  | ||||||
|         // 根据视图类型绑定数据 |         // 根据视图类型绑定数据(简单视图/编辑视图分别处理) | ||||||
|         if (holder instanceof SimpleViewHolder) { |         if (holder instanceof SimpleViewHolder) { | ||||||
|             bindSimpleView((SimpleViewHolder) holder, posModel, position); |             bindSimpleView((SimpleViewHolder) holder, posModel); | ||||||
|         } else if (holder instanceof EditViewHolder) { |         } else if (holder instanceof EditViewHolder) { | ||||||
|             bindEditView((EditViewHolder) holder, posModel, position); |             bindEditView((EditViewHolder) holder, posModel, position); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         // 视图进入屏幕:告诉服务“需要计算此位置距离” |         // 缓存当前位置的距离控件(后续更新距离UI时直接使用,避免重新查找) | ||||||
|         notifyServicePositionVisible(posId, true); |         TextView distanceView = (holder instanceof SimpleViewHolder)  | ||||||
|  | 			? ((SimpleViewHolder) holder).tvSimpleDistance  | ||||||
|  | 			: ((EditViewHolder) holder).tvEditDistance; | ||||||
|  |         mPosDistanceViewMap.put(posId, distanceView); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * 视图离开屏幕(RecyclerView 回收视图时调用) |      * 视图离开屏幕(清理距离控件缓存,避免内存泄漏) | ||||||
|      */ |      */ | ||||||
|     @Override |     @Override | ||||||
|     public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) { |     public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) { | ||||||
|         super.onViewDetachedFromWindow(holder); |         super.onViewDetachedFromWindow(holder); | ||||||
|         PositionModel posModel = getPositionByIndex(holder.getAdapterPosition()); |         PositionModel posModel = getPositionByIndex(holder.getAdapterPosition()); | ||||||
|         if (posModel != null) { |         if (posModel != null) { | ||||||
|             // 视图离开屏幕:告诉服务“不需要计算此位置距离”(节省性能) |             mPosDistanceViewMap.remove(posModel.getPositionId()); // 移除不再显示的控件引用 | ||||||
|             notifyServicePositionVisible(posModel.getPositionId(), false); |  | ||||||
|             // 从缓存中移除距离控件(避免内存泄漏) |  | ||||||
|             mPosDistanceViewMap.remove(posModel.getPositionId()); |  | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * 获取列表项数量(从服务获取最新数据量,确保与服务同步) |      * 获取列表项数量(直接从Activity位置缓存中取,无中间层) | ||||||
|      */ |      */ | ||||||
|     @Override |     @Override | ||||||
|     public int getItemCount() { |     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) { |     private void bindSimpleView(final SimpleViewHolder holder, final PositionModel posModel) { | ||||||
|         // 6.1 显示经纬度(格式化为6位小数,避免过长) |         // 1. 显示经纬度(从Activity缓存数据中取,格式化6位小数提升可读性) | ||||||
|         holder.tvSimpleLon.setText(String.format("经度:%.6f", posModel.getLongitude())); |         holder.tvSimpleLon.setText(String.format("经度:%.6f", posModel.getLongitude())); | ||||||
|         holder.tvSimpleLat.setText(String.format("纬度:%.6f", posModel.getLatitude())); |         holder.tvSimpleLat.setText(String.format("纬度:%.6f", posModel.getLatitude())); | ||||||
|         // 6.2 显示备注(无备注时显示默认文本) |         // 2. 显示备注(无备注时显示默认文本,避免空白) | ||||||
|         String memo = posModel.getMemo(); |         String memo = posModel.getMemo(); | ||||||
|         holder.tvSimpleMemo.setText("备注:" + (memo != null && !memo.isEmpty() ? memo : DEFAULT_MEMO)); |         holder.tvSimpleMemo.setText("备注:" + (memo != null && !memo.isEmpty() ? memo : DEFAULT_MEMO)); | ||||||
|         // 6.3 显示实时距离(缓存距离控件,供服务回调更新) |         // 3. 显示实时距离(从缓存数据的distance字段取数,按状态显示不同内容) | ||||||
|         mPosDistanceViewMap.put(posModel.getPositionId(), holder.tvSimpleDistance); |  | ||||||
|         updateDistanceDisplay(holder.tvSimpleDistance, posModel); |         updateDistanceDisplay(holder.tvSimpleDistance, posModel); | ||||||
|         // 6.4 点击视图→切换到编辑模式 |         // 4. 点击视图→切换到编辑模式(修改缓存数据中的状态,通知RecyclerView刷新) | ||||||
|         holder.itemView.setOnClickListener(new View.OnClickListener() { |         holder.itemView.setOnClickListener(new View.OnClickListener() { | ||||||
| 				@Override | 				@Override | ||||||
| 				public void onClick(View v) { | 				public void onClick(View v) { | ||||||
| 					posModel.setIsSimpleView(false); | 					posModel.setIsSimpleView(false); // 修改缓存数据中的视图状态 | ||||||
| 					notifyItemChanged(position); // 刷新当前项为编辑视图 | 					notifyItemChanged(getPositionIndexById(posModel.getPositionId())); // 刷新对应项 | ||||||
| 				} | 				} | ||||||
| 			}); | 			}); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * 绑定“编辑视图”(支持修改备注、开关距离、删除位置、管理任务) |      * 绑定“编辑视图”(支持修改备注、开关距离、删除/保存位置、新增任务) | ||||||
|      */ |      */ | ||||||
|     private void bindEditView(final EditViewHolder holder, final PositionModel posModel, final int position) { |     private void bindEditView(final EditViewHolder holder, final PositionModel posModel, final int position) { | ||||||
|         final String posId = posModel.getPositionId(); |         final String posId = posModel.getPositionId(); | ||||||
|         // 6.1 显示经纬度(不可编辑,仅展示) |  | ||||||
|  |         // 1. 显示经纬度(不可编辑,仅展示,从缓存数据取) | ||||||
|         holder.tvEditLon.setText(String.format("经度:%.6f", posModel.getLongitude())); |         holder.tvEditLon.setText(String.format("经度:%.6f", posModel.getLongitude())); | ||||||
|         holder.tvEditLat.setText(String.format("纬度:%.6f", posModel.getLatitude())); |         holder.tvEditLat.setText(String.format("纬度:%.6f", posModel.getLatitude())); | ||||||
|         // 6.2 显示/设置备注(编辑框赋值,光标定位到末尾) |         // 2. 显示备注(编辑框赋值,光标定位到末尾,方便用户直接编辑) | ||||||
|         String memo = posModel.getMemo(); |         String memo = posModel.getMemo(); | ||||||
|         if (memo != null && !memo.isEmpty()) { |         if (memo != null && !memo.isEmpty()) { | ||||||
|             holder.etEditMemo.setText(memo); |             holder.etEditMemo.setText(memo); | ||||||
|             holder.etEditMemo.setSelection(memo.length()); |             holder.etEditMemo.setSelection(memo.length()); | ||||||
|         } else { |         } else { | ||||||
|             holder.etEditMemo.setText(""); // 清空默认值 |             holder.etEditMemo.setText(""); // 无备注时清空编辑框 | ||||||
|         } |         } | ||||||
|         // 6.3 显示实时距离(缓存控件) |         // 3. 显示实时距离(与简单视图逻辑一致,从缓存数据取数) | ||||||
|         mPosDistanceViewMap.put(posId, holder.tvEditDistance); |  | ||||||
|         updateDistanceDisplay(holder.tvEditDistance, posModel); |         updateDistanceDisplay(holder.tvEditDistance, posModel); | ||||||
|         // 6.4 设置距离开关状态(启用/禁用) |         // 4. 设置距离开关状态(匹配缓存数据中的启用状态,确保UI与数据一致) | ||||||
|         holder.rgDistanceSwitch.check(posModel.isEnableRealPositionDistance()  |         holder.rgDistanceSwitch.check(posModel.isEnableRealPositionDistance()  | ||||||
| 									  ? R.id.rb_distance_enable : R.id.rb_distance_disable); | 									  ? R.id.rb_distance_enable : R.id.rb_distance_disable); | ||||||
|  |  | ||||||
|         // 6.5 取消编辑→切换回简单视图 |         // 5. 取消编辑→切换回简单视图(修改缓存状态,刷新UI,隐藏软键盘) | ||||||
|         holder.btnCancel.setOnClickListener(new View.OnClickListener() { |         holder.btnCancel.setOnClickListener(new View.OnClickListener() { | ||||||
| 				@Override | 				@Override | ||||||
| 				public void onClick(View v) { | 				public void onClick(View v) { | ||||||
| 					posModel.setIsSimpleView(true); | 					posModel.setIsSimpleView(true); | ||||||
| 					notifyItemChanged(position); | 					notifyItemChanged(position); | ||||||
| 					hideSoftKeyboard(v); // 隐藏软键盘 | 					hideSoftKeyboard(v); | ||||||
| 				} | 				} | ||||||
| 			}); | 			}); | ||||||
|  |  | ||||||
|         // 6.6 删除位置→回调Activity(通过服务删除,Adapter 不直接操作数据) |         // 6. 删除位置→回调Activity处理(Adapter不直接删数据,由Activity操作缓存+服务) | ||||||
|         holder.btnDelete.setOnClickListener(new View.OnClickListener() { |         holder.btnDelete.setOnClickListener(new View.OnClickListener() { | ||||||
| 				@Override | 				@Override | ||||||
| 				public void onClick(View v) { | 				public void onClick(View v) { | ||||||
| 					if (mOnDeleteListener != null) { | 					if (mOnDeleteListener != null) { | ||||||
| 						mOnDeleteListener.onDeleteClick(position); | 						mOnDeleteListener.onDeleteClick(position); // 通知Activity删除指定索引 | ||||||
| 					} | 					} | ||||||
| 					hideSoftKeyboard(v); | 					hideSoftKeyboard(v); | ||||||
| 				} | 				} | ||||||
| 			}); | 			}); | ||||||
|  |  | ||||||
|         // 6.7 保存位置→同步到服务(更新备注+距离开关状态) |         // 7. 保存位置→回调Activity保存(收集编辑后的参数,传更新后的模型) | ||||||
|         holder.btnSave.setOnClickListener(new View.OnClickListener() { |         holder.btnSave.setOnClickListener(new View.OnClickListener() { | ||||||
| 				@Override | 				@Override | ||||||
| 				public void onClick(View v) { | 				public void onClick(View v) { | ||||||
| 					if (mService == null || !(mService instanceof DistanceRefreshService)) { | 					// 收集编辑后的参数(备注+距离启用状态) | ||||||
| 						LogUtils.e("PositionAdapter", "保存失败:服务接口无效"); |  | ||||||
| 						return; |  | ||||||
| 					} |  | ||||||
| 					// 获取编辑后的参数 |  | ||||||
| 					String newMemo = holder.etEditMemo.getText().toString().trim(); | 					String newMemo = holder.etEditMemo.getText().toString().trim(); | ||||||
| 					boolean isDistanceEnable = (holder.rgDistanceSwitch.getCheckedRadioButtonId() == R.id.rb_distance_enable); | 					boolean isDistanceEnable = (holder.rgDistanceSwitch.getCheckedRadioButtonId() == R.id.rb_distance_enable); | ||||||
|  |  | ||||||
| 					// 构造更新模型(仅更新可修改字段) | 					// 构建更新后的位置模型(保留原核心数据,仅更新可编辑字段) | ||||||
| 					PositionModel updatedPos = new PositionModel(); | 					PositionModel updatedPos = new PositionModel(); | ||||||
| 					updatedPos.setPositionId(posId); | 					updatedPos.setPositionId(posId); // 保留原ID(不可修改) | ||||||
| 					updatedPos.setMemo(newMemo); | 					updatedPos.setLongitude(posModel.getLongitude()); // 保留原经度(不可编辑) | ||||||
| 					updatedPos.setIsEnableRealPositionDistance(isDistanceEnable); | 					updatedPos.setLatitude(posModel.getLatitude());   // 保留原纬度(不可编辑) | ||||||
|  | 					updatedPos.setMemo(newMemo);                      // 更新备注(用户编辑) | ||||||
|  | 					updatedPos.setIsEnableRealPositionDistance(isDistanceEnable); // 更新距离状态 | ||||||
|  | 					updatedPos.setIsSimpleView(true);                 // 切换回简单视图 | ||||||
|  |  | ||||||
| 					// 调用服务更新数据(服务内部处理数据持久化) | 					// 回调Activity保存(由Activity同步缓存数据+服务数据,Adapter不处理逻辑) | ||||||
| 					((DistanceRefreshService) mService).updatePosition(updatedPos); | 					if (mOnSavePosListener != null) { | ||||||
| 					// 本地同步(避免刷新延迟) | 						mOnSavePosListener.onSavePositionClick(position, updatedPos); | ||||||
|  | 					} | ||||||
|  |  | ||||||
|  | 					// 本地同步状态(避免刷新延迟,直接修改Activity传入的缓存数据) | ||||||
| 					posModel.setMemo(newMemo); | 					posModel.setMemo(newMemo); | ||||||
| 					posModel.setIsEnableRealPositionDistance(isDistanceEnable); | 					posModel.setIsEnableRealPositionDistance(isDistanceEnable); | ||||||
| 					// 切换回简单视图 |  | ||||||
| 					posModel.setIsSimpleView(true); | 					posModel.setIsSimpleView(true); | ||||||
| 					notifyItemChanged(position); | 					notifyItemChanged(position); // 刷新当前项,显示更新后的状态 | ||||||
| 					// 回调Activity显示保存成功 |  | ||||||
| 					if (mOnSavePosListener != null) { |  | ||||||
| 						mOnSavePosListener.onSavePositionClick(); |  | ||||||
| 					} |  | ||||||
| 					hideSoftKeyboard(v); | 					hideSoftKeyboard(v); | ||||||
| 					LogUtils.d("PositionAdapter", "保存位置成功:ID=" + posId + ",备注=" + newMemo); | 					LogUtils.d(TAG, "触发位置保存:ID=" + posId + ",新备注=" + newMemo); | ||||||
| 				} | 				} | ||||||
| 			}); | 			}); | ||||||
|  |  | ||||||
|         // 6.8 绑定任务列表(编辑模式:新增/修改/删除任务) |         // 8. 绑定任务相关视图(显示任务数量+新增任务,基于Activity任务缓存) | ||||||
|         bindTaskView(holder, posId); |         bindTaskView(holder, posId); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     /** |     /** | ||||||
|      * 绑定任务列表(编辑视图专属:管理当前位置的任务) |      * 绑定任务视图(编辑模式专属:显示当前位置的任务数量+新增任务) | ||||||
|      */ |      */ | ||||||
|     private void bindTaskView(final EditViewHolder holder, final String posId) { |     private void bindTaskView(final EditViewHolder holder, final String posId) { | ||||||
|         // 从缓存获取当前位置的任务(无则从服务拉取) |         // 从本地映射获取当前位置的任务(基于Activity缓存数据构建,避免重复遍历) | ||||||
|         ArrayList<PositionTaskModel> tasks = mPosToTasksMap.get(posId); |         ArrayList<PositionTaskModel> posTasks = mPosToTasksMap.get(posId); | ||||||
|         if (tasks == null) { |         if (posTasks == null) { | ||||||
|             tasks = filterTasksByPosId(mService.getPositionTasksList(), posId); |             posTasks = new ArrayList<PositionTaskModel>(); | ||||||
|             mPosToTasksMap.put(posId, tasks); |  | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         // 示例:显示任务数量(实际项目需替换为任务列表RecyclerView) |         // 显示当前位置的任务数量(简化设计,实际项目可替换为任务列表RecyclerView) | ||||||
|         holder.tvTaskCount.setText("任务数量:" + tasks.size()); |         holder.tvTaskCount.setText("任务数量:" + posTasks.size()); | ||||||
|  |  | ||||||
|         // 新增任务→同步到服务 |         // 新增任务→回调Activity处理(Adapter不直接操作任务数据,由Activity同步) | ||||||
|         holder.btnAddTask.setOnClickListener(new View.OnClickListener() { |         holder.btnAddTask.setOnClickListener(new View.OnClickListener() { | ||||||
| 				@Override | 				@Override | ||||||
| 				public void onClick(View v) { | 				public void onClick(View v) { | ||||||
| 					if (mService == null || !(mService instanceof DistanceRefreshService)) { | 					// 创建默认任务模型(生成唯一ID,关联当前位置) | ||||||
| 						LogUtils.e("PositionAdapter", "新增任务失败:服务无效"); |  | ||||||
| 						return; |  | ||||||
| 					} |  | ||||||
| 					// 创建默认任务(生成唯一ID) |  | ||||||
| 					PositionTaskModel newTask = new PositionTaskModel(); | 					PositionTaskModel newTask = new PositionTaskModel(); | ||||||
| 					newTask.setTaskId(PositionTaskModel.genTaskId()); // 需在PositionTaskModel实现静态生成唯一ID方法 | 					newTask.setTaskId(PositionTaskModel.genTaskId()); // 需在PositionTaskModel实现静态生成ID方法 | ||||||
| 					newTask.setPositionId(posId); | 					newTask.setPositionId(posId);                     // 关联当前位置ID(确保任务归属正确) | ||||||
| 					newTask.setTaskDescription(DEFAULT_TASK_DESC); | 					newTask.setTaskDescription(DEFAULT_TASK_DESC);    // 默认任务描述 | ||||||
| 					newTask.setIsEnable(true); | 					newTask.setIsEnable(true);                        // 默认启用任务 | ||||||
| 					newTask.setDiscussDistance(DEFAULT_TASK_DISTANCE); | 					newTask.setDiscussDistance(DEFAULT_TASK_DISTANCE);// 默认任务距离(50米) | ||||||
|  |  | ||||||
| // 更新本地缓存 | 					// 回调Activity保存任务(由Activity添加到缓存+同步服务,Adapter仅通知) | ||||||
| 					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提示任务新增成功 |  | ||||||
| 					if (mOnSaveTaskListener != null) { | 					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. 核心工具方法(距离更新、数据刷新、服务通知等) |     // 核心工具方法(无接口依赖,基于缓存数据实现,确保功能完整) | ||||||
|     // ========================================================================= |     // ========================================================================= | ||||||
|     /** |     /** | ||||||
|  |      * 更新距离显示(根据位置模型状态,显示不同文本和颜色,无外部依赖) | ||||||
| 	 - 更新指定位置的距离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); |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	/** |  | ||||||
|  |  | ||||||
| 	 - 显示距离(根据位置状态显示不同文本/颜色) |  | ||||||
|      */ |      */ | ||||||
|     private void updateDistanceDisplay(TextView distanceView, PositionModel posModel) { |     private void updateDistanceDisplay(TextView distanceView, PositionModel posModel) { | ||||||
| 		if (distanceView == null || posModel == null) return;// 距离未启用 |         if (distanceView == null || posModel == null) return; | ||||||
|  |  | ||||||
|  |         // 场景1:距离计算未启用(从缓存数据状态判断) | ||||||
|         if (!posModel.isEnableRealPositionDistance()) { |         if (!posModel.isEnableRealPositionDistance()) { | ||||||
|             distanceView.setText(DISTANCE_DISABLED); |             distanceView.setText(DISTANCE_DISABLED); | ||||||
|             distanceView.setTextColor(mContext.getResources().getColor(R.color.gray)); |             distanceView.setTextColor(mContext.getResources().getColor(R.color.gray)); | ||||||
|             return; |             return; | ||||||
| 		}// 距离计算失败(值为-1标记) |         } | ||||||
|  |  | ||||||
|  |         // 场景2:距离计算失败(用-1标记失败,从缓存数据取distance字段) | ||||||
|         double distance = posModel.getRealPositionDistance(); |         double distance = posModel.getRealPositionDistance(); | ||||||
|         if (distance < 0) { |         if (distance < 0) { | ||||||
| 			distanceView.setText(DISTANCE_ERROR); | 			distanceView.setText(DISTANCE_ERROR); | ||||||
| 			distanceView.setTextColor(mContext.getResources().getColor(R.color.red)); | 			distanceView.setTextColor(mContext.getResources().getColor(R.color.red)); | ||||||
| 			return; | 			return; | ||||||
| 		}// 正常显示距离(根据距离范围设置颜色:近=绿、中=黄、远=红) | 		} | ||||||
|  |  | ||||||
|  | // 场景3:正常显示距离(按距离范围设置颜色,提升视觉区分度) | ||||||
| 		distanceView.setText(String.format(DISTANCE_FORMAT, distance)); | 		distanceView.setText(String.format(DISTANCE_FORMAT, distance)); | ||||||
| 		if (distance <= 100) { // 近距离(≤100米) | 		if (distance <= 100) { // 近距离(≤100米):绿色 | ||||||
| 			distanceView.setTextColor(mContext.getResources().getColor(R.color.green)); | 			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)); | 			distanceView.setTextColor(mContext.getResources().getColor(R.color.yellow)); | ||||||
| 		} else { // 远距离(>500米) | 		} else { // 远距离(>500米):红色 | ||||||
| 			distanceView.setTextColor(mContext.getResources().getColor(R.color.red)); | 			distanceView.setTextColor(mContext.getResources().getColor(R.color.red)); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|  |  | ||||||
| 	 - 通知服务:位置可见性变化(控制是否计算距离,优化性能) | 	 - 根据索引获取位置模型(从Activity缓存数据直接读取,无中间层,避免数据不一致) | ||||||
| 	 */ |  | ||||||
| 	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; |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	/** |  | ||||||
|  |  | ||||||
| 	 - 根据列表索引获取位置模型(从服务拉取最新数据) |  | ||||||
| 	 */ | 	 */ | ||||||
| 	private PositionModel getPositionByIndex(int index) { | 	private PositionModel getPositionByIndex(int index) { | ||||||
| 		if (mService == null || index < 0 || index >= getItemCount()) { | 		if (mCachedPositionList == null || index < 0 || index >= mCachedPositionList.size()) { | ||||||
| 			LogUtils.w("PositionAdapter", "获取位置失败:索引无效(" + index + ")"); | 			LogUtils.w(TAG, "获取位置失败:索引无效(" + index + ")或缓存数据为空"); | ||||||
| 			return null; | 			return null; | ||||||
| 		} | 		} | ||||||
| 		return mService.getPositionList().get(index); | 		return mCachedPositionList.get(index); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|  |  | ||||||
| 	 - 过滤指定位置的任务(从所有任务中筛选当前位置的任务) | 	 - 根据位置ID获取列表索引(从Activity缓存数据遍历,用于视图切换后精准刷新) | ||||||
| 	 */ | 	 */ | ||||||
| 	private ArrayList filterTasksByPosId(ArrayList allTasks, String posId) { | 	private int getPositionIndexById(String positionId) { | ||||||
| 		ArrayList targetTasks = new ArrayList(); | 		if (mCachedPositionList == null || positionId == null || positionId.isEmpty()) { | ||||||
| 		if (allTasks == null || posId == null) return targetTasks;Iterator iter = allTasks.iterator(); | 			LogUtils.w(TAG, "获取位置索引失败:缓存数据为空或位置ID无效"); | ||||||
| 		while (iter.hasNext()) { | 			return -1; | ||||||
| 			PositionTaskModel task = (PositionTaskModel)iter.next(); | 		} | ||||||
| 			if (posId.equals(task.getPositionId())) { | 		for (int i = 0; i < mCachedPositionList.size(); i++) { | ||||||
| 				targetTasks.add(task); | 			PositionModel pos = mCachedPositionList.get(i); | ||||||
|  | 			if (positionId.equals(pos.getPositionId())) { | ||||||
|  | 				return i; // 找到匹配ID,返回对应索引 | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		return targetTasks; | 		LogUtils.w(TAG, "未找到位置ID:" + positionId + ",返回无效索引-1"); | ||||||
|  | 		return -1; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|  |  | ||||||
| 	 - 刷新位置ID→索引映射(服务数据变化后调用,如新增/删除位置) | 	 - 刷新“位置→任务”映射(基于Activity最新任务缓存重建,确保本地映射与Activity数据一致) | ||||||
| 	 */ | 	 - (Activity任务数据更新后调用,避免本地映射滞后) | ||||||
| 	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); |  | ||||||
| 		} |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	/** |  | ||||||
|  |  | ||||||
| 	 - 刷新位置→任务映射(服务任务变化后调用,如新增/删除任务) |  | ||||||
| 	 */ | 	 */ | ||||||
| 	public void refreshPositionTaskMap() { | 	public void refreshPositionTaskMap() { | ||||||
| 		if (mService == null) return;try { | 		if (mCachedTaskList == null) { | ||||||
| 			mPosToTasksMap.clear(); | 			mPosToTasksMap.clear(); // 任务缓存为空时,清空本地映射 | ||||||
| 			ArrayList allTasks = mService.getPositionTasksList(); | 			LogUtils.d(TAG, "刷新任务映射:Activity任务缓存为空,已清空本地映射"); | ||||||
| 			Iterator iter = allTasks.iterator(); | 			return; | ||||||
| 			while (iter.hasNext()) { | 		}try { | ||||||
| 				PositionTaskModel task = (PositionTaskModel)iter.next(); | 			mPosToTasksMap.clear(); // 先清空旧映射,避免数据残留 | ||||||
|  | 			Iterator taskIter = mCachedTaskList.iterator(); | ||||||
|  | 			while (taskIter.hasNext()) { | ||||||
|  | 				PositionTaskModel task = (PositionTaskModel)taskIter.next(); | ||||||
| 				String posId = task.getPositionId(); | 				String posId = task.getPositionId(); | ||||||
|  | // 按位置ID分组:同一位置的任务放入同一个列表 | ||||||
| 				if (!mPosToTasksMap.containsKey(posId)) { | 				if (!mPosToTasksMap.containsKey(posId)) { | ||||||
| 					mPosToTasksMap.put(posId, new ArrayList()); | 					mPosToTasksMap.put(posId, new ArrayList()); | ||||||
| 				} | 				} | ||||||
| 				mPosToTasksMap.get(posId).add(task); | 				mPosToTasksMap.get(posId).add(task); | ||||||
| 			} | 			} | ||||||
|  | 			LogUtils.d(TAG, "刷新任务映射完成:已分组" + mPosToTasksMap.size() + "个位置的任务"); | ||||||
| 		} catch (ConcurrentModificationException e) { | 		} catch (ConcurrentModificationException e) { | ||||||
| 			LogUtils.d(TAG, "刷新任务映射失败:并发修改异常。" + e); | 			LogUtils.d(TAG, "刷新任务映射失败:并发修改Activity任务缓存。" + e); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|  |  | ||||||
| 	 - 全量更新列表(Activity 新增/删除位置后调用,同步服务数据) | 	 - 全量更新数据(接收Activity最新缓存数据,同步本地数据源+辅助缓存,刷新UI) | ||||||
|  | 	 - (Activity新增/删除位置/任务后调用,确保Adapter与Activity数据100%一致) | ||||||
| 	 */ | 	 */ | ||||||
| 	public void updateAllPositions(ArrayList newPosList) { | 	public void updateAllData(ArrayList newPosList, ArrayList newTaskList) { | ||||||
| 		if (newPosList == null) return; | // 同步Activity最新缓存数据(容错处理:避免接收null导致空指针) | ||||||
| // 刷新本地缓存 | 		this.mCachedPositionList = (newPosList != null) ? newPosList : new ArrayList(); | ||||||
| 		refreshPositionIndexMap(); | 		this.mCachedTaskList = (newTaskList != null) ? newTaskList : new ArrayList();// 刷新本地辅助缓存(确保映射与最新数据同步) | ||||||
| 		refreshPositionTaskMap(); | 		refreshPositionTaskMap(); | ||||||
| // 通知RecyclerView刷新所有项 | 		mPosDistanceViewMap.clear(); // 清空旧距离控件缓存,避免引用失效控件// 通知RecyclerView全量刷新(数据已同步,更新UI显示) | ||||||
| 		notifyDataSetChanged(); | 		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) { | 	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) { | 		if (imm != null) { | ||||||
| 			imm.hideSoftInputFromWindow(view.getWindowToken(), 0); | 			imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏软键盘 | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|  |  | ||||||
| 	 - 释放资源(Activity 销毁时调用,避免内存泄漏) | 	 - 释放资源(Activity销毁时调用,彻底避免内存泄漏) | ||||||
| 	 */ | 	 */ | ||||||
| 	public void release() { | 	public void release() { | ||||||
| // 清空本地缓存 | // 清空本地辅助缓存(解除控件、数据映射引用) | ||||||
| 		mPosIdToIndexMap.clear(); |  | ||||||
| 		mPosToTasksMap.clear(); | 		mPosToTasksMap.clear(); | ||||||
| 		mPosDistanceViewMap.clear(); | 		mPosDistanceViewMap.clear(); | ||||||
| // 告诉服务清空可见位置(停止计算距离) | // 置空回调实例(避免持有Activity引用导致内存泄漏) | ||||||
| 		if (mService != null) { |  | ||||||
| 			mService.clearVisibleDistanceViews(); |  | ||||||
| 		} |  | ||||||
| // 置空回调(避免Activity内存泄漏) |  | ||||||
| 		mOnDeleteListener = null; | 		mOnDeleteListener = null; | ||||||
| 		mOnSavePosListener = null; | 		mOnSavePosListener = null; | ||||||
| 		mOnSaveTaskListener = null; | 		mOnSaveTaskListener = null; | ||||||
| 		LogUtils.d("PositionAdapter", "资源已释放"); | // 置空数据源引用(帮助GC回收,避免残留数据占用内存) | ||||||
|  | 		mCachedPositionList = null; | ||||||
|  | 		mCachedTaskList = null; | ||||||
|  | 		LogUtils.d(TAG, "Adapter资源已完全释放"); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| // ========================================================================= | // ========================================================================= | ||||||
| // 8. 回调设置方法(Activity 调用此方法设置回调) | // 回调设置方法(LocationActivity调用,绑定交互逻辑,无冗余参数) | ||||||
| // ========================================================================= | // ========================================================================= | ||||||
| 	public void setOnDeleteClickListener(OnDeleteClickListener listener) { | 	public void setOnDeleteClickListener(OnDeleteClickListener listener) { | ||||||
| 		this.mOnDeleteListener = listener; | 		this.mOnDeleteListener = listener; | ||||||
| @@ -619,20 +505,20 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| // ========================================================================= | // ========================================================================= | ||||||
| // 9. 视图Holder类(静态内部类,避免内存泄漏) | // 视图Holder类(静态内部类,不持有外部引用,彻底避免内存泄漏) | ||||||
| // ========================================================================= | // ========================================================================= | ||||||
| 	/** | 	/** | ||||||
|  |  | ||||||
| 	 - 简单视图Holder(仅显示数据,无编辑控件) | 	 - 简单视图Holder(仅显示数据,对应布局:item_position_simple.xml) | ||||||
| 	 */ | 	 */ | ||||||
| 	public static class SimpleViewHolder extends RecyclerView.ViewHolder { | 	public static class SimpleViewHolder extends RecyclerView.ViewHolder { | ||||||
| 		TextView tvSimpleLon;   // 经度 | 		TextView tvSimpleLon;     // 经度显示控件 | ||||||
| 		TextView tvSimpleLat;   // 纬度 | 		TextView tvSimpleLat;     // 纬度显示控件 | ||||||
| 		TextView tvSimpleMemo;  // 备注 | 		TextView tvSimpleMemo;    // 备注显示控件 | ||||||
| 		TextView tvSimpleDistance; // 实时距离 | 		TextView tvSimpleDistance;// 实时距离显示控件 | ||||||
| 		public SimpleViewHolder(View itemView) { | 		public SimpleViewHolder(View itemView) { | ||||||
| 		super(itemView); | 		super(itemView); | ||||||
| // 绑定布局控件(对应 item_position_simple.xml 中的ID) | // 绑定布局控件(与XML中ID严格对应,避免运行时空指针) | ||||||
| 		tvSimpleLon = (TextView) itemView.findViewById(R.id.tv_simple_longitude); | 		tvSimpleLon = (TextView) itemView.findViewById(R.id.tv_simple_longitude); | ||||||
| 		tvSimpleLat = (TextView) itemView.findViewById(R.id.tv_simple_latitude); | 		tvSimpleLat = (TextView) itemView.findViewById(R.id.tv_simple_latitude); | ||||||
| 		tvSimpleMemo = (TextView) itemView.findViewById(R.id.tv_simple_memo); | 		tvSimpleMemo = (TextView) itemView.findViewById(R.id.tv_simple_memo); | ||||||
| @@ -642,31 +528,27 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde | |||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|  |  | ||||||
| 	 - 编辑视图Holder(含编辑控件、按钮等) | 	 - 编辑视图Holder(含编辑控件+功能按钮,对应布局:item_position_edit.xml) | ||||||
| 	 */ | 	 */ | ||||||
| 	public static class EditViewHolder extends RecyclerView.ViewHolder { | 	public static class EditViewHolder extends RecyclerView.ViewHolder { | ||||||
| 		TextView tvEditLon;     // 经度 | 		TextView tvEditLon;       // 经度显示控件(不可编辑) | ||||||
| 		TextView tvEditLat;     // 纬度 | 		TextView tvEditLat;       // 纬度显示控件(不可编辑) | ||||||
| 		EditText etEditMemo;    // 备注编辑框 | 		EditText etEditMemo;      // 备注编辑控件 | ||||||
| 		TextView tvEditDistance;// 实时距离 | 		TextView tvEditDistance;  // 实时距离显示控件 | ||||||
| 		RadioGroup rgDistanceSwitch; // 距离开关(启用/禁用) | 		RadioGroup rgDistanceSwitch; // 距离启用/禁用开关组 | ||||||
| 		RadioButton rbEnable;   // 启用距离 | 		Button btnCancel;         // 取消编辑按钮 | ||||||
| 		RadioButton rbDisable;  // 禁用距离 | 		Button btnDelete;         // 删除位置按钮 | ||||||
| 		Button btnCancel;       // 取消编辑 | 		Button btnSave;           // 保存位置按钮 | ||||||
| 		Button btnDelete;       // 删除位置 | 		Button btnAddTask;        // 新增任务按钮 | ||||||
| 		Button btnSave;         // 保存位置 | 		TextView tvTaskCount;     // 任务数量显示控件(简化设计) | ||||||
| 		Button btnAddTask;      // 新增任务 |  | ||||||
| 		TextView tvTaskCount;   // 任务数量显示(示例用,实际替换为任务列表) |  | ||||||
| 		public EditViewHolder(View itemView) { | 		public EditViewHolder(View itemView) { | ||||||
| 		super(itemView); | 		super(itemView); | ||||||
| // 绑定布局控件(对应 item_position_edit.xml 中的ID) | // 绑定布局控件(与XML中ID严格对应,避免运行时空指针) | ||||||
| 		tvEditLon = (TextView) itemView.findViewById(R.id.tv_edit_longitude); | 		tvEditLon = (TextView) itemView.findViewById(R.id.tv_edit_longitude); | ||||||
| 		tvEditLat = (TextView) itemView.findViewById(R.id.tv_edit_latitude); | 		tvEditLat = (TextView) itemView.findViewById(R.id.tv_edit_latitude); | ||||||
| 		etEditMemo = (EditText) itemView.findViewById(R.id.et_edit_memo); | 		etEditMemo = (EditText) itemView.findViewById(R.id.et_edit_memo); | ||||||
| 		tvEditDistance = (TextView) itemView.findViewById(R.id.tv_edit_distance); | 		tvEditDistance = (TextView) itemView.findViewById(R.id.tv_edit_distance); | ||||||
| 		rgDistanceSwitch = (RadioGroup) itemView.findViewById(R.id.rg_distance_switch); | 		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); | 		btnCancel = (Button) itemView.findViewById(R.id.btn_edit_cancel); | ||||||
| 		btnDelete = (Button) itemView.findViewById(R.id.btn_edit_delete); | 		btnDelete = (Button) itemView.findViewById(R.id.btn_edit_delete); | ||||||
| 		btnSave = (Button) itemView.findViewById(R.id.btn_edit_save); | 		btnSave = (Button) itemView.findViewById(R.id.btn_edit_save); | ||||||
| @@ -675,4 +557,3 @@ public class PositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde | |||||||
| 	} | 	} | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -14,18 +14,22 @@ public class AppConfigsModel extends BaseBean { | |||||||
|      |      | ||||||
|     public static final String TAG = "AppConfigsModel"; |     public static final String TAG = "AppConfigsModel"; | ||||||
| 	 | 	 | ||||||
| 	boolean isEnableDistanceRefreshService = false; | 	boolean isEnableMainService; | ||||||
|  |  | ||||||
| 	public AppConfigsModel(boolean isEnableDistanceRefreshService) { | 	public AppConfigsModel(boolean isEnableMainService) { | ||||||
| 		this.isEnableDistanceRefreshService = isEnableDistanceRefreshService; | 		this.isEnableMainService = isEnableMainService; | ||||||
| 	} | 	} | ||||||
| 	 | 	 | ||||||
| 	public void setIsEnableDistanceRefreshService(boolean isEnableDistanceRefreshService) { | 	public AppConfigsModel() { | ||||||
| 		this.isEnableDistanceRefreshService = isEnableDistanceRefreshService; | 		this.isEnableMainService = false; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	public boolean isEnableDistanceRefreshService() { | 	public void setIsEnableMainService(boolean isEnableMainService) { | ||||||
| 		return isEnableDistanceRefreshService; | 		this.isEnableMainService = isEnableMainService; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	public boolean isEnableMainService() { | ||||||
|  | 		return isEnableMainService; | ||||||
| 	} | 	} | ||||||
|      |      | ||||||
|     @Override |     @Override | ||||||
| @@ -37,7 +41,7 @@ public class AppConfigsModel extends BaseBean { | |||||||
| 	@Override | 	@Override | ||||||
| 	public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException { | 	public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException { | ||||||
| 		super.writeThisToJsonWriter(jsonWriter); | 		super.writeThisToJsonWriter(jsonWriter); | ||||||
| 		jsonWriter.name("isEnableDistanceRefreshService").value(isEnableDistanceRefreshService()); | 		jsonWriter.name("isEnableDistanceRefreshService").value(isEnableMainService()); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// JSON反序列化(加载位置数据,校验字段) | 	// JSON反序列化(加载位置数据,校验字段) | ||||||
| @@ -47,7 +51,7 @@ public class AppConfigsModel extends BaseBean { | |||||||
| 			return true;  | 			return true;  | ||||||
| 		} else { | 		} else { | ||||||
| 			if (name.equals("isEnableDistanceRefreshService")) { | 			if (name.equals("isEnableDistanceRefreshService")) { | ||||||
| 				setIsEnableDistanceRefreshService(jsonReader.nextBoolean()); | 				setIsEnableMainService(jsonReader.nextBoolean()); | ||||||
| 			} else { | 			} else { | ||||||
| 				return false; | 				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(); | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
| @@ -3,19 +3,27 @@ package cc.winboll.studio.positions.services; | |||||||
| /** | /** | ||||||
|  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> |  * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> | ||||||
|  * @Date 2025/09/30 19:53 |  * @Date 2025/09/30 19:53 | ||||||
|  * @Describe 位置距离服务:管理数据+定时计算距离+适配Adapter(Java 7 兼容) |  * @Describe 位置距离服务:管理数据+定时计算距离+适配Adapter(Java 7 兼容)+ GPS信号加载 | ||||||
|  */ |  */ | ||||||
| import android.app.Service; | import android.app.Service; | ||||||
|  | import android.content.Context; | ||||||
| import android.content.Intent; | import android.content.Intent; | ||||||
|  | import android.content.pm.PackageManager; | ||||||
|  | import android.location.Location; | ||||||
|  | import android.location.LocationListener; | ||||||
|  | import android.location.LocationManager; | ||||||
| import android.os.Binder; | import android.os.Binder; | ||||||
|  | import android.os.Build; | ||||||
|  | import android.os.Bundle; | ||||||
| import android.os.IBinder; | import android.os.IBinder; | ||||||
| import android.os.Looper; | import android.os.Looper; | ||||||
|  | import android.widget.Toast; | ||||||
| import cc.winboll.studio.libappbase.LogUtils; | import cc.winboll.studio.libappbase.LogUtils; | ||||||
| import cc.winboll.studio.positions.adapters.PositionAdapter; | import cc.winboll.studio.positions.adapters.PositionAdapter; | ||||||
|  | import cc.winboll.studio.positions.models.AppConfigsModel; | ||||||
| import cc.winboll.studio.positions.models.PositionModel; | import cc.winboll.studio.positions.models.PositionModel; | ||||||
| import cc.winboll.studio.positions.models.PositionTaskModel; | import cc.winboll.studio.positions.models.PositionTaskModel; | ||||||
|  | import cc.winboll.studio.positions.utils.NotificationUtil; | ||||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||||
| import java.util.HashSet; | import java.util.HashSet; | ||||||
| import java.util.Iterator; | import java.util.Iterator; | ||||||
| @@ -23,36 +31,242 @@ import java.util.Set; | |||||||
| import java.util.concurrent.Executors; | import java.util.concurrent.Executors; | ||||||
| import java.util.concurrent.ScheduledExecutorService; | import java.util.concurrent.ScheduledExecutorService; | ||||||
| import java.util.concurrent.TimeUnit; | import java.util.concurrent.TimeUnit; | ||||||
| import cc.winboll.studio.positions.models.AppConfigsModel; |  | ||||||
|  |  | ||||||
| /** | /** | ||||||
|  * 核心职责: |  * 核心职责: | ||||||
|  * 1. 实现 PositionAdapter.DistanceServiceInterface 接口,解耦Adapter与服务 |  * 1. 实现 PositionAdapter.DistanceServiceInterface 接口,解耦Adapter与服务 | ||||||
|  * 2. 单例式管理位置/任务数据,提供安全增删改查接口 |  * 2. 单例式管理位置/任务数据,提供安全增删改查接口 | ||||||
|  * 3. 后台单线程定时计算可见位置距离,主线程回调更新UI |  * 3. 后台单线程定时计算可见位置距离,主线程回调更新UI | ||||||
|  * 4. 严格Java 7语法:无Lambda/Stream,显式迭代器/匿名内部类 |  * 4. 内置GPS信号加载(通过LocationManager实时获取位置,解决“等待GPS信号”问题) | ||||||
|  |  * 5. 服务启动时启动前台通知(保活后台GPS功能,符合系统规范) | ||||||
|  |  * 6. 严格Java 7语法:无Lambda/Stream,显式迭代器/匿名内部类 | ||||||
|  */ |  */ | ||||||
| public class DistanceRefreshService extends Service implements PositionAdapter.DistanceServiceInterface { | public class DistanceRefreshService extends Service { | ||||||
|     public static final String TAG = "DistanceRefreshService"; |     public static final String TAG = "DistanceRefreshService"; | ||||||
|  | 	 | ||||||
|  | 	 | ||||||
|     // 服务状态与配置 |     // 服务状态与配置 | ||||||
|     private boolean isServiceRunning = false; |     private boolean isServiceRunning = false; | ||||||
|     private final ScheduledExecutorService distanceExecutor; // 定时计算线程池(单线程) |     private final ScheduledExecutorService distanceExecutor; // 定时计算线程池(单线程) | ||||||
|     private static final int REFRESH_INTERVAL = 3; // 距离刷新间隔(秒) |     private static final int REFRESH_INTERVAL = 3; // 距离刷新间隔(秒) | ||||||
|  |     // 前台通知相关:记录是否已启动前台服务(避免重复调用startForeground) | ||||||
|  |     private boolean isForegroundServiceStarted = false; | ||||||
|  |  | ||||||
|  |     // ---------------------- 新增:GPS信号加载核心变量 ---------------------- | ||||||
|  |     private LocationManager mLocationManager; // 系统GPS管理类(核心) | ||||||
|  |     private LocationListener mGpsLocationListener; // GPS位置监听回调 | ||||||
|  |     private static final long GPS_UPDATE_INTERVAL = 2000; // GPS位置更新间隔(2秒,平衡耗电与实时性) | ||||||
|  |     private static final float GPS_UPDATE_DISTANCE = 1; // 位置变化超过1米时更新(避免频繁回调) | ||||||
|  |     private boolean isGpsEnabled = false; // GPS是否已开启(系统设置中) | ||||||
|  |     private boolean isGpsPermissionGranted = false; // 是否拥有GPS权限 | ||||||
|  |  | ||||||
|     // 核心数据存储(服务内唯一数据源,避免外部直接修改) |     // 核心数据存储(服务内唯一数据源,避免外部直接修改) | ||||||
|     private final ArrayList<PositionModel> mPositionList = new ArrayList<PositionModel>(); |     private final ArrayList<PositionModel> mPositionList = new ArrayList<PositionModel>(); | ||||||
|     private final ArrayList<PositionTaskModel> mTaskList = new ArrayList<PositionTaskModel>(); |     private final ArrayList<PositionTaskModel> mTaskList = new ArrayList<PositionTaskModel>(); | ||||||
|     private final Set<String> mVisiblePositionIds = new HashSet<String>(); // 可见位置ID(优化性能) |     private final Set<String> mVisiblePositionIds = new HashSet<String>(); // 可见位置ID(优化性能) | ||||||
|     private PositionModel mCurrentGpsPosition; // 当前GPS位置(外部传入) |     private PositionModel mCurrentGpsPosition; // 当前GPS位置(外部传入/内部GPS获取) | ||||||
|  |  | ||||||
|     // 服务绑定与UI回调 |     // 服务绑定与UI回调 | ||||||
|     private final IBinder mBinder = new DistanceBinder(); |     private final IBinder mBinder = new DistanceBinder(); | ||||||
|     private PositionAdapter.OnDistanceUpdateReceiver mDistanceReceiver; // Adapter回调接收器 |  | ||||||
|  |  | ||||||
|     // ---------------------- 构造初始化(线程池提前创建) ---------------------- |     // ---------------------- 构造初始化(线程池+GPS监听器提前创建) ---------------------- | ||||||
|  | 	// 关键:添加/修改为 PUBLIC 无参构造函数 | ||||||
|  |      | ||||||
|     public DistanceRefreshService() { |     public DistanceRefreshService() { | ||||||
|         // Java 7 显式初始化线程池(单线程,避免并发修改数据) |         // Java 7 显式初始化线程池(单线程,避免并发修改数据) | ||||||
|         distanceExecutor = Executors.newSingleThreadScheduledExecutor(); |         distanceExecutor = Executors.newSingleThreadScheduledExecutor(); | ||||||
|  |         // 初始化GPS位置监听器(接收系统GPS位置更新) | ||||||
|  |         initGpsLocationListener(); | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     // ---------------------- 新增:GPS核心逻辑(初始化监听+权限/状态检查+启动定位) ---------------------- | ||||||
|  |     /** | ||||||
|  |      * 初始化GPS位置监听器:系统GPS位置变化时触发,实时更新当前位置 | ||||||
|  |      */ | ||||||
|  |     private void initGpsLocationListener() { | ||||||
|  |         // Java 7 匿名内部类实现 LocationListener(接收GPS位置回调) | ||||||
|  |         mGpsLocationListener = new LocationListener() { | ||||||
|  |             // GPS位置发生变化时回调(核心:更新当前GPS位置) | ||||||
|  |             @Override | ||||||
|  |             public void onLocationChanged(Location location) { | ||||||
|  |                 if (location != null) { | ||||||
|  |                     // 将系统Location对象转为自定义PositionModel(适配现有逻辑) | ||||||
|  |                     PositionModel gpsPos = new PositionModel(); | ||||||
|  |                     gpsPos.setLatitude(location.getLatitude()); // 纬度 | ||||||
|  |                     gpsPos.setLongitude(location.getLongitude()); // 经度 | ||||||
|  |                     gpsPos.setPositionId("CURRENT_GPS_POS"); // 标记为“当前GPS位置”(自定义ID) | ||||||
|  |                     gpsPos.setMemo("实时GPS位置"); | ||||||
|  |  | ||||||
|  |                     // 同步GPS位置到服务(触发距离计算+通知更新) | ||||||
|  |                     syncCurrentGpsPosition(gpsPos); | ||||||
|  |                     LogUtils.d(TAG, "GPS位置更新:纬度=" + location.getLatitude() + ",经度=" + location.getLongitude()); | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |  | ||||||
|  |             // GPS状态变化时回调(如从“搜索中”变为“可用”) | ||||||
|  |             @Override | ||||||
|  |             public void onStatusChanged(String provider, int status, Bundle extras) { | ||||||
|  |                 if (provider.equals(LocationManager.GPS_PROVIDER)) { | ||||||
|  |                     switch (status) { | ||||||
|  |                         case LocationProvider.AVAILABLE: | ||||||
|  |                             LogUtils.d(TAG, "GPS状态:已就绪(可用)"); | ||||||
|  |                             updateNotificationGpsStatus("GPS已就绪,正在获取位置..."); | ||||||
|  |                             break; | ||||||
|  |                         case LocationProvider.OUT_OF_SERVICE: | ||||||
|  |                             LogUtils.w(TAG, "GPS状态:无服务(信号弱/无信号)"); | ||||||
|  |                             updateNotificationGpsStatus("GPS无服务,尝试重新连接..."); | ||||||
|  |                             break; | ||||||
|  |                         case LocationProvider.TEMPORARILY_UNAVAILABLE: | ||||||
|  |                             LogUtils.w(TAG, "GPS状态:临时不可用(如遮挡)"); | ||||||
|  |                             updateNotificationGpsStatus("GPS临时不可用,稍后重试..."); | ||||||
|  |                             break; | ||||||
|  |                     } | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |  | ||||||
|  |             // GPS被开启时回调(用户在设置中打开GPS) | ||||||
|  |             @Override | ||||||
|  |             public void onProviderEnabled(String provider) { | ||||||
|  |                 if (provider.equals(LocationManager.GPS_PROVIDER)) { | ||||||
|  |                     isGpsEnabled = true; | ||||||
|  |                     LogUtils.d(TAG, "GPS已开启(用户手动打开)"); | ||||||
|  |                     updateNotificationGpsStatus("GPS已开启,正在获取位置..."); | ||||||
|  |                     // 重新启动GPS定位(确保获取最新位置) | ||||||
|  |                     startGpsLocation(); | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |  | ||||||
|  |             // GPS被关闭时回调(用户在设置中关闭GPS) | ||||||
|  |             @Override | ||||||
|  |             public void onProviderDisabled(String provider) { | ||||||
|  |                 if (provider.equals(LocationManager.GPS_PROVIDER)) { | ||||||
|  |                     isGpsEnabled = false; | ||||||
|  |                     mCurrentGpsPosition = null; // 清空无效GPS位置 | ||||||
|  |                     LogUtils.w(TAG, "GPS已关闭(用户手动关闭)"); | ||||||
|  |                     updateNotificationGpsStatus("GPS已关闭,请在设置中开启"); | ||||||
|  |                     // 提示用户打开GPS(主线程显示Toast) | ||||||
|  |                     showToastOnMainThread("GPS已关闭,无法获取位置,请在设置中开启"); | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         }; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * 检查GPS权限+系统状态(解决“等待GPS信号”的前提:权限+GPS开启) | ||||||
|  |      * @return true:权限+状态都满足;false:缺少权限或GPS未开启 | ||||||
|  |      */ | ||||||
|  |     private boolean checkGpsReady() { | ||||||
|  |         // 1. 检查GPS权限(前台精确定位权限,必须拥有) | ||||||
|  |         isGpsPermissionGranted = checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)  | ||||||
|  | 			== PackageManager.PERMISSION_GRANTED; | ||||||
|  |  | ||||||
|  |         // 2. 检查GPS是否开启(系统设置中) | ||||||
|  |         if (mLocationManager == null) { | ||||||
|  |             mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); | ||||||
|  |         } | ||||||
|  |         isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); | ||||||
|  |  | ||||||
|  |         // 3. 异常场景处理(权限缺失/GPS未开启) | ||||||
|  |         if (!isGpsPermissionGranted) { | ||||||
|  |             LogUtils.e(TAG, "GPS准备失败:缺少精确定位权限"); | ||||||
|  |             updateNotificationGpsStatus("缺少定位权限,无法获取GPS"); | ||||||
|  |             showToastOnMainThread("请授予定位权限,否则无法获取GPS位置"); | ||||||
|  |             return false; | ||||||
|  |         } | ||||||
|  |         if (!isGpsEnabled) { | ||||||
|  |             LogUtils.e(TAG, "GPS准备失败:系统GPS未开启"); | ||||||
|  |             updateNotificationGpsStatus("GPS未开启,请在设置中打开"); | ||||||
|  |             showToastOnMainThread("GPS已关闭,请在设置中开启以获取位置"); | ||||||
|  |             return false; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         // 权限+状态都满足 | ||||||
|  |         LogUtils.d(TAG, "GPS准备就绪:权限已获取,GPS已开启"); | ||||||
|  |         return true; | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * 启动GPS定位(注册监听器,开始接收系统GPS位置更新) | ||||||
|  |      */ | ||||||
|  |     private void startGpsLocation() { | ||||||
|  |         // 先检查GPS是否就绪(避免无效调用) | ||||||
|  |         if (!checkGpsReady()) { | ||||||
|  |             return; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         try { | ||||||
|  |             // 注册GPS监听器:指定GPS provider、更新间隔、距离变化阈值 | ||||||
|  |             mLocationManager.requestLocationUpdates( | ||||||
|  | 				LocationManager.GPS_PROVIDER, | ||||||
|  | 				GPS_UPDATE_INTERVAL, | ||||||
|  | 				GPS_UPDATE_DISTANCE, | ||||||
|  | 				mGpsLocationListener, | ||||||
|  | 				Looper.getMainLooper() // 在主线程回调(避免跨线程问题) | ||||||
|  |             ); | ||||||
|  |  | ||||||
|  |             // 额外优化:立即获取最近一次缓存的GPS位置(避免等待首次定位) | ||||||
|  |             Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); | ||||||
|  |             if (lastKnownLocation != null) { | ||||||
|  |                 PositionModel lastGpsPos = new PositionModel(); | ||||||
|  |                 lastGpsPos.setLatitude(lastKnownLocation.getLatitude()); | ||||||
|  |                 lastGpsPos.setLongitude(lastKnownLocation.getLongitude()); | ||||||
|  |                 lastGpsPos.setPositionId("CURRENT_GPS_POS"); | ||||||
|  |                 syncCurrentGpsPosition(lastGpsPos); | ||||||
|  |                 LogUtils.d(TAG, "已获取最近缓存的GPS位置:纬度=" + lastKnownLocation.getLatitude()); | ||||||
|  |             } else { | ||||||
|  |                 LogUtils.d(TAG, "无缓存GPS位置,等待实时定位..."); | ||||||
|  |                 updateNotificationGpsStatus("GPS搜索中(请移至开阔地带)"); | ||||||
|  |             } | ||||||
|  |  | ||||||
|  |         } catch (SecurityException e) { | ||||||
|  |             // 异常防护:避免权限突然被回收导致崩溃 | ||||||
|  |             LogUtils.e(TAG, "启动GPS定位失败(权限异常):" + e.getMessage()); | ||||||
|  |             isGpsPermissionGranted = false; | ||||||
|  |             updateNotificationGpsStatus("定位权限异常,无法获取GPS"); | ||||||
|  |         } catch (Exception e) { | ||||||
|  |             LogUtils.e(TAG, "启动GPS定位失败:" + e.getMessage()); | ||||||
|  |             updateNotificationGpsStatus("GPS启动失败,尝试重试..."); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * 停止GPS定位(服务销毁/暂停时调用,避免耗电+内存泄漏) | ||||||
|  |      */ | ||||||
|  |     private void stopGpsLocation() { | ||||||
|  |         if (mLocationManager != null && mGpsLocationListener != null && isGpsPermissionGranted) { | ||||||
|  |             try { | ||||||
|  |                 mLocationManager.removeUpdates(mGpsLocationListener); | ||||||
|  |                 LogUtils.d(TAG, "GPS定位已停止(移除监听器)"); | ||||||
|  |             } catch (Exception e) { | ||||||
|  |                 LogUtils.e(TAG, "停止GPS定位失败:" + e.getMessage()); | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     // ---------------------- 新增:辅助方法(通知更新+主线程Toast) ---------------------- | ||||||
|  |     /** | ||||||
|  |      * 统一更新通知栏的GPS状态文本(简化代码,避免重复) | ||||||
|  |      */ | ||||||
|  |     private void updateNotificationGpsStatus(String statusText) { | ||||||
|  |         if (isForegroundServiceStarted) { | ||||||
|  |             NotificationUtil.updateForegroundServiceStatus(this, statusText); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  |  | ||||||
|  |     /** | ||||||
|  |      * 在主线程显示Toast(避免子线程无法显示Toast的问题) | ||||||
|  |      */ | ||||||
|  |     private void showToastOnMainThread(final String message) { | ||||||
|  |         if (Looper.myLooper() == Looper.getMainLooper()) { | ||||||
|  |             Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); | ||||||
|  |         } else { | ||||||
|  |             new android.os.Handler(Looper.getMainLooper()).post(new Runnable() { | ||||||
|  | 					@Override | ||||||
|  | 					public void run() { | ||||||
|  | 						Toast.makeText(DistanceRefreshService.this, message, Toast.LENGTH_SHORT).show(); | ||||||
|  | 					} | ||||||
|  | 				}); | ||||||
|  |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     // ---------------------- Binder 内部类(供外部绑定服务) ---------------------- |     // ---------------------- Binder 内部类(供外部绑定服务) ---------------------- | ||||||
| @@ -65,10 +279,40 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     // ---------------------- 服务生命周期方法(严格管理资源) ---------------------- |     // ---------------------- 服务生命周期方法(集成GPS启停逻辑) ---------------------- | ||||||
|  |  | ||||||
|  | 	// 服务单例实例(私有静态) | ||||||
|  | 	// 1. 单例实例(volatile确保多线程可见性) | ||||||
|  |     private static volatile DistanceRefreshService sInstance; | ||||||
|  |     // 2. 单独持有ApplicationContext(避免内存泄漏+确保非null) | ||||||
|  |     private static Context sAppContext; | ||||||
|  |     // 单例PUBLIC方法(供外部获取实例,确保全局唯一) | ||||||
|  |     public static synchronized DistanceRefreshService getInstance() { | ||||||
|  | 	// 4. 修复后的单例方法:先判空,再返回(避免空指针) | ||||||
|  |      | ||||||
|  |         // 第一步:先判断实例是否存在(未创建则返回null,不强行调用Context) | ||||||
|  |         if (sInstance == null) { | ||||||
|  |             // 可选:若调用时Service未启动,主动启动Service(避免后续空指针) | ||||||
|  |              Intent intent = new Intent(sAppContext, DistanceRefreshService.class); | ||||||
|  |              sAppContext.startService(intent); | ||||||
|  |             return null; // 或抛明确异常(如"Service未启动"),不触发空指针 | ||||||
|  |         } | ||||||
|  |         // 第二步:实例存在时,确保Context非null(双重保险) | ||||||
|  |         if (sAppContext == null) { | ||||||
|  |             sAppContext = sInstance.getApplicationContext(); | ||||||
|  |         } | ||||||
|  |         return sInstance; | ||||||
|  |     } | ||||||
|  |  | ||||||
|     @Override |     @Override | ||||||
|     public void onCreate() { |     public void onCreate() { | ||||||
|         super.onCreate(); |         super.onCreate(); | ||||||
|  | 		sInstance = this; // 此时Service已创建,Context非null | ||||||
|  |         // 保存ApplicationContext(全局唯一,不会因Service销毁而失效) | ||||||
|  |         sAppContext = getApplicationContext(); | ||||||
|  | 		 | ||||||
|  |         // 初始化GPS管理器(提前获取系统服务,避免启动时延迟) | ||||||
|  |         mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); | ||||||
|         LogUtils.d(TAG, "服务 onCreate:初始化完成,等待启动命令"); |         LogUtils.d(TAG, "服务 onCreate:初始化完成,等待启动命令"); | ||||||
|         run(); |         run(); | ||||||
|     } |     } | ||||||
| @@ -77,117 +321,186 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
|     public int onStartCommand(Intent intent, int flags, int startId) { |     public int onStartCommand(Intent intent, int flags, int startId) { | ||||||
|         run(); |         run(); | ||||||
|         AppConfigsModel bean = AppConfigsModel.loadBean(DistanceRefreshService.this, AppConfigsModel.class); |         AppConfigsModel bean = AppConfigsModel.loadBean(DistanceRefreshService.this, AppConfigsModel.class); | ||||||
|         boolean isEnableService = (bean == null) ? false : bean.isEnableDistanceRefreshService(); |         boolean isEnableService = (bean == null) ? false : bean.isEnableMainService(); | ||||||
|  |         // 服务启用时返回START_STICKY(被杀死后尝试重启),禁用时返回默认值 | ||||||
|         return isEnableService ? Service.START_STICKY : super.onStartCommand(intent, flags, startId); |         return isEnableService ? Service.START_STICKY : super.onStartCommand(intent, flags, startId); | ||||||
|     } |     } | ||||||
|  |  | ||||||
| 	void run() { |     public void run() { | ||||||
|         // 仅服务未运行时启动(避免重复启动) |         // 仅服务未运行时启动(避免重复启动) | ||||||
|         if (!isServiceRunning) { |         if (!isServiceRunning) { | ||||||
|             isServiceRunning = true; |             isServiceRunning = true; | ||||||
|  | 			 | ||||||
|  | 			mLocationManager = (LocationManager) sInstance.getApplicationContext().getSystemService(Context.LOCATION_SERVICE); | ||||||
|  |             initGpsLocationListener(); | ||||||
|  | 			 | ||||||
|             startDistanceRefreshTask(); // 启动定时距离计算 |             startDistanceRefreshTask(); // 启动定时距离计算 | ||||||
|             LogUtils.d(TAG, "服务 onStartCommand:启动成功,刷新间隔=" + REFRESH_INTERVAL + "秒"); |             startForegroundNotification(); // 启动前台通知 | ||||||
|  |             startGpsLocation(); // 新增:启动GPS定位(核心修复:解决“等待GPS信号”) | ||||||
|  |             LogUtils.d(TAG, "服务 onStartCommand:启动成功,刷新间隔=" + REFRESH_INTERVAL + "秒,前台通知+GPS已启动"); | ||||||
|         } else { |         } else { | ||||||
|             LogUtils.w(TAG, "服务 onStartCommand:已在运行,无需重复启动"); |             LogUtils.w(TAG, "服务 onStartCommand:已在运行,无需重复启动(前台通知:" + (isForegroundServiceStarted ? "已启动" : "未启动") + " | GPS:" + (isGpsEnabled ? "已开启" : "未开启") + ")"); | ||||||
|  |             // 异常场景恢复:补全未启动的组件 | ||||||
|  |             if (!isForegroundServiceStarted) { | ||||||
|  |                 startForegroundNotification(); | ||||||
|  |                 LogUtils.d(TAG, "服务 run:前台通知未启动,已恢复"); | ||||||
|  |             } | ||||||
|  |             if (isServiceRunning && !isGpsEnabled) { | ||||||
|  |                 startGpsLocation(); | ||||||
|  |                 LogUtils.d(TAG, "服务 run:GPS未启动,已恢复"); | ||||||
|  |             } | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     @Override |     @Override | ||||||
|     public IBinder onBind(Intent intent) { |     public IBinder onBind(Intent intent) { | ||||||
|         LogUtils.d(TAG, "服务 onBind:外部绑定成功(运行状态:" + (isServiceRunning ? "是" : "否") + ")"); | 		return null; // 按你的业务逻辑返回,无绑定需求则保留null | ||||||
|         return mBinder; // 返回Binder实例,供外部获取服务 |         //LogUtils.d(TAG, "服务 onBind:外部绑定成功(运行状态:" + (isServiceRunning ? "是" : "否") + " | GPS状态:" + (isGpsEnabled ? "可用" : "不可用") + ")"); | ||||||
|  |         //return mBinder; // 返回Binder实例,供外部获取服务 | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     @Override |     /*@Override | ||||||
| 	 public boolean onUnbind(Intent intent) { | 	 public boolean onUnbind(Intent intent) { | ||||||
| 	 LogUtils.d(TAG, "服务 onUnbind:外部解绑,清理回调与可见位置"); | 	 LogUtils.d(TAG, "服务 onUnbind:外部解绑,清理回调与可见位置"); | ||||||
| 	 // 解绑后清理资源,避免内存泄漏 | 	 // 解绑后清理资源,避免内存泄漏 | ||||||
| 	 mDistanceReceiver = null; | 	 mDistanceReceiver = null; | ||||||
| 	 mVisiblePositionIds.clear(); | 	 mVisiblePositionIds.clear(); | ||||||
|  | 	 // 解绑时不停止GPS(服务仍在后台运行,需持续获取位置) | ||||||
| 	 return super.onUnbind(intent); | 	 return super.onUnbind(intent); | ||||||
|     } | 	 }*/ | ||||||
|  |  | ||||||
|     @Override |     @Override | ||||||
|     public void onDestroy() { |     public void onDestroy() { | ||||||
|         super.onDestroy(); |         super.onDestroy(); | ||||||
|         // 停止线程池+清空数据(服务销毁后释放资源) | 		sInstance = null; // 释放实例,避免内存泄漏 | ||||||
|         stopDistanceRefreshTask(); |         // sAppContext 不清空(ApplicationContext全局有效) | ||||||
|         clearAllData(); | 		 | ||||||
|  |         // 停止所有核心组件+释放资源(避免内存泄漏/耗电) | ||||||
|  |         stopDistanceRefreshTask(); // 停止距离计算 | ||||||
|  |         stopGpsLocation(); // 新增:停止GPS定位(关键:避免服务销毁后仍耗电) | ||||||
|  |         clearAllData(); // 清空数据 | ||||||
|  |         stopForeground(true); // 停止前台服务(移除通知) | ||||||
|  |  | ||||||
|  |         // 重置状态标记 | ||||||
|  |         isForegroundServiceStarted = false; | ||||||
|         isServiceRunning = false; |         isServiceRunning = false; | ||||||
|         LogUtils.d(TAG, "服务 onDestroy:销毁完成,资源已释放"); |         isGpsEnabled = false; | ||||||
|  |         mLocationManager = null; // 释放GPS管理器引用 | ||||||
|  |  | ||||||
|  |         LogUtils.d(TAG, "服务 onDestroy:销毁完成,资源已释放(GPS+前台通知+线程池)"); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     // ---------------------- 核心:定时距离计算(后台线程+主线程回调) ---------------------- |     // ---------------------- 前台服务通知管理(与GPS状态联动优化) ---------------------- | ||||||
|     /** |     /** | ||||||
|      * 启动定时距离计算任务(延迟1秒开始,周期执行) |      * 启动前台服务通知(调用NotificationUtils创建通知,确保仅启动一次) | ||||||
|  |      */ | ||||||
|  |     private void startForegroundNotification() { | ||||||
|  |         // 1. 校验:避免重复调用startForeground(系统不允许重复启动) | ||||||
|  |         if (isForegroundServiceStarted) { | ||||||
|  |             LogUtils.w(TAG, "startForegroundNotification:前台通知已启动,无需重复执行"); | ||||||
|  |             return; | ||||||
|  |         } | ||||||
|  |  | ||||||
|  |         try { | ||||||
|  | // 2. 初始化通知状态文本(根据GPS初始状态动态显示,避免固定“等待”) | ||||||
|  | 			String initialStatus; | ||||||
|  | 			if (isGpsPermissionGranted && isGpsEnabled) { | ||||||
|  | 				initialStatus = "GPS已就绪,正在获取位置(刷新间隔" + REFRESH_INTERVAL + "秒)"; | ||||||
|  | 			} else if (!isGpsPermissionGranted) { | ||||||
|  | 				initialStatus = "缺少定位权限,无法获取GPS位置"; | ||||||
|  | 			} else { | ||||||
|  | 				initialStatus = "GPS未开启,请在设置中打开"; | ||||||
|  | 			} | ||||||
|  |  | ||||||
|  |  | ||||||
|  | // 5. 标记前台服务已启动 | ||||||
|  | 			isForegroundServiceStarted = true; | ||||||
|  | 			LogUtils.d(TAG, "startForegroundNotification:前台服务通知启动成功,初始状态:" + initialStatus); | ||||||
|  |  | ||||||
|  | 		} catch (Exception e) { | ||||||
|  | // 捕获异常(如上下文失效、通知渠道未创建) | ||||||
|  | 			isForegroundServiceStarted = false; | ||||||
|  | 			LogUtils.d(TAG, "startForegroundNotification:前台通知启动失败" + e); | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | // ---------------------- 核心:定时距离计算(与GPS状态联动优化) ---------------------- | ||||||
|  | 	/** | ||||||
|  |  | ||||||
|  | 	 - 启动定时距离计算任务(延迟1秒开始,周期执行) | ||||||
| 	 */ | 	 */ | ||||||
| 	private void startDistanceRefreshTask() { | 	private void startDistanceRefreshTask() { | ||||||
| 		if (distanceExecutor == null || distanceExecutor.isShutdown()) { | 		if (distanceExecutor == null || distanceExecutor.isShutdown()) { | ||||||
| 			LogUtils.e(TAG, "启动计算失败:线程池未初始化/已关闭"); | 			LogUtils.e(TAG, "启动计算失败:线程池未初始化/已关闭"); | ||||||
| 			return; | 			return; | ||||||
|         } | 		}distanceExecutor.scheduleAtFixedRate(new Runnable() { | ||||||
|  |  | ||||||
|         // Java 7:匿名内部类实现 Runnable(不使用Lambda) |  | ||||||
|         distanceExecutor.scheduleAtFixedRate(new Runnable() { |  | ||||||
| 				@Override | 				@Override | ||||||
| 				public void run() { | 				public void run() { | ||||||
| 					// 仅满足所有条件时计算:服务运行+GPS有效+有可见位置 | // 优化判断逻辑:先检查GPS核心状态,再决定是否计算 | ||||||
|  | 					if (!isGpsPermissionGranted) { | ||||||
|  | 						LogUtils.d(TAG, "跳过距离计算:缺少定位权限"); | ||||||
|  | 						updateNotificationGpsStatus("缺少定位权限,无法计算距离"); | ||||||
|  | 						return; | ||||||
|  | 					} | ||||||
|  | 					if (!isGpsEnabled) { | ||||||
|  | 						LogUtils.d(TAG, "跳过距离计算:GPS未开启"); | ||||||
|  | 						updateNotificationGpsStatus("GPS未开启,无法计算距离"); | ||||||
|  | 						return; | ||||||
|  | 					}// 原有逻辑:服务运行+GPS位置有效+有可见位置才计算 | ||||||
| 					if (isServiceRunning && mCurrentGpsPosition != null && !mVisiblePositionIds.isEmpty()) { | 					if (isServiceRunning && mCurrentGpsPosition != null && !mVisiblePositionIds.isEmpty()) { | ||||||
| 						calculateVisiblePositionDistance(); | 						calculateVisiblePositionDistance(); | ||||||
|  | // 计算后更新通知(显示实时GPS+距离计算状态) | ||||||
|  | 						syncGpsStatusToNotification(); | ||||||
| 					} else { | 					} else { | ||||||
| 						// 打印跳过原因(便于调试) |  | ||||||
| 						String reason = ""; | 						String reason = ""; | ||||||
| 						if (!isServiceRunning) reason = "服务未运行"; | 						if (!isServiceRunning) reason = "服务未运行"; | ||||||
| 						else if (mCurrentGpsPosition == null) reason = "GPS无效"; | 						else if (mCurrentGpsPosition == null) reason = "GPS信号弱(获取位置中)"; | ||||||
| 						else if (mVisiblePositionIds.isEmpty()) reason = "无可见位置"; | 						else if (mVisiblePositionIds.isEmpty()) reason = "无可见位置(无需计算)"; | ||||||
| 						LogUtils.d(TAG, "跳过距离计算:" + reason); | 						LogUtils.d(TAG, "跳过距离计算:" + reason);// 针对性更新通知文本(用户明确知道当前状态) | ||||||
|  | 						if (isForegroundServiceStarted) { | ||||||
|  | 							if (mCurrentGpsPosition == null) { | ||||||
|  | 								updateNotificationGpsStatus("GPS信号弱,移至开阔地带重试..."); | ||||||
|  | 							} else if (mVisiblePositionIds.isEmpty()) { | ||||||
|  | 								updateNotificationGpsStatus("无可见位置,距离计算暂停"); | ||||||
|  | 							} | ||||||
|  | 						} | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
| 			}, 1, REFRESH_INTERVAL, TimeUnit.SECONDS); | 			}, 1, REFRESH_INTERVAL, TimeUnit.SECONDS); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|      * 停止定时计算任务(强制关闭线程池) |  | ||||||
|  | 	 - 停止定时计算任务(强制关闭线程池) | ||||||
| 	 */ | 	 */ | ||||||
| 	private void stopDistanceRefreshTask() { | 	private void stopDistanceRefreshTask() { | ||||||
| 		if (distanceExecutor != null && !distanceExecutor.isShutdown()) { | 		if (distanceExecutor != null && !distanceExecutor.isShutdown()) { | ||||||
|             distanceExecutor.shutdownNow(); // 立即停止所有任务 | 			distanceExecutor.shutdownNow(); | ||||||
| 			LogUtils.d(TAG, "距离计算任务已停止"); | 			LogUtils.d(TAG, "距离计算任务已停止"); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|      * 计算可见位置与GPS的距离(Haversine公式,后台线程执行) |  | ||||||
|  | 	 - 计算可见位置与GPS的距离(Haversine公式,后台线程执行) | ||||||
| 	 */ | 	 */ | ||||||
| 	private void calculateVisiblePositionDistance() { | 	private void calculateVisiblePositionDistance() { | ||||||
|         // 拷贝可见ID集合:避免遍历中修改引发 ConcurrentModificationException | 		Set tempVisibleIds = new HashSet(mVisiblePositionIds); | ||||||
|         Set<String> tempVisibleIds = new HashSet<String>(mVisiblePositionIds); | 		if (tempVisibleIds.isEmpty()) return;Iterator posIter = mPositionList.iterator(); | ||||||
|         if (tempVisibleIds.isEmpty()) return; |  | ||||||
|  |  | ||||||
|         // Java 7:迭代器遍历位置列表(安全删除/修改) |  | ||||||
|         Iterator<PositionModel> posIter = mPositionList.iterator(); |  | ||||||
| 		while (posIter.hasNext()) { | 		while (posIter.hasNext()) { | ||||||
|             PositionModel pos = posIter.next(); | 			PositionModel pos = (PositionModel)posIter.next(); | ||||||
|             String posId = pos.getPositionId(); | 			String posId = pos.getPositionId();if (tempVisibleIds.contains(posId) && pos.isEnableRealPositionDistance()) { | ||||||
|  |  | ||||||
|             // 仅计算“可见+启用距离”的位置 |  | ||||||
|             if (tempVisibleIds.contains(posId) && pos.isEnableRealPositionDistance()) { |  | ||||||
| 				try { | 				try { | ||||||
|                     // 调用Haversine公式计算距离(经纬度→米) |  | ||||||
| 					double distanceM = calculateHaversineDistance( | 					double distanceM = calculateHaversineDistance( | ||||||
| 						mCurrentGpsPosition.getLatitude(), mCurrentGpsPosition.getLongitude(), | 						mCurrentGpsPosition.getLatitude(), mCurrentGpsPosition.getLongitude(), | ||||||
| 						pos.getLatitude(), pos.getLongitude() | 						pos.getLatitude(), pos.getLongitude() | ||||||
| 					); | 					); | ||||||
|                     // 更新位置距离(服务内数据实时同步) |  | ||||||
| 					pos.setRealPositionDistance(distanceM); | 					pos.setRealPositionDistance(distanceM); | ||||||
| 					LogUtils.d(TAG, "计算完成:位置ID=" + posId + ",距离=" + String.format("%.1f", distanceM) + "米"); | 					LogUtils.d(TAG, "计算完成:位置ID=" + posId + ",距离=" + String.format("%.1f", distanceM) + "米"); | ||||||
| 					 | 					 | ||||||
|                     // 回调Adapter更新UI(确保主线程) |  | ||||||
|                     notifyDistanceUpdateToUI(posId); |  | ||||||
| 				} catch (Exception e) { | 				} catch (Exception e) { | ||||||
|                     // 计算异常时标记距离为-1(Adapter识别为“计算异常”) |  | ||||||
| 					pos.setRealPositionDistance(-1); | 					pos.setRealPositionDistance(-1); | ||||||
|                     notifyDistanceUpdateToUI(posId); | 					 | ||||||
| 					LogUtils.e(TAG, "计算失败(位置ID=" + posId + "):" + e.getMessage()); | 					LogUtils.e(TAG, "计算失败(位置ID=" + posId + "):" + e.getMessage()); | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| @@ -195,16 +508,15 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|      * 主线程回调Adapter更新UI(避免跨线程操作UI异常) |  | ||||||
|  | 	 - 主线程回调Adapter更新UI(避免跨线程操作UI异常) | ||||||
| 	 */ | 	 */ | ||||||
|     private void notifyDistanceUpdateToUI(final String positionId) { | 	/*private void notifyDistanceUpdateToUI(final String positionId) { | ||||||
| 	 if (Looper.myLooper() == Looper.getMainLooper()) { | 	 if (Looper.myLooper() == Looper.getMainLooper()) { | ||||||
|             // 已在主线程:直接回调 |  | ||||||
| 	 if (mDistanceReceiver != null) { | 	 if (mDistanceReceiver != null) { | ||||||
| 	 mDistanceReceiver.onDistanceUpdate(positionId); | 	 mDistanceReceiver.onDistanceUpdate(positionId); | ||||||
| 	 } | 	 } | ||||||
| 	 } else { | 	 } else { | ||||||
|             // 子线程:通过主线程Handler切换(Java 7 显式创建Handler) |  | ||||||
| 	 new android.os.Handler(Looper.getMainLooper()).post(new Runnable() { | 	 new android.os.Handler(Looper.getMainLooper()).post(new Runnable() { | ||||||
| 	 @Override | 	 @Override | ||||||
| 	 public void run() { | 	 public void run() { | ||||||
| @@ -214,44 +526,68 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 	 } | 	 } | ||||||
| 	 }); | 	 }); | ||||||
| 	 } | 	 } | ||||||
|     } | 	 }*/ | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|      * Haversine公式:计算两点间直线距离(经纬度→米,精度满足日常需求) |  | ||||||
|  | 	 - Haversine公式:计算两点间直线距离(经纬度→米) | ||||||
| 	 */ | 	 */ | ||||||
| 	private double calculateHaversineDistance(double gpsLat, double gpsLon, double posLat, double posLon) { | 	private double calculateHaversineDistance(double gpsLat, double gpsLon, double posLat, double posLon) { | ||||||
| 		final double EARTH_RADIUS = 6371000; // 地球半径(米) | 		final double EARTH_RADIUS = 6371000; // 地球半径(米) | ||||||
| 		double latDiff = Math.toRadians(posLat - gpsLat); | 		double latDiff = Math.toRadians(posLat - gpsLat); | ||||||
|         double lonDiff = Math.toRadians(posLon - gpsLon); | 		double lonDiff = Math.toRadians(posLon - gpsLon);double a = Math.sin(latDiff / 2) * Math.sin(latDiff / 2) | ||||||
|  | 			- Math.cos(Math.toRadians(gpsLat)) * Math.cos(Math.toRadians(posLat)) | ||||||
|  |  | ||||||
|         double a = Math.sin(latDiff / 2) * Math.sin(latDiff / 2) | 			- Math.sin(lonDiff / 2) * Math.sin(lonDiff / 2); | ||||||
| 			+ Math.cos(Math.toRadians(gpsLat)) * Math.cos(Math.toRadians(posLat)) |  | ||||||
| 			* Math.sin(lonDiff / 2) * Math.sin(lonDiff / 2); |  | ||||||
| 		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | 		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | ||||||
|         return EARTH_RADIUS * c; // 返回距离(米) | 		return EARTH_RADIUS * c; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	/** | ||||||
|  |  | ||||||
|  | 	 - 同步GPS状态到前台通知(显示实时经纬度+计算状态) | ||||||
|  | 	 */ | ||||||
|  | 	private void syncGpsStatusToNotification() { | ||||||
|  | 		if (!isForegroundServiceStarted || mCurrentGpsPosition == null) { | ||||||
|  | 			return; | ||||||
|  | 		}// 构造详细状态文本(包含经纬度+可见位置数量,用户感知更清晰) | ||||||
|  | 		final String gpsStatus = String.format( | ||||||
|  | 			"GPS位置:北纬%.4f° 东经%.4f° | 计算中(可见位置:%d个)", | ||||||
|  | 			mCurrentGpsPosition.getLatitude(), | ||||||
|  | 			mCurrentGpsPosition.getLongitude(), | ||||||
|  | 			mVisiblePositionIds.size() | ||||||
|  | 		);if (Looper.myLooper() == Looper.getMainLooper()) { | ||||||
|  | 			NotificationUtil.updateForegroundServiceStatus(this, gpsStatus); | ||||||
|  | 		} else { | ||||||
|  | 			new android.os.Handler(Looper.getMainLooper()).post(new Runnable() { | ||||||
|  | 					@Override | ||||||
|  | 					public void run() { | ||||||
|  | 						NotificationUtil.updateForegroundServiceStatus(DistanceRefreshService.this, gpsStatus); | ||||||
|  | 					} | ||||||
|  | 				}); | ||||||
|  | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| // ---------------------- 实现 PositionAdapter.DistanceServiceInterface 接口 ---------------------- | // ---------------------- 实现 PositionAdapter.DistanceServiceInterface 接口 ---------------------- | ||||||
|     @Override |  | ||||||
|     public ArrayList<PositionModel> getPositionList() { | 	public ArrayList getPositionList() { | ||||||
|         // 服务未运行返回空列表;运行中返回拷贝(避免外部修改原列表) |  | ||||||
| 		if (!isServiceRunning) { | 		if (!isServiceRunning) { | ||||||
| 			LogUtils.w(TAG, "getPositionList:服务未运行,返回空列表"); | 			LogUtils.w(TAG, "getPositionList:服务未运行,返回空列表"); | ||||||
|             return new ArrayList<PositionModel>(); | 			return new ArrayList(); | ||||||
| 		} | 		} | ||||||
|         return new ArrayList<PositionModel>(mPositionList); | 		return new ArrayList(mPositionList); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     @Override |  | ||||||
|     public ArrayList<PositionTaskModel> getPositionTasksList() { | 	public ArrayList getPositionTasksList() { | ||||||
| 		if (!isServiceRunning) { | 		if (!isServiceRunning) { | ||||||
| 			LogUtils.w(TAG, "getPositionTasksList:服务未运行,返回空列表"); | 			LogUtils.w(TAG, "getPositionTasksList:服务未运行,返回空列表"); | ||||||
|             return new ArrayList<PositionTaskModel>(); | 			return new ArrayList(); | ||||||
| 		} | 		} | ||||||
|         return new ArrayList<PositionTaskModel>(mTaskList); | 		return new ArrayList(mTaskList); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     @Override | 	 | ||||||
| 	public void syncCurrentGpsPosition(PositionModel position) { | 	public void syncCurrentGpsPosition(PositionModel position) { | ||||||
| 		if (position == null) { | 		if (position == null) { | ||||||
| 			LogUtils.w(TAG, "syncCurrentGpsPosition:GPS位置为空,同步失败"); | 			LogUtils.w(TAG, "syncCurrentGpsPosition:GPS位置为空,同步失败"); | ||||||
| @@ -259,15 +595,18 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 		} | 		} | ||||||
| 		this.mCurrentGpsPosition = position; | 		this.mCurrentGpsPosition = position; | ||||||
| 		LogUtils.d(TAG, "syncCurrentGpsPosition:同步成功(纬度=" + position.getLatitude() + ",经度=" + position.getLongitude() + ")"); | 		LogUtils.d(TAG, "syncCurrentGpsPosition:同步成功(纬度=" + position.getLatitude() + ",经度=" + position.getLongitude() + ")"); | ||||||
|  |  | ||||||
|  | // GPS位置同步后,立即更新通知(避免延迟) | ||||||
|  | 		if (isForegroundServiceStarted) { | ||||||
|  | 			syncGpsStatusToNotification(); | ||||||
|  | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     @Override | 	/*public void setOnDistanceUpdateReceiver(PositionAdapter.OnDistanceUpdateReceiver receiver) { | ||||||
|     public void setOnDistanceUpdateReceiver(PositionAdapter.OnDistanceUpdateReceiver receiver) { |  | ||||||
| 		this.mDistanceReceiver = receiver; | 		this.mDistanceReceiver = receiver; | ||||||
| 		LogUtils.d(TAG, "setOnDistanceUpdateReceiver:回调接收器已设置(" + (receiver != null ? "有效" : "无效") + ")"); | 		LogUtils.d(TAG, "setOnDistanceUpdateReceiver:回调接收器已设置(" + (receiver != null ? "有效" : "无效") + ")"); | ||||||
|     } | 	}*/ | ||||||
|  |  | ||||||
|     @Override |  | ||||||
| 	public void addVisibleDistanceView(String positionId) { | 	public void addVisibleDistanceView(String positionId) { | ||||||
| 		if (!isServiceRunning || positionId == null) { | 		if (!isServiceRunning || positionId == null) { | ||||||
| 			LogUtils.w(TAG, "addVisibleDistanceView:服务未运行/位置ID无效,添加失败"); | 			LogUtils.w(TAG, "addVisibleDistanceView:服务未运行/位置ID无效,添加失败"); | ||||||
| @@ -275,54 +614,64 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 		} | 		} | ||||||
| 		if (mVisiblePositionIds.add(positionId)) { | 		if (mVisiblePositionIds.add(positionId)) { | ||||||
| 			LogUtils.d(TAG, "addVisibleDistanceView:添加成功(位置ID=" + positionId + ",当前可见数=" + mVisiblePositionIds.size() + ")"); | 			LogUtils.d(TAG, "addVisibleDistanceView:添加成功(位置ID=" + positionId + ",当前可见数=" + mVisiblePositionIds.size() + ")"); | ||||||
|  | // 新增:添加可见位置后,立即更新通知(显示最新可见数量) | ||||||
|  | 			if (isForegroundServiceStarted && mCurrentGpsPosition != null) { | ||||||
|  | 				syncGpsStatusToNotification(); | ||||||
|  | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     @Override |  | ||||||
| 	public void removeVisibleDistanceView(String positionId) { | 	public void removeVisibleDistanceView(String positionId) { | ||||||
| 		if (positionId == null) { | 		if (positionId == null) { | ||||||
| 			LogUtils.w(TAG, "removeVisibleDistanceView:位置ID为空,移除失败"); | 			LogUtils.w(TAG, "removeVisibleDistanceView:位置ID为空,移除失败"); | ||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
| 		if (mVisiblePositionIds.remove(positionId)) { | 		if (mVisiblePositionIds.remove(positionId)) { | ||||||
|             LogUtils.d(TAG, "removeVisibleDistanceView:移除成功(位置ID=" + positionId + ",当前可见数=" + mVisiblePositionIds.size() + ")"); | 			int remainingCount = mVisiblePositionIds.size(); | ||||||
|  | 			LogUtils.d(TAG, "removeVisibleDistanceView:移除成功(位置ID=" + positionId + ",当前可见数=" + remainingCount + ")"); | ||||||
|  | // 新增:移除可见位置后,更新通知(同步数量变化) | ||||||
|  | 			if (isForegroundServiceStarted && mCurrentGpsPosition != null) { | ||||||
|  | 				syncGpsStatusToNotification(); | ||||||
|  | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     @Override |  | ||||||
| 	public void clearVisibleDistanceViews() { | 	public void clearVisibleDistanceViews() { | ||||||
| 		mVisiblePositionIds.clear(); | 		mVisiblePositionIds.clear(); | ||||||
| 		LogUtils.d(TAG, "clearVisibleDistanceViews:所有可见位置已清空"); | 		LogUtils.d(TAG, "clearVisibleDistanceViews:所有可见位置已清空"); | ||||||
|  | // 新增:清空可见位置后,更新通知(提示计算暂停) | ||||||
|  | 		if (isForegroundServiceStarted) { | ||||||
|  | 			updateNotificationGpsStatus("无可见位置,距离计算暂停"); | ||||||
|  | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     // ---------------------- 数据管理接口(给外部/Adapter调用,安全校验) ---------------------- | // ---------------------- 数据管理接口(修复原有语法错误+优化逻辑) ---------------------- | ||||||
| 	/** | 	/** | ||||||
|      * 获取服务运行状态(供Activity/Adapter判断是否加载数据) |  | ||||||
|  | 	 - 获取服务运行状态 | ||||||
| 	 */ | 	 */ | ||||||
| 	public boolean isServiceRunning() { | 	public boolean isServiceRunning() { | ||||||
| 		return isServiceRunning; | 		return isServiceRunning; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|      * 添加位置(Adapter新增位置时调用,自动去重) |  | ||||||
|  | 	 - 添加位置(修复迭代器泛型缺失问题) | ||||||
| 	 */ | 	 */ | ||||||
| 	public void addPosition(PositionModel position) { | 	public void addPosition(PositionModel position) { | ||||||
| 		if (!isServiceRunning || position == null || position.getPositionId() == null) { | 		if (!isServiceRunning || position == null || position.getPositionId() == null) { | ||||||
| 			LogUtils.w(TAG, "addPosition:服务未运行/数据无效,添加失败"); | 			LogUtils.w(TAG, "addPosition:服务未运行/数据无效,添加失败"); | ||||||
| 			return; | 			return; | ||||||
|         } | 		}// 修复:显式声明PositionModel泛型,避免类型转换警告 | ||||||
|  |  | ||||||
|         // 去重校验(根据位置ID) |  | ||||||
| 		boolean isDuplicate = false; | 		boolean isDuplicate = false; | ||||||
|         Iterator<PositionModel> posIter = mPositionList.iterator(); | 		Iterator posIter = mPositionList.iterator(); | ||||||
| 		while (posIter.hasNext()) { | 		while (posIter.hasNext()) { | ||||||
|             if (position.getPositionId().equals(posIter.next().getPositionId())) { | 			PositionModel existingPos = (PositionModel)posIter.next(); | ||||||
|  | 			if (position.getPositionId().equals(existingPos.getPositionId())) { | ||||||
| 				isDuplicate = true; | 				isDuplicate = true; | ||||||
| 				break; | 				break; | ||||||
| 			} | 			} | ||||||
|         } | 		}if (!isDuplicate) { | ||||||
|  |  | ||||||
|         if (!isDuplicate) { |  | ||||||
| 			mPositionList.add(position); | 			mPositionList.add(position); | ||||||
| 			LogUtils.d(TAG, "addPosition:添加成功(位置ID=" + position.getPositionId() + ",总数=" + mPositionList.size() + ")"); | 			LogUtils.d(TAG, "addPosition:添加成功(位置ID=" + position.getPositionId() + ",总数=" + mPositionList.size() + ")"); | ||||||
| 		} else { | 		} else { | ||||||
| @@ -331,70 +680,62 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|      * 删除位置(连带删除关联任务,Adapter删除时调用) |  | ||||||
|  | 	 - 删除位置(修复任务删除时的类型转换错误) | ||||||
| 	 */ | 	 */ | ||||||
| 	public void removePosition(String positionId) { | 	public void removePosition(String positionId) { | ||||||
| 		if (!isServiceRunning || positionId == null) { | 		if (!isServiceRunning || positionId == null) { | ||||||
| 			LogUtils.w(TAG, "removePosition:服务未运行/位置ID无效,删除失败"); | 			LogUtils.w(TAG, "removePosition:服务未运行/位置ID无效,删除失败"); | ||||||
| 			return; | 			return; | ||||||
|         } | 		}// 1. 删除位置 | ||||||
|  |  | ||||||
|         // 1. 删除位置 |  | ||||||
| 		boolean isRemoved = false; | 		boolean isRemoved = false; | ||||||
|         Iterator<PositionModel> posIter = mPositionList.iterator(); | 		Iterator posIter = mPositionList.iterator(); | ||||||
| 		while (posIter.hasNext()) { | 		while (posIter.hasNext()) { | ||||||
|             PositionModel pos = posIter.next(); | 			PositionModel pos = (PositionModel)posIter.next(); | ||||||
| 			if (positionId.equals(pos.getPositionId())) { | 			if (positionId.equals(pos.getPositionId())) { | ||||||
| 				posIter.remove(); | 				posIter.remove(); | ||||||
| 				isRemoved = true; | 				isRemoved = true; | ||||||
| 				break; | 				break; | ||||||
| 			} | 			} | ||||||
|         } | 		}if (isRemoved) { | ||||||
|  | // 修复:任务列表迭代时用PositionTaskModel泛型(原错误用PositionModel导致转换失败) | ||||||
|         if (isRemoved) { | 			Iterator taskIter = mTaskList.iterator(); | ||||||
|             // 2. 删除关联任务 |  | ||||||
|             Iterator<PositionTaskModel> taskIter = mTaskList.iterator(); |  | ||||||
| 			while (taskIter.hasNext()) { | 			while (taskIter.hasNext()) { | ||||||
|                 if (positionId.equals(taskIter.next().getPositionId())) { | 				PositionTaskModel task = (PositionTaskModel)taskIter.next(); | ||||||
|  | 				if (positionId.equals(task.getPositionId())) { | ||||||
| 					taskIter.remove(); | 					taskIter.remove(); | ||||||
| 				} | 				} | ||||||
|             } | 			}// 3. 移除可见位置 | ||||||
|             // 3. 移除可见位置(避免继续计算已删除位置) |  | ||||||
| 			mVisiblePositionIds.remove(positionId); | 			mVisiblePositionIds.remove(positionId); | ||||||
|             LogUtils.d(TAG, "removePosition:删除成功(位置ID=" + positionId + ",剩余位置数=" + mPositionList.size() + ")"); | 			LogUtils.d(TAG, "removePosition:删除成功(位置ID=" + positionId + ",剩余位置数=" + mPositionList.size() + ",剩余任务数=" + mTaskList.size() + ")"); | ||||||
| 		} else { | 		} else { | ||||||
| 			LogUtils.w(TAG, "removePosition:位置ID=" + positionId + "不存在,删除失败"); | 			LogUtils.w(TAG, "removePosition:位置ID=" + positionId + "不存在,删除失败"); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|      * 更新位置信息(Adapter编辑后调用,仅更新备注/距离开关) |  | ||||||
|  | 	 - 更新位置信息(修复代码格式+迭代器泛型) | ||||||
| 	 */ | 	 */ | ||||||
| 	public void updatePosition(PositionModel updatedPosition) { | 	public void updatePosition(PositionModel updatedPosition) { | ||||||
| 		if (!isServiceRunning || updatedPosition == null || updatedPosition.getPositionId() == null) { | 		if (!isServiceRunning || updatedPosition == null || updatedPosition.getPositionId() == null) { | ||||||
| 			LogUtils.w(TAG, "updatePosition:服务未运行/数据无效,更新失败"); | 			LogUtils.w(TAG, "updatePosition:服务未运行/数据无效,更新失败"); | ||||||
| 			return; | 			return; | ||||||
|         } | 		}boolean isUpdated = false; | ||||||
|  | 		Iterator posIter = mPositionList.iterator(); | ||||||
|         boolean isUpdated = false; |  | ||||||
|         Iterator<PositionModel> posIter = mPositionList.iterator(); |  | ||||||
| 		while (posIter.hasNext()) { | 		while (posIter.hasNext()) { | ||||||
|             PositionModel pos = posIter.next(); | 			PositionModel pos = (PositionModel)posIter.next(); | ||||||
| 			if (updatedPosition.getPositionId().equals(pos.getPositionId())) { | 			if (updatedPosition.getPositionId().equals(pos.getPositionId())) { | ||||||
|                 // 仅更新允许修改的字段(备注+距离开关) |  | ||||||
| 				pos.setMemo(updatedPosition.getMemo()); | 				pos.setMemo(updatedPosition.getMemo()); | ||||||
| 				pos.setIsEnableRealPositionDistance(updatedPosition.isEnableRealPositionDistance()); | 				pos.setIsEnableRealPositionDistance(updatedPosition.isEnableRealPositionDistance()); | ||||||
|                 // 关闭距离时重置距离值 |  | ||||||
| 				if (!updatedPosition.isEnableRealPositionDistance()) { | 				if (!updatedPosition.isEnableRealPositionDistance()) { | ||||||
| 					pos.setRealPositionDistance(-1); | 					pos.setRealPositionDistance(-1); | ||||||
|                     notifyDistanceUpdateToUI(pos.getPositionId()); // 通知UI更新状态 | 					//notifyDistanceUpdateToUI(pos.getPositionId()); | ||||||
| 				} | 				} | ||||||
| 				isUpdated = true; | 				isUpdated = true; | ||||||
| 				break; | 				break; | ||||||
| 			} | 			} | ||||||
|         } | 		}if (isUpdated) { | ||||||
|  |  | ||||||
|         if (isUpdated) { |  | ||||||
| 			LogUtils.d(TAG, "updatePosition:更新成功(位置ID=" + updatedPosition.getPositionId() + ")"); | 			LogUtils.d(TAG, "updatePosition:更新成功(位置ID=" + updatedPosition.getPositionId() + ")"); | ||||||
| 		} else { | 		} else { | ||||||
| 			LogUtils.w(TAG, "updatePosition:位置ID=" + updatedPosition.getPositionId() + "不存在,更新失败"); | 			LogUtils.w(TAG, "updatePosition:位置ID=" + updatedPosition.getPositionId() + "不存在,更新失败"); | ||||||
| @@ -402,17 +743,16 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
|      * 同步任务列表(Adapter编辑任务后调用,全量覆盖+去重) |  | ||||||
|  | 	 - 同步任务列表(修复泛型缺失+代码格式) | ||||||
| 	 */ | 	 */ | ||||||
|     public void syncAllPositionTasks(ArrayList<PositionTaskModel> tasks) { | 	public void syncAllPositionTasks(ArrayList tasks) { | ||||||
| 		if (!isServiceRunning || tasks == null) { | 		if (!isServiceRunning || tasks == null) { | ||||||
| 			LogUtils.w(TAG, "syncAllPositionTasks:服务未运行/任务列表为空,同步失败"); | 			LogUtils.w(TAG, "syncAllPositionTasks:服务未运行/任务列表为空,同步失败"); | ||||||
| 			return; | 			return; | ||||||
| 		} | 		}// 1. 清空旧任务 | ||||||
|  |  | ||||||
| // 1. 清空旧任务(全量同步,避免增量逻辑复杂) |  | ||||||
| 		mTaskList.clear(); | 		mTaskList.clear(); | ||||||
| // 2. 添加新任务(根据任务ID去重,避免重复) | // 2. 添加新任务(修复泛型+去重逻辑) | ||||||
| 		Set taskIdSet = new HashSet(); | 		Set taskIdSet = new HashSet(); | ||||||
| 		Iterator taskIter = tasks.iterator(); | 		Iterator taskIter = tasks.iterator(); | ||||||
| 		while (taskIter.hasNext()) { | 		while (taskIter.hasNext()) { | ||||||
| @@ -421,13 +761,12 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 				taskIdSet.add(task.getTaskId()); | 				taskIdSet.add(task.getTaskId()); | ||||||
| 				mTaskList.add(task); | 				mTaskList.add(task); | ||||||
| 			} | 			} | ||||||
| 		} | 		}LogUtils.d(TAG, "syncAllPositionTasks:同步成功(接收任务数=" + tasks.size() + ",去重后=" + mTaskList.size() + ")"); | ||||||
|  |  | ||||||
| 		LogUtils.d(TAG, "syncAllPositionTasks:同步成功(接收任务数=" + tasks.size() + ",去重后=" + mTaskList.size() + ")"); |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
| 	 * 清空所有数据(服务销毁/调试时调用,重置所有状态) |  | ||||||
|  | 	 - 清空所有数据 | ||||||
| 	 */ | 	 */ | ||||||
| 	public void clearAllData() { | 	public void clearAllData() { | ||||||
| 		mPositionList.clear(); | 		mPositionList.clear(); | ||||||
| @@ -438,7 +777,8 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	/** | 	/** | ||||||
| 	 * 强制刷新距离(外部主动触发,如GPS位置突变时) |  | ||||||
|  | 	 - 强制刷新距离(优化:刷新后同步通知状态) | ||||||
| 	 */ | 	 */ | ||||||
| 	public void forceRefreshDistance() { | 	public void forceRefreshDistance() { | ||||||
| 		if (!isServiceRunning) { | 		if (!isServiceRunning) { | ||||||
| @@ -450,11 +790,50 @@ public class DistanceRefreshService extends Service implements PositionAdapter.D | |||||||
| 			distanceExecutor.submit(new Runnable() { | 			distanceExecutor.submit(new Runnable() { | ||||||
| 					@Override | 					@Override | ||||||
| 					public void run() { | 					public void run() { | ||||||
|  | // 强制刷新前先检查GPS状态,避免无效计算 | ||||||
|  | 						if (isGpsPermissionGranted && isGpsEnabled && mCurrentGpsPosition != null) { | ||||||
| 							calculateVisiblePositionDistance(); | 							calculateVisiblePositionDistance(); | ||||||
|  | 							syncGpsStatusToNotification(); // 刷新后同步通知 | ||||||
|  | 							LogUtils.d(TAG, "forceRefreshDistance:即时距离计算完成,通知已更新"); | ||||||
|  | 						} else { | ||||||
|  | 							String reason = !isGpsPermissionGranted ? "缺少定位权限" : | ||||||
|  | 								(!isGpsEnabled ? "GPS未开启" : "未获取到GPS位置"); | ||||||
|  | 							LogUtils.w(TAG, "forceRefreshDistance:刷新失败,原因:" + reason); | ||||||
|  | 							updateNotificationGpsStatus("强制刷新失败:" + reason); | ||||||
|  | 						} | ||||||
| 					} | 					} | ||||||
| 				}); | 				}); | ||||||
| 			LogUtils.d(TAG, "forceRefreshDistance:已触发即时距离计算"); | 			LogUtils.d(TAG, "forceRefreshDistance:已触发即时距离计算请求"); | ||||||
| 		} | 		} else { | ||||||
|  | 			LogUtils.e(TAG, "forceRefreshDistance:线程池已关闭,无法触发刷新"); | ||||||
|  | 			updateNotificationGpsStatus("线程池已关闭,无法执行强制刷新"); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | // ---------------------- 补充:修复LocationProvider引用缺失问题(避免编译错误) ---------------------- | ||||||
|  | // 注:原代码中onStatusChanged使用LocationProvider枚举,需补充静态导入或显式声明 | ||||||
|  | // 此处通过内部静态类定义,解决系统API引用问题(兼容Java 7语法) | ||||||
|  | 	private static class LocationProvider { | ||||||
|  | 		public static final int AVAILABLE = 2; | ||||||
|  | 		public static final int OUT_OF_SERVICE = 0; | ||||||
|  | 		public static final int TEMPORARILY_UNAVAILABLE = 1; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | // ---------------------- 补充:Context引用工具(避免服务销毁后Context失效) ---------------------- | ||||||
|  | 	/*private Context getSafeContext() { | ||||||
|  | 	 // 服务未销毁时返回自身Context,已销毁时返回应用Context(避免内存泄漏) | ||||||
|  | 	 if (isDestroyed()) { | ||||||
|  | 	 return getApplicationContext(); | ||||||
|  | 	 } | ||||||
|  | 	 return this; | ||||||
|  | 	 }*/ | ||||||
|  |  | ||||||
|  | // 注:isDestroyed()为API 17+方法,若需兼容更低版本,可添加版本判断 | ||||||
|  | 	/*private boolean isDestroyed() { | ||||||
|  | 	 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { | ||||||
|  | 	 return super.isDestroyed(); | ||||||
|  | 	 } | ||||||
|  | 	 // 低版本通过状态标记间接判断(服务销毁时会置为false) | ||||||
|  | 	 return !isServiceRunning && !isForegroundServiceStarted; | ||||||
|  | 	 }*/ | ||||||
|  | } | ||||||
|   | |||||||
| @@ -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:layout_height="match_parent" | ||||||
| 	android:orientation="vertical"> | 	android:orientation="vertical"> | ||||||
|  |  | ||||||
| 	<!-- 顶部 Toolbar --> |  | ||||||
| 	<androidx.appcompat.widget.Toolbar | 	<androidx.appcompat.widget.Toolbar | ||||||
| 		android:id="@+id/toolbar" | 		android:id="@+id/toolbar" | ||||||
| 		android:layout_width="match_parent" | 		android:layout_width="match_parent" | ||||||
| @@ -14,15 +13,13 @@ | |||||||
| 		android:background="?attr/colorPrimary" | 		android:background="?attr/colorPrimary" | ||||||
| 		android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/> | 		android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/> | ||||||
|  |  | ||||||
| 	<!-- 服务控制开关 --> | 	<Switch | ||||||
| 	<androidx.appcompat.widget.SwitchCompat |  | ||||||
| 		android:id="@+id/switch_service_control" | 		android:id="@+id/switch_service_control" | ||||||
| 		android:layout_width="wrap_content" |  | ||||||
| 		android:layout_height="wrap_content" |  | ||||||
| 		android:layout_margin="16dp" | 		android:layout_margin="16dp" | ||||||
| 		android:text="位置服务"/> | 		android:text="主要服务开关" | ||||||
|  | 		android:layout_width="match_parent" | ||||||
|  | 		android:layout_height="wrap_content"/> | ||||||
|  |  | ||||||
| 	<!-- 跳转按钮:位置管理页 --> |  | ||||||
| 	<Button | 	<Button | ||||||
| 		android:layout_width="match_parent" | 		android:layout_width="match_parent" | ||||||
| 		android:layout_height="wrap_content" | 		android:layout_height="wrap_content" | ||||||
| @@ -30,7 +27,6 @@ | |||||||
| 		android:onClick="onPositions" | 		android:onClick="onPositions" | ||||||
| 		android:text="进入位置管理"/> | 		android:text="进入位置管理"/> | ||||||
|  |  | ||||||
| 	<!-- 跳转按钮:日志页 --> |  | ||||||
| 	<Button | 	<Button | ||||||
| 		android:layout_width="match_parent" | 		android:layout_width="match_parent" | ||||||
| 		android:layout_height="wrap_content" | 		android:layout_height="wrap_content" | ||||||
| @@ -38,6 +34,5 @@ | |||||||
| 		android:onClick="onLog" | 		android:onClick="onLog" | ||||||
| 		android:text="查看操作日志"/> | 		android:text="查看操作日志"/> | ||||||
|  |  | ||||||
|  |  | ||||||
| </LinearLayout> | </LinearLayout> | ||||||
|  |  | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user
	 ZhanGSKen
					ZhanGSKen