feat: 添加后台定时自动扫描和相册最近扫描时间显示功能
## 新增功能 ### 1. 后台定时自动扫描 - 添加 ScanTaskManager 工具类,使用线程池管理扫描任务 - 添加 CacheScanReceiver 广播接收器处理定时扫描 - 在设置页面添加自动扫描间隔配置(禁用、1小时、6小时、12小时、24小时) - 使用 AlarmManager 定时触发扫描任务 - 扫描完成后自动更新相册的 lastScanTime ### 2. 相册最近扫描时间显示 - 在 Album 模型中添加 lastScanTime 字段 - 在相册卡片上显示格式化的扫描时间(刚刚、X分钟前、X小时前、X天前、具体日期) - 在相册管理页面、相册编辑页面和壁纸服务中更新扫描时间 ### 3. 性能优化 - 使用 ScanTaskManager 替代直接创建 Thread - 避免在 onBindViewHolder 中创建大量线程 - 使用固定大小的线程池(最多3个并发任务) - 在 Activity/Fragment 销毁时自动取消所有扫描任务 - 优先使用缓存,减少不必要的扫描 ## 技术实现 ### 核心类 - ScanTaskManager: 单例模式的扫描任务管理器,使用 ExecutorService 管理线程池 - CacheScanReceiver: 处理定时扫描任务的广播接收器 - AlarmScheduler: 新增 scheduleCacheScan() 和 cancelCacheScan() 方法 - MediaScanner: 新增 clearCache()、clearAllCache()、rescanFolder() 方法 - JsonHelper: 新增 clearIndex() 和 clearAllIndexes() 方法 ### UI 更新 - fragment_settings.xml: 添加自动扫描配置卡片 - item_album_card.xml: 添加最近扫描时间显示 - SettingsFragment: 添加自动扫描配置逻辑 - AlbumManagementFragment: 使用 ScanTaskManager 替代 Thread - AlbumEditorActivity: 使用 ScanTaskManager 替代 Thread ### 数据模型 - Album: 添加 lastScanTime 字段 - AppConfig: 添加 autoScanIntervalHours 字段 - WallpaperPreferences: 添加自动扫描间隔的持久化逻辑 ## 文档更新 - 更新 CLAUDE.md,添加后台定时自动扫描和性能优化的说明 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
86c46f3f04
commit
e77da929bc
16 files changed
+1134
-52
No files matched your search
@@ -13,8 +13,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
- 返回桌面时更换壁纸
|
- 返回桌面时更换壁纸
|
||||||
- 双击桌面切换壁纸
|
- 双击桌面切换壁纸
|
||||||
- 视频壁纸支持(播放完成后自动切换)
|
- 视频壁纸支持(播放完成后自动切换)
|
||||||
|
- 固定壁纸收藏功能(四指点击通知打开)
|
||||||
- 壁纸历史记录
|
- 壁纸历史记录
|
||||||
- 顺序/随机播放模式
|
- 顺序/随机播放模式
|
||||||
|
- 后台定时自动扫描相册文件夹
|
||||||
|
- 相册最近扫描时间显示
|
||||||
|
|
||||||
## 构建和运行
|
## 构建和运行
|
||||||
|
|
||||||
@@ -85,6 +88,7 @@ cn.hugh.bz.gk2/
|
|||||||
├── utils/ # 工具类
|
├── utils/ # 工具类
|
||||||
│ ├── AlarmScheduler.java # 定时任务调度
|
│ ├── AlarmScheduler.java # 定时任务调度
|
||||||
│ ├── MediaScanner.java # 媒体扫描器
|
│ ├── MediaScanner.java # 媒体扫描器
|
||||||
|
│ ├── ScanTaskManager.java # 扫描任务管理器(线程池)
|
||||||
│ ├── ThumbnailHelper.java # 缩略图工具
|
│ ├── ThumbnailHelper.java # 缩略图工具
|
||||||
│ ├── WallpaperServiceHelper.java # 服务状态检测
|
│ ├── WallpaperServiceHelper.java # 服务状态检测
|
||||||
│ ├── BackgroundHelper.java # 背景图片辅助
|
│ ├── BackgroundHelper.java # 背景图片辅助
|
||||||
@@ -92,7 +96,8 @@ cn.hugh.bz.gk2/
|
|||||||
│ ├── JsonHelper.java
|
│ ├── JsonHelper.java
|
||||||
│ └── WallpaperGlideModule.java
|
│ └── WallpaperGlideModule.java
|
||||||
├── receiver/ # 广播接收器
|
├── receiver/ # 广播接收器
|
||||||
│ └── WallpaperChangeReceiver.java # 壁纸更换接收器
|
│ ├── WallpaperChangeReceiver.java # 壁纸更换接收器
|
||||||
|
│ └── CacheScanReceiver.java # 缓存扫描接收器
|
||||||
└── bridge/ # 桥接层(预留)
|
└── bridge/ # 桥接层(预留)
|
||||||
└── modules/
|
└── modules/
|
||||||
```
|
```
|
||||||
@@ -115,6 +120,7 @@ cn.hugh.bz.gk2/
|
|||||||
3. **返回桌面更换**(`changeOnReturn`):壁纸可见时自动更换
|
3. **返回桌面更换**(`changeOnReturn`):壁纸可见时自动更换
|
||||||
4. **双击切换**:在桌面双击触发快速切换(可在设置中开关)
|
4. **双击切换**:在桌面双击触发快速切换(可在设置中开关)
|
||||||
5. **视频播放完成**(`videoCompleted`):视频壁纸播放完成后自动切换到下一个媒体
|
5. **视频播放完成**(`videoCompleted`):视频壁纸播放完成后自动切换到下一个媒体
|
||||||
|
6. **四指点击**:四指或更多手指点击桌面,显示通知打开固定壁纸并禁用 app
|
||||||
|
|
||||||
**关键状态标志**:
|
**关键状态标志**:
|
||||||
- `forceChangeNext`:用户强制更换标志
|
- `forceChangeNext`:用户强制更换标志
|
||||||
@@ -132,6 +138,7 @@ cn.hugh.bz.gk2/
|
|||||||
- 每个相册有独立的文件夹列表、播放模式、更换间隔等配置
|
- 每个相册有独立的文件夹列表、播放模式、更换间隔等配置
|
||||||
- 支持默认相册(ID 为 "default",不可删除)
|
- 支持默认相册(ID 为 "default",不可删除)
|
||||||
- 通过 `AlbumPreferences` 持久化到 SharedPreferences(JSON 格式)
|
- 通过 `AlbumPreferences` 持久化到 SharedPreferences(JSON 格式)
|
||||||
|
- 记录最近扫描时间(`lastScanTime`),用于显示数据新鲜度
|
||||||
|
|
||||||
**激活机制**:
|
**激活机制**:
|
||||||
- 同一时间只有一个相册处于激活状态
|
- 同一时间只有一个相册处于激活状态
|
||||||
@@ -198,7 +205,100 @@ onCompletion() 回调 → 触发 AutoWallpaperService 切换下一个壁纸
|
|||||||
- Fragment 通过 `MainActivity` 的回调接口启动文件夹/图片选择器
|
- Fragment 通过 `MainActivity` 的回调接口启动文件夹/图片选择器
|
||||||
- 使用 `switchToPage(int)` 方法在 Fragment 间导航
|
- 使用 `switchToPage(int)` 方法在 Fragment 间导航
|
||||||
|
|
||||||
#### 7. 权限管理
|
#### 7. 固定壁纸系统(Fixed Wallpaper)
|
||||||
|
|
||||||
|
**固定壁纸功能**:
|
||||||
|
- **收藏功能**:保存用户喜欢的壁纸 URL,不影响 app 自动更新
|
||||||
|
- **四指点击**:在桌面上四指或更多手指点击,发送通知打开固定壁纸
|
||||||
|
- **通知机制**:使用通知绕过 Android 后台服务启动 Activity 的系统限制
|
||||||
|
- **状态管理**:app 启用/禁用使用独立的 `isEnabled` 标志控制
|
||||||
|
|
||||||
|
**数据模型**:
|
||||||
|
- `fixedWallpaperUri`:固定壁纸的 URI 字符串(AppConfig)
|
||||||
|
- `isFixedWallpaperEnabled`:固定壁纸模式启用标志(暂时保留,未来扩展用)
|
||||||
|
- `isEnabled`:app 启用/禁用状态,与固定壁纸无关
|
||||||
|
|
||||||
|
**使用流程**:
|
||||||
|
```
|
||||||
|
用户在设置页面选择固定壁纸
|
||||||
|
↓
|
||||||
|
固定壁纸只保存 URI,app 继续正常自动更新
|
||||||
|
↓
|
||||||
|
用户四指点击桌面
|
||||||
|
↓
|
||||||
|
检查 app 是否启用 + 是否有固定壁纸
|
||||||
|
↓
|
||||||
|
创建通知渠道(Android 8.0+)
|
||||||
|
↓
|
||||||
|
显示通知:"打开固定壁纸"(优先级:IMPORTANCE_HIGH)
|
||||||
|
↓
|
||||||
|
设置 app 为禁用(config.setEnabled(false))
|
||||||
|
↓
|
||||||
|
用户点击通知
|
||||||
|
↓
|
||||||
|
在系统相册中打开固定壁纸
|
||||||
|
↓
|
||||||
|
用户在相册中将图片设置为壁纸
|
||||||
|
```
|
||||||
|
|
||||||
|
**四指点击检测**(`AutoWallpaperService.java:962-1009`):
|
||||||
|
```java
|
||||||
|
if (pointerCount >= 4 && action == ACTION_POINTER_DOWN) {
|
||||||
|
// 检查 app 状态和固定壁纸
|
||||||
|
// 创建并发送通知
|
||||||
|
// 设置 app 为禁用
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**通知创建**:
|
||||||
|
- 通知渠道 ID:`fixed_wallpaper_channel`
|
||||||
|
- 通知权限:`POST_NOTIFICATIONS`
|
||||||
|
- 通知优先级:`IMPORTANCE_HIGH`
|
||||||
|
- PendingIntents 标志:`FLAG_UPDATE_CURRENT | FLAG_IMMUTABLE`
|
||||||
|
|
||||||
|
**技术要点**:
|
||||||
|
- 使用 `NotificationCompat` 兼容 Android 各版本
|
||||||
|
- 使用 `FLAG_ACTIVITY_NEW_TASK` 确保 Activity 能从通知启动
|
||||||
|
- 使用 `FLAG_GRANT_READ_URI_PERMISSION` 授予 URI 读取权限
|
||||||
|
- 自动取消通知:`setAutoCancel(true)`
|
||||||
|
|
||||||
|
#### 8. 后台定时自动扫描(Auto Scan)
|
||||||
|
|
||||||
|
**扫描任务管理器**(`ScanTaskManager`):
|
||||||
|
- **单例模式**:全局共享的扫描任务管理器
|
||||||
|
- **线程池管理**:使用固定大小的线程池(最多 3 个并发任务)
|
||||||
|
- **任务缓存**:跟踪正在执行的任务,支持取消
|
||||||
|
- **避免重复扫描**:优先使用 `MediaScanner` 的缓存机制
|
||||||
|
|
||||||
|
**性能优化**:
|
||||||
|
- 避免在 `onBindViewHolder` 中直接创建 Thread
|
||||||
|
- 使用线程池复用线程,减少线程创建开销
|
||||||
|
- 限制并发扫描任务数量,避免资源竞争
|
||||||
|
- 在 Activity/Fragment 销毁时取消所有任务
|
||||||
|
|
||||||
|
**自动扫描功能**:
|
||||||
|
- **配置选项**:禁用、1小时、6小时、12小时、24小时(推荐)
|
||||||
|
- **后台执行**:使用 `AlarmManager` 定时触发 `CacheScanReceiver`
|
||||||
|
- **省电优化**:使用 `setAndAllowWhileIdle()` 而非精确闹钟
|
||||||
|
- **扫描逻辑**:
|
||||||
|
- 遍历所有相册的文件夹
|
||||||
|
- 清除缓存并重新扫描
|
||||||
|
- 更新相册的 `lastScanTime`
|
||||||
|
- 记录详细日志
|
||||||
|
|
||||||
|
**最近扫描时间显示**:
|
||||||
|
- **时间格式**:
|
||||||
|
- 刚刚(< 1分钟)
|
||||||
|
- X 分钟前(< 1小时)
|
||||||
|
- X 小时前(< 1天)
|
||||||
|
- X 天前(< 7天)
|
||||||
|
- MM-dd HH:mm(≥ 7天)
|
||||||
|
- **更新时机**:
|
||||||
|
- 自动扫描完成后
|
||||||
|
- 相册管理页面加载相册信息时
|
||||||
|
- 壁纸服务扫描文件夹时
|
||||||
|
|
||||||
|
#### 9. 权限管理
|
||||||
|
|
||||||
**必需权限**:
|
**必需权限**:
|
||||||
- `READ_EXTERNAL_STORAGE`(Android 12 及以下)
|
- `READ_EXTERNAL_STORAGE`(Android 12 及以下)
|
||||||
@@ -417,6 +517,93 @@ adb shell tail -f /sdcard/Android/data/cn.hugh.bz.gk2/files/wallpaper_log.txt
|
|||||||
- 在 `SettingsFragment` 中添加开关控件
|
- 在 `SettingsFragment` 中添加开关控件
|
||||||
- 在 `WallpaperPreferences` 中添加持久化逻辑
|
- 在 `WallpaperPreferences` 中添加持久化逻辑
|
||||||
|
|
||||||
|
### 添加固定壁纸收藏功能
|
||||||
|
|
||||||
|
**固定壁纸功能**:保存用户喜欢的壁纸 URL,支持通过四指点击快速访问
|
||||||
|
|
||||||
|
1. **在 `AppConfig` 中添加字段**:
|
||||||
|
```java
|
||||||
|
private String fixedWallpaperUri; // 固定壁纸 URI
|
||||||
|
private boolean isFixedWallpaperEnabled; // 固定壁纸模式启用标志
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **在 `WallpaperPreferences` 中添加持久化**:
|
||||||
|
```java
|
||||||
|
// 定义常量
|
||||||
|
private static final String KEY_FIXED_WALLPAPER_URI = "fixed_wallpaper_uri";
|
||||||
|
private static final String KEY_FIXED_WALLPAPER_ENABLED = "fixed_wallpaper_enabled";
|
||||||
|
|
||||||
|
// 在 loadConfig() 中加载
|
||||||
|
config.setFixedWallpaperUri(prefs.getString(KEY_FIXED_WALLPAPER_URI, null));
|
||||||
|
config.setFixedWallpaperEnabled(prefs.getBoolean(KEY_FIXED_WALLPAPER_ENABLED, false));
|
||||||
|
|
||||||
|
// 在 saveConfig() 中保存
|
||||||
|
editor.putString(KEY_FIXED_WALLPAPER_URI, config.getFixedWallpaperUri());
|
||||||
|
editor.putBoolean(KEY_FIXED_WALLPAPER_ENABLED, config.isFixedWallpaperEnabled());
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **在 `SettingsFragment` 中添加 UI**:
|
||||||
|
- 添加选择固定壁纸按钮
|
||||||
|
- 添加固定壁纸预览 ImageView
|
||||||
|
- 添加清除固定壁纸按钮
|
||||||
|
- 实现 `ActivityResultLauncher` 处理图片选择
|
||||||
|
- 使用 Glide 加载预览缩略图
|
||||||
|
|
||||||
|
4. **在 `AutoWallpaperService` 中实现四指点击检测**:
|
||||||
|
```java
|
||||||
|
@Override
|
||||||
|
public void onTouchEvent(MotionEvent event) {
|
||||||
|
// 检测多指点击
|
||||||
|
int pointerCount = event.getPointerCount();
|
||||||
|
int action = event.getAction() & MotionEvent.ACTION_MASK;
|
||||||
|
|
||||||
|
if (pointerCount >= 4 && action == MotionEvent.ACTION_POINTER_DOWN) {
|
||||||
|
// 创建通知渠道
|
||||||
|
String channelId = "fixed_wallpaper_channel";
|
||||||
|
NotificationManager notificationManager =
|
||||||
|
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
NotificationChannel channel = new NotificationChannel(
|
||||||
|
channelId, "固定壁纸",
|
||||||
|
NotificationManager.IMPORTANCE_HIGH
|
||||||
|
);
|
||||||
|
notificationManager.createNotificationChannel(channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建通知
|
||||||
|
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||||
|
intent.setDataAndType(uri, "image/*");
|
||||||
|
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||||
|
|
||||||
|
PendingIntent pendingIntent = PendingIntent.getActivity(
|
||||||
|
this, 0, intent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
|
||||||
|
);
|
||||||
|
|
||||||
|
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
|
||||||
|
.setSmallIcon(android.R.drawable.ic_menu_gallery)
|
||||||
|
.setContentTitle("打开固定壁纸")
|
||||||
|
.setContentText("点击在系统相册中查看固定壁纸")
|
||||||
|
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.setContentIntent(pendingIntent);
|
||||||
|
|
||||||
|
// 显示通知并禁用 app
|
||||||
|
notificationManager.notify(1, builder.build());
|
||||||
|
config.setEnabled(false);
|
||||||
|
prefs.saveConfig(config);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**注意事项**:
|
||||||
|
- 固定壁纸只是收藏功能,不停止 app 自动更新
|
||||||
|
- app 启用/禁用使用 `config.isEnabled()` 控制,与固定壁纸无关
|
||||||
|
- 四指点击会同时禁用 app,但用户可以手动重新启用
|
||||||
|
- 使用通知是因为 Android 10+ 限制后台服务启动 Activity
|
||||||
|
|
||||||
### 添加新的播放模式
|
### 添加新的播放模式
|
||||||
|
|
||||||
1. 在 `PlayMode` 枚举中添加新模式
|
1. 在 `PlayMode` 枚举中添加新模式
|
||||||
|
|||||||
@@ -58,6 +58,16 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
|
<!-- Broadcast Receiver for cache scanning -->
|
||||||
|
<receiver
|
||||||
|
android:name=".receiver.CacheScanReceiver"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="cn.hugh.bz.gk2.ACTION_SCAN_CACHE" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
<!-- Album Editor Activity -->
|
<!-- Album Editor Activity -->
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.AlbumEditorActivity"
|
android:name=".ui.AlbumEditorActivity"
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ public class Album implements Serializable {
|
|||||||
private boolean enabled; // 是否启用
|
private boolean enabled; // 是否启用
|
||||||
private List<String> imageUris; // 图片URI列表(与 folders 同级)
|
private List<String> imageUris; // 图片URI列表(与 folders 同级)
|
||||||
private List<String> videoUris; // 视频URI列表(与 imageUris 同级)
|
private List<String> videoUris; // 视频URI列表(与 imageUris 同级)
|
||||||
|
private long lastScanTime; // 最近扫描时间
|
||||||
|
|
||||||
public Album() {
|
public Album() {
|
||||||
this.id = UUID.randomUUID().toString();
|
this.id = UUID.randomUUID().toString();
|
||||||
@@ -36,6 +37,7 @@ public class Album implements Serializable {
|
|||||||
this.enabled = true;
|
this.enabled = true;
|
||||||
this.imageUris = new ArrayList<>();
|
this.imageUris = new ArrayList<>();
|
||||||
this.videoUris = new ArrayList<>();
|
this.videoUris = new ArrayList<>();
|
||||||
|
this.lastScanTime = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Getters and Setters
|
// Getters and Setters
|
||||||
@@ -135,6 +137,14 @@ public class Album implements Serializable {
|
|||||||
this.videoUris = videoUris;
|
this.videoUris = videoUris;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public long getLastScanTime() {
|
||||||
|
return lastScanTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLastScanTime(long lastScanTime) {
|
||||||
|
this.lastScanTime = lastScanTime;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 判断是否为默认相册
|
* 判断是否为默认相册
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ public class AppConfig {
|
|||||||
private boolean doubleTapEnabled;
|
private boolean doubleTapEnabled;
|
||||||
private String fixedWallpaperUri;
|
private String fixedWallpaperUri;
|
||||||
private boolean isFixedWallpaperEnabled;
|
private boolean isFixedWallpaperEnabled;
|
||||||
|
private int autoScanIntervalHours; // 自动扫描间隔(小时),0 表示禁用
|
||||||
|
|
||||||
public AppConfig() {
|
public AppConfig() {
|
||||||
this.selectedFolders = new java.util.ArrayList<>();
|
this.selectedFolders = new java.util.ArrayList<>();
|
||||||
@@ -31,6 +32,7 @@ public class AppConfig {
|
|||||||
this.videoPauseOnBattery = true;
|
this.videoPauseOnBattery = true;
|
||||||
this.doubleTapEnabled = true;
|
this.doubleTapEnabled = true;
|
||||||
this.isFixedWallpaperEnabled = false;
|
this.isFixedWallpaperEnabled = false;
|
||||||
|
this.autoScanIntervalHours = 0; // 默认禁用自动扫描
|
||||||
}
|
}
|
||||||
|
|
||||||
// Getters and Setters
|
// Getters and Setters
|
||||||
@@ -79,6 +81,9 @@ public class AppConfig {
|
|||||||
public boolean isFixedWallpaperEnabled() { return isFixedWallpaperEnabled; }
|
public boolean isFixedWallpaperEnabled() { return isFixedWallpaperEnabled; }
|
||||||
public void setFixedWallpaperEnabled(boolean isFixedWallpaperEnabled) { this.isFixedWallpaperEnabled = isFixedWallpaperEnabled; }
|
public void setFixedWallpaperEnabled(boolean isFixedWallpaperEnabled) { this.isFixedWallpaperEnabled = isFixedWallpaperEnabled; }
|
||||||
|
|
||||||
|
public int getAutoScanIntervalHours() { return autoScanIntervalHours; }
|
||||||
|
public void setAutoScanIntervalHours(int autoScanIntervalHours) { this.autoScanIntervalHours = autoScanIntervalHours; }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查是否有可用的媒体源(文件夹、图片或视频)
|
* 检查是否有可用的媒体源(文件夹、图片或视频)
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package cn.hugh.bz.gk2.receiver;
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import cn.hugh.bz.gk2.model.Album;
|
||||||
|
import cn.hugh.bz.gk2.utils.FileLogger;
|
||||||
|
import cn.hugh.bz.gk2.utils.MediaScanner;
|
||||||
|
import cn.hugh.bz.gk2.wallpaper.AlbumPreferences;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缓存扫描接收器
|
||||||
|
* 定时清除缓存并重新扫描相册文件夹
|
||||||
|
*/
|
||||||
|
public class CacheScanReceiver extends BroadcastReceiver {
|
||||||
|
private static final String TAG = "CacheScanReceiver";
|
||||||
|
public static final String ACTION_SCAN_CACHE = "cn.hugh.bz.gk2.ACTION_SCAN_CACHE";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onReceive(Context context, Intent intent) {
|
||||||
|
if (intent == null || !ACTION_SCAN_CACHE.equals(intent.getAction())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
FileLogger fileLogger = FileLogger.getInstance(context);
|
||||||
|
String msg = "CacheScanReceiver triggered: starting cache scan";
|
||||||
|
Log.i(TAG, msg);
|
||||||
|
fileLogger.log(TAG, msg);
|
||||||
|
|
||||||
|
// 在后台线程执行扫描任务
|
||||||
|
new Thread(() -> {
|
||||||
|
try {
|
||||||
|
scanAllAlbums(context, fileLogger);
|
||||||
|
} catch (Exception e) {
|
||||||
|
String errorMsg = "Error during cache scan: " + e.getMessage();
|
||||||
|
Log.e(TAG, errorMsg, e);
|
||||||
|
fileLogger.log(TAG, errorMsg);
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫描所有相册的文件夹
|
||||||
|
*/
|
||||||
|
private void scanAllAlbums(Context context, FileLogger fileLogger) {
|
||||||
|
AlbumPreferences albumPrefs = new AlbumPreferences(context);
|
||||||
|
List<Album> albums = albumPrefs.loadAlbums();
|
||||||
|
|
||||||
|
if (albums == null || albums.isEmpty()) {
|
||||||
|
String msg = "No albums found, skipping cache scan";
|
||||||
|
Log.i(TAG, msg);
|
||||||
|
fileLogger.log(TAG, msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
MediaScanner scanner = new MediaScanner(context);
|
||||||
|
int totalFolders = 0;
|
||||||
|
int scannedFolders = 0;
|
||||||
|
|
||||||
|
// 遍历所有相册
|
||||||
|
for (Album album : albums) {
|
||||||
|
List<String> folders = album.getFolders();
|
||||||
|
if (folders == null || folders.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
totalFolders += folders.size();
|
||||||
|
boolean albumScanned = false;
|
||||||
|
|
||||||
|
// 扫描每个文件夹
|
||||||
|
for (String folder : folders) {
|
||||||
|
try {
|
||||||
|
String scanMsg = "Scanning folder: " + folder + " (album: " + album.getName() + ")";
|
||||||
|
Log.i(TAG, scanMsg);
|
||||||
|
fileLogger.log(TAG, scanMsg);
|
||||||
|
|
||||||
|
// 清除缓存并重新扫描
|
||||||
|
scanner.rescanFolder(folder);
|
||||||
|
scannedFolders++;
|
||||||
|
albumScanned = true;
|
||||||
|
|
||||||
|
String successMsg = "Successfully scanned folder: " + folder;
|
||||||
|
Log.i(TAG, successMsg);
|
||||||
|
fileLogger.log(TAG, successMsg);
|
||||||
|
} catch (Exception e) {
|
||||||
|
String errorMsg = "Error scanning folder: " + folder + ", error: " + e.getMessage();
|
||||||
|
Log.e(TAG, errorMsg, e);
|
||||||
|
fileLogger.log(TAG, errorMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新相册的最近扫描时间
|
||||||
|
if (albumScanned) {
|
||||||
|
album.setLastScanTime(System.currentTimeMillis());
|
||||||
|
albumPrefs.updateAlbum(album);
|
||||||
|
String updateMsg = "Updated last scan time for album: " + album.getName();
|
||||||
|
Log.i(TAG, updateMsg);
|
||||||
|
fileLogger.log(TAG, updateMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭扫描器
|
||||||
|
scanner.shutdown();
|
||||||
|
|
||||||
|
String summaryMsg = "Cache scan completed: scanned " + scannedFolders + "/" + totalFolders + " folders";
|
||||||
|
Log.i(TAG, summaryMsg);
|
||||||
|
fileLogger.log(TAG, summaryMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -42,6 +42,7 @@ import cn.hugh.bz.gk2.model.MediaType;
|
|||||||
import cn.hugh.bz.gk2.model.PlayMode;
|
import cn.hugh.bz.gk2.model.PlayMode;
|
||||||
import cn.hugh.bz.gk2.model.WallpaperMedia;
|
import cn.hugh.bz.gk2.model.WallpaperMedia;
|
||||||
import cn.hugh.bz.gk2.utils.MediaScanner;
|
import cn.hugh.bz.gk2.utils.MediaScanner;
|
||||||
|
import cn.hugh.bz.gk2.utils.ScanTaskManager;
|
||||||
import cn.hugh.bz.gk2.utils.ThumbnailHelper;
|
import cn.hugh.bz.gk2.utils.ThumbnailHelper;
|
||||||
import cn.hugh.bz.gk2.wallpaper.AlbumPreferences;
|
import cn.hugh.bz.gk2.wallpaper.AlbumPreferences;
|
||||||
|
|
||||||
@@ -83,6 +84,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
|
|||||||
private MediaScanner mediaScanner;
|
private MediaScanner mediaScanner;
|
||||||
private ProgressDialog progressDialog;
|
private ProgressDialog progressDialog;
|
||||||
private Handler mainHandler;
|
private Handler mainHandler;
|
||||||
|
private ScanTaskManager scanTaskManager;
|
||||||
|
|
||||||
// 文件夹图片数量缓存
|
// 文件夹图片数量缓存
|
||||||
private final java.util.Map<String, Integer> folderImageCountCache = new java.util.HashMap<>();
|
private final java.util.Map<String, Integer> folderImageCountCache = new java.util.HashMap<>();
|
||||||
@@ -101,6 +103,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
|
|||||||
// 初始化扫描器和 Handler
|
// 初始化扫描器和 Handler
|
||||||
mediaScanner = new MediaScanner(this);
|
mediaScanner = new MediaScanner(this);
|
||||||
mainHandler = new Handler(Looper.getMainLooper());
|
mainHandler = new Handler(Looper.getMainLooper());
|
||||||
|
scanTaskManager = ScanTaskManager.getInstance(this);
|
||||||
|
|
||||||
initFolderPickerLauncher();
|
initFolderPickerLauncher();
|
||||||
initImagePickerLauncher();
|
initImagePickerLauncher();
|
||||||
@@ -112,6 +115,10 @@ public class AlbumEditorActivity extends AppCompatActivity {
|
|||||||
@Override
|
@Override
|
||||||
protected void onDestroy() {
|
protected void onDestroy() {
|
||||||
super.onDestroy();
|
super.onDestroy();
|
||||||
|
// 取消所有扫描任务
|
||||||
|
if (scanTaskManager != null) {
|
||||||
|
scanTaskManager.cancelAllTasks();
|
||||||
|
}
|
||||||
// 关闭扫描器
|
// 关闭扫描器
|
||||||
if (mediaScanner != null) {
|
if (mediaScanner != null) {
|
||||||
mediaScanner.shutdown();
|
mediaScanner.shutdown();
|
||||||
@@ -358,7 +365,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
|
|||||||
|
|
||||||
// 文件夹列表
|
// 文件夹列表
|
||||||
rvFolders.setLayoutManager(new LinearLayoutManager(this));
|
rvFolders.setLayoutManager(new LinearLayoutManager(this));
|
||||||
folderAdapter = new FolderAdapter(this, folders, this::removeFolder, folderImageCountCache);
|
folderAdapter = new FolderAdapter(this, folders, this::removeFolder, folderImageCountCache, scanTaskManager);
|
||||||
rvFolders.setAdapter(folderAdapter);
|
rvFolders.setAdapter(folderAdapter);
|
||||||
|
|
||||||
// 媒体列表(图片和视频)
|
// 媒体列表(图片和视频)
|
||||||
@@ -491,28 +498,38 @@ public class AlbumEditorActivity extends AppCompatActivity {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 预加载所有文件夹的图片数量(编辑现有相册时)
|
* 预加载所有文件夹的图片数量(编辑现有相册时)
|
||||||
* 在后台线程中并行扫描所有文件夹
|
* 使用 ScanTaskManager 管理扫描任务
|
||||||
*/
|
*/
|
||||||
private void preloadFolderImageCounts() {
|
private void preloadFolderImageCounts() {
|
||||||
if (folders.isEmpty()) {
|
if (folders.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
new Thread(() -> {
|
// 使用 ScanTaskManager 异步扫描所有文件夹
|
||||||
MediaScanner scanner = new MediaScanner(this);
|
for (String folderUri : folders) {
|
||||||
for (String folderUri : folders) {
|
// 检查是否已有缓存
|
||||||
// 检查是否已有缓存
|
if (!folderImageCountCache.containsKey(folderUri)) {
|
||||||
if (!folderImageCountCache.containsKey(folderUri)) {
|
scanTaskManager.scanFolderAsync(folderUri, new ScanTaskManager.ScanCallback() {
|
||||||
// 扫描文件夹
|
@Override
|
||||||
List<WallpaperMedia> mediaList = scanner.scanFolder(folderUri);
|
public void onScanComplete(String folderPath, List<WallpaperMedia> mediaList) {
|
||||||
int count = mediaList != null ? mediaList.size() : 0;
|
int count = mediaList != null ? mediaList.size() : 0;
|
||||||
|
// 缓存结果
|
||||||
|
folderImageCountCache.put(folderUri, count);
|
||||||
|
// 通知适配器更新(如果需要)
|
||||||
|
mainHandler.post(() -> {
|
||||||
|
if (folderAdapter != null) {
|
||||||
|
folderAdapter.notifyDataSetChanged();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 缓存结果
|
@Override
|
||||||
folderImageCountCache.put(folderUri, count);
|
public void onScanError(String folderPath, String error) {
|
||||||
}
|
android.util.Log.e("AlbumEditorActivity", "Error scanning folder: " + error);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
scanner.shutdown();
|
}
|
||||||
}).start();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void openFolderPicker() {
|
private void openFolderPicker() {
|
||||||
@@ -644,14 +661,17 @@ public class AlbumEditorActivity extends AppCompatActivity {
|
|||||||
private List<String> folders;
|
private List<String> folders;
|
||||||
private final OnFolderRemoveListener removeListener;
|
private final OnFolderRemoveListener removeListener;
|
||||||
private final java.util.Map<String, Integer> imageCountCache;
|
private final java.util.Map<String, Integer> imageCountCache;
|
||||||
|
private final ScanTaskManager scanTaskManager;
|
||||||
|
|
||||||
public FolderAdapter(android.content.Context context, List<String> folders,
|
public FolderAdapter(android.content.Context context, List<String> folders,
|
||||||
OnFolderRemoveListener removeListener,
|
OnFolderRemoveListener removeListener,
|
||||||
java.util.Map<String, Integer> imageCountCache) {
|
java.util.Map<String, Integer> imageCountCache,
|
||||||
|
ScanTaskManager scanTaskManager) {
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.folders = folders != null ? folders : new ArrayList<>();
|
this.folders = folders != null ? folders : new ArrayList<>();
|
||||||
this.removeListener = removeListener;
|
this.removeListener = removeListener;
|
||||||
this.imageCountCache = imageCountCache != null ? imageCountCache : new java.util.HashMap<>();
|
this.imageCountCache = imageCountCache != null ? imageCountCache : new java.util.HashMap<>();
|
||||||
|
this.scanTaskManager = scanTaskManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateFolders(List<String> folders) {
|
public void updateFolders(List<String> folders) {
|
||||||
@@ -721,21 +741,29 @@ public class AlbumEditorActivity extends AppCompatActivity {
|
|||||||
// 首次显示,标记为待扫描
|
// 首次显示,标记为待扫描
|
||||||
tvImageCount.setText("扫描中...");
|
tvImageCount.setText("扫描中...");
|
||||||
|
|
||||||
// 异步扫描(只扫描一次)
|
// 使用 ScanTaskManager 异步扫描
|
||||||
new Thread(() -> {
|
scanTaskManager.scanFolderAsync(folderUri, new ScanTaskManager.ScanCallback() {
|
||||||
MediaScanner scanner = new MediaScanner(context);
|
@Override
|
||||||
List<WallpaperMedia> mediaList = scanner.scanFolder(folderUri);
|
public void onScanComplete(String folderPath, List<WallpaperMedia> mediaList) {
|
||||||
int count = mediaList != null ? mediaList.size() : 0;
|
int count = mediaList != null ? mediaList.size() : 0;
|
||||||
|
|
||||||
// 更新缓存
|
// 更新缓存
|
||||||
imageCountCache.put(folderUri, count);
|
imageCountCache.put(folderUri, count);
|
||||||
scanner.shutdown();
|
|
||||||
|
|
||||||
// 更新 UI
|
// 更新 UI(在主线程)
|
||||||
tvImageCount.post(() -> {
|
tvImageCount.post(() -> {
|
||||||
tvImageCount.setText(count + " 个文件");
|
tvImageCount.setText(count + " 个文件");
|
||||||
});
|
});
|
||||||
}).start();
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onScanError(String folderPath, String error) {
|
||||||
|
// 更新 UI 显示错误
|
||||||
|
tvImageCount.post(() -> {
|
||||||
|
tvImageCount.setText("扫描失败");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import cn.hugh.bz.gk2.model.PlayMode;
|
|||||||
import cn.hugh.bz.gk2.model.WallpaperMedia;
|
import cn.hugh.bz.gk2.model.WallpaperMedia;
|
||||||
import cn.hugh.bz.gk2.utils.BackgroundHelper;
|
import cn.hugh.bz.gk2.utils.BackgroundHelper;
|
||||||
import cn.hugh.bz.gk2.utils.MediaScanner;
|
import cn.hugh.bz.gk2.utils.MediaScanner;
|
||||||
|
import cn.hugh.bz.gk2.utils.ScanTaskManager;
|
||||||
import cn.hugh.bz.gk2.wallpaper.AlbumPreferences;
|
import cn.hugh.bz.gk2.wallpaper.AlbumPreferences;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -42,6 +43,7 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
private AlbumPreferences albumPrefs;
|
private AlbumPreferences albumPrefs;
|
||||||
private AlbumAdapter adapter;
|
private AlbumAdapter adapter;
|
||||||
private List<Album> albums;
|
private List<Album> albums;
|
||||||
|
private ScanTaskManager scanTaskManager;
|
||||||
|
|
||||||
// 目标相册ID(用于从历史页面跳转)
|
// 目标相册ID(用于从历史页面跳转)
|
||||||
public static String targetAlbumId = null;
|
public static String targetAlbumId = null;
|
||||||
@@ -50,6 +52,7 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||||
super.onCreate(savedInstanceState);
|
super.onCreate(savedInstanceState);
|
||||||
albumPrefs = new AlbumPreferences(requireContext());
|
albumPrefs = new AlbumPreferences(requireContext());
|
||||||
|
scanTaskManager = ScanTaskManager.getInstance(requireContext());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@@ -91,7 +94,7 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
public void onDelete(Album album) {
|
public void onDelete(Album album) {
|
||||||
deleteAlbum(album);
|
deleteAlbum(album);
|
||||||
}
|
}
|
||||||
});
|
}, scanTaskManager);
|
||||||
rvAlbums.setAdapter(adapter);
|
rvAlbums.setAdapter(adapter);
|
||||||
|
|
||||||
// 创建相册按钮
|
// 创建相册按钮
|
||||||
@@ -218,6 +221,15 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
targetAlbumId = null;
|
targetAlbumId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDestroyView() {
|
||||||
|
super.onDestroyView();
|
||||||
|
// 取消所有正在执行的扫描任务
|
||||||
|
if (scanTaskManager != null) {
|
||||||
|
scanTaskManager.cancelAllTasks();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 相册列表适配器
|
* 相册列表适配器
|
||||||
*/
|
*/
|
||||||
@@ -227,12 +239,14 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
private List<Album> albums;
|
private List<Album> albums;
|
||||||
private final AlbumCallback callback;
|
private final AlbumCallback callback;
|
||||||
private final AlbumPreferences prefs;
|
private final AlbumPreferences prefs;
|
||||||
|
private final ScanTaskManager scanTaskManager;
|
||||||
|
|
||||||
public AlbumAdapter(Context context, List<Album> albums, AlbumCallback callback) {
|
public AlbumAdapter(Context context, List<Album> albums, AlbumCallback callback, ScanTaskManager scanTaskManager) {
|
||||||
this.context = context;
|
this.context = context;
|
||||||
this.albums = albums != null ? albums : new ArrayList<>();
|
this.albums = albums != null ? albums : new ArrayList<>();
|
||||||
this.callback = callback;
|
this.callback = callback;
|
||||||
this.prefs = new AlbumPreferences(context);
|
this.prefs = new AlbumPreferences(context);
|
||||||
|
this.scanTaskManager = scanTaskManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateAlbums(List<Album> albums) {
|
public void updateAlbums(List<Album> albums) {
|
||||||
@@ -264,6 +278,7 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
private final TextView tvAlbumInfo;
|
private final TextView tvAlbumInfo;
|
||||||
private final TextView tvPlayMode;
|
private final TextView tvPlayMode;
|
||||||
private final TextView tvInterval;
|
private final TextView tvInterval;
|
||||||
|
private final TextView tvLastScanTime;
|
||||||
private final MaterialButton btnEdit;
|
private final MaterialButton btnEdit;
|
||||||
private final MaterialButton btnSwitch;
|
private final MaterialButton btnSwitch;
|
||||||
private final MaterialButton btnDelete;
|
private final MaterialButton btnDelete;
|
||||||
@@ -275,6 +290,7 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
tvAlbumInfo = itemView.findViewById(R.id.tvAlbumInfo);
|
tvAlbumInfo = itemView.findViewById(R.id.tvAlbumInfo);
|
||||||
tvPlayMode = itemView.findViewById(R.id.tvPlayMode);
|
tvPlayMode = itemView.findViewById(R.id.tvPlayMode);
|
||||||
tvInterval = itemView.findViewById(R.id.tvInterval);
|
tvInterval = itemView.findViewById(R.id.tvInterval);
|
||||||
|
tvLastScanTime = itemView.findViewById(R.id.tvLastScanTime);
|
||||||
btnEdit = itemView.findViewById(R.id.btnEdit);
|
btnEdit = itemView.findViewById(R.id.btnEdit);
|
||||||
btnSwitch = itemView.findViewById(R.id.btnSwitch);
|
btnSwitch = itemView.findViewById(R.id.btnSwitch);
|
||||||
btnDelete = itemView.findViewById(R.id.btnDelete);
|
btnDelete = itemView.findViewById(R.id.btnDelete);
|
||||||
@@ -304,27 +320,32 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
|
|
||||||
// 异步计算文件夹中的媒体数量并显示更详细的信息
|
// 异步计算文件夹中的媒体数量并显示更详细的信息
|
||||||
if (folderCount > 0) {
|
if (folderCount > 0) {
|
||||||
new Thread(() -> {
|
// 先显示缓存的扫描时间
|
||||||
MediaScanner scanner = new MediaScanner(context);
|
updateLastScanTime(album);
|
||||||
int totalImages = directImageCount;
|
|
||||||
int totalVideos = directVideoCount;
|
// 使用 ScanTaskManager 异步扫描
|
||||||
|
scanTaskManager.scanFoldersAsync(album.getFolders(), new ScanTaskManager.MultiFolderScanCallback() {
|
||||||
for (String folder : album.getFolders()) {
|
@Override
|
||||||
List<WallpaperMedia> mediaList = scanner.scanFolder(folder);
|
public void onAllComplete(int totalImages, int totalVideos) {
|
||||||
for (WallpaperMedia m : mediaList) {
|
// 加上直接添加的图片和视频
|
||||||
if (m.isVideo()) totalVideos++;
|
int finalImages = totalImages + directImageCount;
|
||||||
else totalImages++;
|
int finalVideos = totalVideos + directVideoCount;
|
||||||
|
|
||||||
|
// 更新相册的最近扫描时间
|
||||||
|
album.setLastScanTime(System.currentTimeMillis());
|
||||||
|
prefs.updateAlbum(album);
|
||||||
|
|
||||||
|
final String summary = folderCount + " 个文件夹 · " + finalImages + " 张图片 · " + finalVideos + " 个视频";
|
||||||
|
|
||||||
|
// 更新 UI(在主线程)
|
||||||
|
if (tvAlbumInfo != null) {
|
||||||
|
tvAlbumInfo.post(() -> {
|
||||||
|
tvAlbumInfo.setText(summary);
|
||||||
|
updateLastScanTime(album);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
});
|
||||||
final String summary = folderCount + " 个文件夹 · " + totalImages + " 张图片 · " + totalVideos + " 个视频";
|
|
||||||
|
|
||||||
// 更新 UI
|
|
||||||
if (tvAlbumInfo != null) {
|
|
||||||
tvAlbumInfo.post(() -> tvAlbumInfo.setText(summary));
|
|
||||||
}
|
|
||||||
scanner.shutdown();
|
|
||||||
}).start();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 播放模式
|
// 播放模式
|
||||||
@@ -334,6 +355,9 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
// 更换间隔
|
// 更换间隔
|
||||||
tvInterval.setText(album.getIntervalMinutes() + " 分钟");
|
tvInterval.setText(album.getIntervalMinutes() + " 分钟");
|
||||||
|
|
||||||
|
// 最近扫描时间
|
||||||
|
updateLastScanTime(album);
|
||||||
|
|
||||||
// 默认相册不显示删除按钮
|
// 默认相册不显示删除按钮
|
||||||
if (album.isDefault()) {
|
if (album.isDefault()) {
|
||||||
btnDelete.setVisibility(View.GONE);
|
btnDelete.setVisibility(View.GONE);
|
||||||
@@ -362,6 +386,51 @@ public class AlbumManagementFragment extends Fragment {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新最近扫描时间显示
|
||||||
|
*/
|
||||||
|
private void updateLastScanTime(Album album) {
|
||||||
|
long lastScanTime = album.getLastScanTime();
|
||||||
|
|
||||||
|
if (lastScanTime == 0) {
|
||||||
|
tvLastScanTime.setText("未扫描");
|
||||||
|
} else {
|
||||||
|
String timeText = formatTimeAgo(lastScanTime);
|
||||||
|
tvLastScanTime.setText(timeText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化时间为"多久之前"的形式
|
||||||
|
*/
|
||||||
|
private String formatTimeAgo(long timestamp) {
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
long diff = now - timestamp;
|
||||||
|
|
||||||
|
if (diff < 0) {
|
||||||
|
return "刚刚";
|
||||||
|
}
|
||||||
|
|
||||||
|
long seconds = diff / 1000;
|
||||||
|
long minutes = seconds / 60;
|
||||||
|
long hours = minutes / 60;
|
||||||
|
long days = hours / 24;
|
||||||
|
|
||||||
|
if (seconds < 60) {
|
||||||
|
return "刚刚";
|
||||||
|
} else if (minutes < 60) {
|
||||||
|
return minutes + " 分钟前";
|
||||||
|
} else if (hours < 24) {
|
||||||
|
return hours + " 小时前";
|
||||||
|
} else if (days < 7) {
|
||||||
|
return days + " 天前";
|
||||||
|
} else {
|
||||||
|
// 超过 7 天显示具体日期
|
||||||
|
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM-dd HH:mm", java.util.Locale.getDefault());
|
||||||
|
return sdf.format(new java.util.Date(timestamp));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AlbumCallback {
|
interface AlbumCallback {
|
||||||
|
|||||||
@@ -57,6 +57,14 @@ public class SettingsFragment extends Fragment {
|
|||||||
private MaterialButton btnClearFixedWallpaper;
|
private MaterialButton btnClearFixedWallpaper;
|
||||||
private ImageView ivFixedWallpaperPreview;
|
private ImageView ivFixedWallpaperPreview;
|
||||||
|
|
||||||
|
// 自动扫描控件
|
||||||
|
private android.widget.RadioGroup radioGroupAutoScan;
|
||||||
|
private android.widget.RadioButton radioAutoScanDisabled;
|
||||||
|
private android.widget.RadioButton radioAutoScan1Hour;
|
||||||
|
private android.widget.RadioButton radioAutoScan6Hours;
|
||||||
|
private android.widget.RadioButton radioAutoScan12Hours;
|
||||||
|
private android.widget.RadioButton radioAutoScan24Hours;
|
||||||
|
|
||||||
// 图片选择器
|
// 图片选择器
|
||||||
private ActivityResultLauncher<Intent> pickImageLauncher;
|
private ActivityResultLauncher<Intent> pickImageLauncher;
|
||||||
private ActivityResultLauncher<Intent> pickFixedWallpaperLauncher;
|
private ActivityResultLauncher<Intent> pickFixedWallpaperLauncher;
|
||||||
@@ -82,6 +90,7 @@ public class SettingsFragment extends Fragment {
|
|||||||
loadVideoSettings();
|
loadVideoSettings();
|
||||||
loadDoubleTapSettings();
|
loadDoubleTapSettings();
|
||||||
loadFixedWallpaperSettings();
|
loadFixedWallpaperSettings();
|
||||||
|
loadAutoScanSettings();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void initViews(View view) {
|
private void initViews(View view) {
|
||||||
@@ -138,9 +147,18 @@ public class SettingsFragment extends Fragment {
|
|||||||
btnClearFixedWallpaper = view.findViewById(R.id.btnClearFixedWallpaper);
|
btnClearFixedWallpaper = view.findViewById(R.id.btnClearFixedWallpaper);
|
||||||
ivFixedWallpaperPreview = view.findViewById(R.id.ivFixedWallpaperPreview);
|
ivFixedWallpaperPreview = view.findViewById(R.id.ivFixedWallpaperPreview);
|
||||||
|
|
||||||
|
// 自动扫描控件
|
||||||
|
radioGroupAutoScan = view.findViewById(R.id.radioGroupAutoScan);
|
||||||
|
radioAutoScanDisabled = view.findViewById(R.id.radioAutoScanDisabled);
|
||||||
|
radioAutoScan1Hour = view.findViewById(R.id.radioAutoScan1Hour);
|
||||||
|
radioAutoScan6Hours = view.findViewById(R.id.radioAutoScan6Hours);
|
||||||
|
radioAutoScan12Hours = view.findViewById(R.id.radioAutoScan12Hours);
|
||||||
|
radioAutoScan24Hours = view.findViewById(R.id.radioAutoScan24Hours);
|
||||||
|
|
||||||
setupVideoSettingsListeners();
|
setupVideoSettingsListeners();
|
||||||
setupDoubleTapListener();
|
setupDoubleTapListener();
|
||||||
setupFixedWallpaperListeners();
|
setupFixedWallpaperListeners();
|
||||||
|
setupAutoScanListener();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setupVideoSettingsListeners() {
|
private void setupVideoSettingsListeners() {
|
||||||
@@ -416,6 +434,71 @@ public class SettingsFragment extends Fragment {
|
|||||||
requireContext().sendBroadcast(intent);
|
requireContext().sendBroadcast(intent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 自动扫描相关方法 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置自动扫描监听器
|
||||||
|
*/
|
||||||
|
private void setupAutoScanListener() {
|
||||||
|
radioGroupAutoScan.setOnCheckedChangeListener((group, checkedId) -> {
|
||||||
|
int intervalHours = 0;
|
||||||
|
|
||||||
|
if (checkedId == R.id.radioAutoScanDisabled) {
|
||||||
|
intervalHours = 0;
|
||||||
|
} else if (checkedId == R.id.radioAutoScan1Hour) {
|
||||||
|
intervalHours = 1;
|
||||||
|
} else if (checkedId == R.id.radioAutoScan6Hours) {
|
||||||
|
intervalHours = 6;
|
||||||
|
} else if (checkedId == R.id.radioAutoScan12Hours) {
|
||||||
|
intervalHours = 12;
|
||||||
|
} else if (checkedId == R.id.radioAutoScan24Hours) {
|
||||||
|
intervalHours = 24;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存配置
|
||||||
|
AppConfig config = wallpaperPrefs.loadConfig();
|
||||||
|
config.setAutoScanIntervalHours(intervalHours);
|
||||||
|
wallpaperPrefs.saveConfig(config);
|
||||||
|
|
||||||
|
// 调度自动扫描任务
|
||||||
|
cn.hugh.bz.gk2.utils.AlarmScheduler scheduler = new cn.hugh.bz.gk2.utils.AlarmScheduler(requireContext());
|
||||||
|
scheduler.scheduleCacheScan(intervalHours);
|
||||||
|
|
||||||
|
// 显示提示
|
||||||
|
String message;
|
||||||
|
if (intervalHours == 0) {
|
||||||
|
message = "已禁用自动扫描";
|
||||||
|
} else {
|
||||||
|
message = "已设置自动扫描间隔为 " + intervalHours + " 小时";
|
||||||
|
}
|
||||||
|
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载自动扫描设置
|
||||||
|
*/
|
||||||
|
private void loadAutoScanSettings() {
|
||||||
|
AppConfig config = wallpaperPrefs.loadConfig();
|
||||||
|
int intervalHours = config.getAutoScanIntervalHours();
|
||||||
|
|
||||||
|
// 根据间隔时间选择对应的单选按钮
|
||||||
|
if (intervalHours == 0) {
|
||||||
|
radioAutoScanDisabled.setChecked(true);
|
||||||
|
} else if (intervalHours == 1) {
|
||||||
|
radioAutoScan1Hour.setChecked(true);
|
||||||
|
} else if (intervalHours == 6) {
|
||||||
|
radioAutoScan6Hours.setChecked(true);
|
||||||
|
} else if (intervalHours == 12) {
|
||||||
|
radioAutoScan12Hours.setChecked(true);
|
||||||
|
} else if (intervalHours == 24) {
|
||||||
|
radioAutoScan24Hours.setChecked(true);
|
||||||
|
} else {
|
||||||
|
// 默认选择禁用
|
||||||
|
radioAutoScanDisabled.setChecked(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onResume() {
|
public void onResume() {
|
||||||
super.onResume();
|
super.onResume();
|
||||||
@@ -423,5 +506,6 @@ public class SettingsFragment extends Fragment {
|
|||||||
loadVideoSettings();
|
loadVideoSettings();
|
||||||
loadDoubleTapSettings();
|
loadDoubleTapSettings();
|
||||||
loadFixedWallpaperSettings();
|
loadFixedWallpaperSettings();
|
||||||
|
loadAutoScanSettings();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,6 +12,7 @@ import cn.hugh.bz.gk2.receiver.WallpaperChangeReceiver;
|
|||||||
public class AlarmScheduler {
|
public class AlarmScheduler {
|
||||||
private static final String TAG = "AlarmScheduler";
|
private static final String TAG = "AlarmScheduler";
|
||||||
private static final int REQUEST_CODE = 1000;
|
private static final int REQUEST_CODE = 1000;
|
||||||
|
private static final int CACHE_SCAN_REQUEST_CODE = 1001;
|
||||||
|
|
||||||
private final Context context;
|
private final Context context;
|
||||||
private final AlarmManager alarmManager;
|
private final AlarmManager alarmManager;
|
||||||
@@ -134,4 +135,115 @@ public class AlarmScheduler {
|
|||||||
fileLogger.log(TAG, errorMsg);
|
fileLogger.log(TAG, errorMsg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调度缓存扫描任务
|
||||||
|
* @param intervalHours 扫描间隔(小时),0 表示取消调度
|
||||||
|
*/
|
||||||
|
public void scheduleCacheScan(int intervalHours) {
|
||||||
|
String msg = "scheduleCacheScan called: intervalHours=" + intervalHours;
|
||||||
|
Log.i(TAG, msg);
|
||||||
|
fileLogger.log(TAG, msg);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 先取消现有的调度
|
||||||
|
cancelCacheScan();
|
||||||
|
|
||||||
|
// 如果间隔为 0,则不重新调度
|
||||||
|
if (intervalHours <= 0) {
|
||||||
|
String cancelMsg = "Cache scan disabled (intervalHours=" + intervalHours + ")";
|
||||||
|
Log.i(TAG, cancelMsg);
|
||||||
|
fileLogger.log(TAG, cancelMsg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算间隔(毫秒)
|
||||||
|
long intervalMillis = intervalHours * 60L * 60L * 1000L;
|
||||||
|
long triggerAtMillis = System.currentTimeMillis() + intervalMillis;
|
||||||
|
|
||||||
|
String timeMsg = "Scheduling cache scan: intervalMillis=" + intervalMillis +
|
||||||
|
", triggerAtMillis=" + triggerAtMillis +
|
||||||
|
", currentTime=" + System.currentTimeMillis();
|
||||||
|
Log.i(TAG, timeMsg);
|
||||||
|
fileLogger.log(TAG, timeMsg);
|
||||||
|
|
||||||
|
// 创建 PendingIntent
|
||||||
|
Intent intent = new Intent(context, cn.hugh.bz.gk2.receiver.CacheScanReceiver.class);
|
||||||
|
intent.setAction(cn.hugh.bz.gk2.receiver.CacheScanReceiver.ACTION_SCAN_CACHE);
|
||||||
|
|
||||||
|
PendingIntent pendingIntent = PendingIntent.getBroadcast(
|
||||||
|
context,
|
||||||
|
CACHE_SCAN_REQUEST_CODE,
|
||||||
|
intent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
|
||||||
|
);
|
||||||
|
|
||||||
|
if (pendingIntent == null) {
|
||||||
|
String error = "ERROR: PendingIntent is null for cache scan!";
|
||||||
|
Log.e(TAG, error);
|
||||||
|
fileLogger.log(TAG, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调度闹钟(使用不精确闹钟以节省电量)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
alarmManager.setAndAllowWhileIdle(
|
||||||
|
AlarmManager.RTC_WAKEUP,
|
||||||
|
triggerAtMillis,
|
||||||
|
pendingIntent
|
||||||
|
);
|
||||||
|
String apiMsg = "Cache scan scheduled using setAndAllowWhileIdle (API " + Build.VERSION.SDK_INT + ")";
|
||||||
|
Log.i(TAG, apiMsg);
|
||||||
|
fileLogger.log(TAG, apiMsg);
|
||||||
|
} else {
|
||||||
|
alarmManager.setRepeating(
|
||||||
|
AlarmManager.RTC_WAKEUP,
|
||||||
|
triggerAtMillis,
|
||||||
|
intervalMillis,
|
||||||
|
pendingIntent
|
||||||
|
);
|
||||||
|
String apiMsg = "Cache scan scheduled using setRepeating (API " + Build.VERSION.SDK_INT + ")";
|
||||||
|
Log.i(TAG, apiMsg);
|
||||||
|
fileLogger.log(TAG, apiMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
String successMsg = "✓ Cache scan scheduled successfully! Next scan in " + intervalHours + " hours";
|
||||||
|
Log.i(TAG, successMsg);
|
||||||
|
fileLogger.log(TAG, successMsg);
|
||||||
|
} catch (Exception e) {
|
||||||
|
String errorMsg = "ERROR scheduling cache scan: " + e.getMessage();
|
||||||
|
Log.e(TAG, errorMsg, e);
|
||||||
|
fileLogger.log(TAG, errorMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消缓存扫描调度
|
||||||
|
*/
|
||||||
|
public void cancelCacheScan() {
|
||||||
|
String msg = "cancelCacheScan called";
|
||||||
|
Log.i(TAG, msg);
|
||||||
|
fileLogger.log(TAG, msg);
|
||||||
|
|
||||||
|
try {
|
||||||
|
Intent intent = new Intent(context, cn.hugh.bz.gk2.receiver.CacheScanReceiver.class);
|
||||||
|
intent.setAction(cn.hugh.bz.gk2.receiver.CacheScanReceiver.ACTION_SCAN_CACHE);
|
||||||
|
|
||||||
|
PendingIntent pendingIntent = PendingIntent.getBroadcast(
|
||||||
|
context,
|
||||||
|
CACHE_SCAN_REQUEST_CODE,
|
||||||
|
intent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
|
||||||
|
);
|
||||||
|
|
||||||
|
alarmManager.cancel(pendingIntent);
|
||||||
|
String cancelMsg = "Cancelled cache scan alarm successfully";
|
||||||
|
Log.i(TAG, cancelMsg);
|
||||||
|
fileLogger.log(TAG, cancelMsg);
|
||||||
|
} catch (Exception e) {
|
||||||
|
String errorMsg = "ERROR cancelling cache scan alarm: " + e.getMessage();
|
||||||
|
Log.e(TAG, errorMsg, e);
|
||||||
|
fileLogger.log(TAG, errorMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -85,6 +85,43 @@ public class JsonHelper {
|
|||||||
return folder.lastModified() > indexFile.lastModified();
|
return folder.lastModified() > indexFile.lastModified();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除指定文件夹的索引缓存
|
||||||
|
*/
|
||||||
|
public void clearIndex(String folderPath) {
|
||||||
|
String fileName = getIndexFileName(folderPath);
|
||||||
|
File indexFile = new File(indicesDir, fileName);
|
||||||
|
|
||||||
|
if (indexFile.exists()) {
|
||||||
|
boolean deleted = indexFile.delete();
|
||||||
|
if (deleted) {
|
||||||
|
Log.i(TAG, "Cleared index: " + fileName);
|
||||||
|
} else {
|
||||||
|
Log.w(TAG, "Failed to clear index: " + fileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除所有索引缓存
|
||||||
|
*/
|
||||||
|
public void clearAllIndexes() {
|
||||||
|
if (indicesDir.exists() && indicesDir.isDirectory()) {
|
||||||
|
File[] files = indicesDir.listFiles();
|
||||||
|
if (files != null) {
|
||||||
|
int count = 0;
|
||||||
|
for (File file : files) {
|
||||||
|
if (file.isFile() && file.getName().endsWith(".json")) {
|
||||||
|
if (file.delete()) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log.i(TAG, "Cleared " + count + " index files");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static class IndexData {
|
private static class IndexData {
|
||||||
String folderPath;
|
String folderPath;
|
||||||
String folderName;
|
String folderName;
|
||||||
|
|||||||
@@ -656,4 +656,42 @@ public class MediaScanner {
|
|||||||
return "LRU Cache: " + memoryCache.size() + " entries, " +
|
return "LRU Cache: " + memoryCache.size() + " entries, " +
|
||||||
"max size=" + (MEMORY_CACHE_SIZE / 1024 / 1024) + "MB";
|
"max size=" + (MEMORY_CACHE_SIZE / 1024 / 1024) + "MB";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除指定文件夹的缓存
|
||||||
|
* 用于手动刷新或定时自动刷新
|
||||||
|
*/
|
||||||
|
public void clearCache(String folderPath) {
|
||||||
|
// 清除内存缓存
|
||||||
|
memoryCache.remove(folderPath);
|
||||||
|
lastScanTime.remove(folderPath);
|
||||||
|
|
||||||
|
// 清除磁盘缓存
|
||||||
|
jsonHelper.clearIndex(folderPath);
|
||||||
|
|
||||||
|
Log.i(TAG, "Cache cleared for: " + folderPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除所有缓存
|
||||||
|
* 用于全局刷新
|
||||||
|
*/
|
||||||
|
public void clearAllCache() {
|
||||||
|
// 清除内存缓存
|
||||||
|
memoryCache.evictAll();
|
||||||
|
lastScanTime.clear();
|
||||||
|
|
||||||
|
// 清除所有磁盘缓存
|
||||||
|
jsonHelper.clearAllIndexes();
|
||||||
|
|
||||||
|
Log.i(TAG, "All cache cleared");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 强制重新扫描文件夹(忽略缓存)
|
||||||
|
*/
|
||||||
|
public List<WallpaperMedia> rescanFolder(String folderPath) {
|
||||||
|
clearCache(folderPath);
|
||||||
|
return scanFolder(folderPath);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
package cn.hugh.bz.gk2.utils;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
import cn.hugh.bz.gk2.model.WallpaperMedia;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫描任务管理器
|
||||||
|
* 使用线程池管理媒体扫描任务,避免创建大量线程
|
||||||
|
*/
|
||||||
|
public class ScanTaskManager {
|
||||||
|
private static final String TAG = "ScanTaskManager";
|
||||||
|
private static ScanTaskManager instance;
|
||||||
|
|
||||||
|
// 使用固定大小的线程池(最多 3 个并发扫描任务)
|
||||||
|
private final ExecutorService executorService;
|
||||||
|
private final MediaScanner mediaScanner;
|
||||||
|
|
||||||
|
// 缓存正在执行的任务,用于取消
|
||||||
|
private final Map<String, Future<?>> runningTasks;
|
||||||
|
|
||||||
|
private ScanTaskManager(Context context) {
|
||||||
|
this.executorService = Executors.newFixedThreadPool(3);
|
||||||
|
this.mediaScanner = new MediaScanner(context.getApplicationContext());
|
||||||
|
this.runningTasks = new HashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static synchronized ScanTaskManager getInstance(Context context) {
|
||||||
|
if (instance == null) {
|
||||||
|
instance = new ScanTaskManager(context);
|
||||||
|
}
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫描文件夹(异步)
|
||||||
|
* @param folderPath 文件夹路径
|
||||||
|
* @param callback 回调接口
|
||||||
|
* @return 任务 ID,用于取消任务
|
||||||
|
*/
|
||||||
|
public String scanFolderAsync(String folderPath, ScanCallback callback) {
|
||||||
|
// 取消之前的任务(如果存在)
|
||||||
|
cancelTask(folderPath);
|
||||||
|
|
||||||
|
Future<?> future = executorService.submit(() -> {
|
||||||
|
try {
|
||||||
|
Log.i(TAG, "Scanning folder: " + folderPath);
|
||||||
|
List<WallpaperMedia> mediaList = mediaScanner.scanFolder(folderPath);
|
||||||
|
|
||||||
|
if (callback != null) {
|
||||||
|
callback.onScanComplete(folderPath, mediaList);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
Log.e(TAG, "Error scanning folder: " + folderPath, e);
|
||||||
|
if (callback != null) {
|
||||||
|
callback.onScanError(folderPath, e.getMessage());
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
// 任务完成后从缓存中移除
|
||||||
|
synchronized (runningTasks) {
|
||||||
|
runningTasks.remove(folderPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 缓存任务
|
||||||
|
synchronized (runningTasks) {
|
||||||
|
runningTasks.put(folderPath, future);
|
||||||
|
}
|
||||||
|
|
||||||
|
return folderPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫描多个文件夹(异步)
|
||||||
|
* @param folders 文件夹列表
|
||||||
|
* @param callback 回调接口
|
||||||
|
*/
|
||||||
|
public void scanFoldersAsync(List<String> folders, MultiFolderScanCallback callback) {
|
||||||
|
if (folders == null || folders.isEmpty()) {
|
||||||
|
if (callback != null) {
|
||||||
|
callback.onAllComplete(0, 0);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final int totalFolders = folders.size();
|
||||||
|
final int[] completedCount = {0};
|
||||||
|
final int[] totalImages = {0};
|
||||||
|
final int[] totalVideos = {0};
|
||||||
|
|
||||||
|
for (String folder : folders) {
|
||||||
|
scanFolderAsync(folder, new ScanCallback() {
|
||||||
|
@Override
|
||||||
|
public void onScanComplete(String folderPath, List<WallpaperMedia> mediaList) {
|
||||||
|
synchronized (completedCount) {
|
||||||
|
completedCount[0]++;
|
||||||
|
|
||||||
|
// 统计图片和视频数量
|
||||||
|
for (WallpaperMedia media : mediaList) {
|
||||||
|
if (media.isVideo()) {
|
||||||
|
totalVideos[0]++;
|
||||||
|
} else {
|
||||||
|
totalImages[0]++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 所有文件夹扫描完成
|
||||||
|
if (completedCount[0] == totalFolders) {
|
||||||
|
if (callback != null) {
|
||||||
|
callback.onAllComplete(totalImages[0], totalVideos[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onScanError(String folderPath, String error) {
|
||||||
|
synchronized (completedCount) {
|
||||||
|
completedCount[0]++;
|
||||||
|
|
||||||
|
// 即使出错也要检查是否所有任务完成
|
||||||
|
if (completedCount[0] == totalFolders) {
|
||||||
|
if (callback != null) {
|
||||||
|
callback.onAllComplete(totalImages[0], totalVideos[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消指定的扫描任务
|
||||||
|
* @param taskId 任务 ID(文件夹路径)
|
||||||
|
*/
|
||||||
|
public void cancelTask(String taskId) {
|
||||||
|
synchronized (runningTasks) {
|
||||||
|
Future<?> future = runningTasks.get(taskId);
|
||||||
|
if (future != null && !future.isDone()) {
|
||||||
|
future.cancel(true);
|
||||||
|
runningTasks.remove(taskId);
|
||||||
|
Log.i(TAG, "Cancelled task: " + taskId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消所有正在执行的任务
|
||||||
|
*/
|
||||||
|
public void cancelAllTasks() {
|
||||||
|
synchronized (runningTasks) {
|
||||||
|
for (Map.Entry<String, Future<?>> entry : runningTasks.entrySet()) {
|
||||||
|
Future<?> future = entry.getValue();
|
||||||
|
if (future != null && !future.isDone()) {
|
||||||
|
future.cancel(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runningTasks.clear();
|
||||||
|
Log.i(TAG, "Cancelled all tasks");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取缓存的扫描结果(同步,不触发扫描)
|
||||||
|
* @param folderPath 文件夹路径
|
||||||
|
* @return 缓存的媒体列表,如果没有缓存则返回 null
|
||||||
|
*/
|
||||||
|
public List<WallpaperMedia> getCachedResult(String folderPath) {
|
||||||
|
return mediaScanner.scanFolder(folderPath); // MediaScanner 内部有缓存机制
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除指定文件夹的缓存
|
||||||
|
* @param folderPath 文件夹路径
|
||||||
|
*/
|
||||||
|
public void clearCache(String folderPath) {
|
||||||
|
mediaScanner.clearCache(folderPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除所有缓存
|
||||||
|
*/
|
||||||
|
public void clearAllCache() {
|
||||||
|
mediaScanner.clearAllCache();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭管理器,释放资源
|
||||||
|
*/
|
||||||
|
public void shutdown() {
|
||||||
|
cancelAllTasks();
|
||||||
|
executorService.shutdown();
|
||||||
|
mediaScanner.shutdown();
|
||||||
|
Log.i(TAG, "ScanTaskManager shutdown");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫描回调接口
|
||||||
|
*/
|
||||||
|
public interface ScanCallback {
|
||||||
|
void onScanComplete(String folderPath, List<WallpaperMedia> mediaList);
|
||||||
|
void onScanError(String folderPath, String error);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多文件夹扫描回调接口
|
||||||
|
*/
|
||||||
|
public interface MultiFolderScanCallback {
|
||||||
|
void onAllComplete(int totalImages, int totalVideos);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -669,6 +669,9 @@ public class AutoWallpaperService extends WallpaperService {
|
|||||||
fileLogger.log(TAG, scanResult);
|
fileLogger.log(TAG, scanResult);
|
||||||
allMedia.addAll(folderMedia);
|
allMedia.addAll(folderMedia);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 更新当前相册的最近扫描时间
|
||||||
|
updateAlbumLastScanTime(config.getAlbumId());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 添加直接选择的图片 URI
|
// 2. 添加直接选择的图片 URI
|
||||||
@@ -822,6 +825,31 @@ public class AutoWallpaperService extends WallpaperService {
|
|||||||
/**
|
/**
|
||||||
* 从媒体 URI 中提取显示名称
|
* 从媒体 URI 中提取显示名称
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* 更新相册的最近扫描时间
|
||||||
|
*/
|
||||||
|
private void updateAlbumLastScanTime(String albumId) {
|
||||||
|
if (albumId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
AlbumPreferences albumPrefs = new AlbumPreferences(AutoWallpaperService.this);
|
||||||
|
Album album = albumPrefs.findAlbumById(albumId);
|
||||||
|
if (album != null) {
|
||||||
|
album.setLastScanTime(System.currentTimeMillis());
|
||||||
|
albumPrefs.updateAlbum(album);
|
||||||
|
String msg = "Updated last scan time for album: " + album.getName();
|
||||||
|
Log.i(TAG, msg);
|
||||||
|
fileLogger.log(TAG, msg);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
String errorMsg = "Error updating album last scan time: " + e.getMessage();
|
||||||
|
Log.e(TAG, errorMsg, e);
|
||||||
|
fileLogger.log(TAG, errorMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private String extractDisplayName(String uriString) {
|
private String extractDisplayName(String uriString) {
|
||||||
try {
|
try {
|
||||||
android.net.Uri uri = android.net.Uri.parse(uriString);
|
android.net.Uri uri = android.net.Uri.parse(uriString);
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ public class WallpaperPreferences {
|
|||||||
private static final String KEY_DOUBLE_TAP_ENABLED = "double_tap_enabled";
|
private static final String KEY_DOUBLE_TAP_ENABLED = "double_tap_enabled";
|
||||||
private static final String KEY_FIXED_WALLPAPER_URI = "fixed_wallpaper_uri";
|
private static final String KEY_FIXED_WALLPAPER_URI = "fixed_wallpaper_uri";
|
||||||
private static final String KEY_FIXED_WALLPAPER_ENABLED = "fixed_wallpaper_enabled";
|
private static final String KEY_FIXED_WALLPAPER_ENABLED = "fixed_wallpaper_enabled";
|
||||||
|
private static final String KEY_AUTO_SCAN_INTERVAL_HOURS = "auto_scan_interval_hours";
|
||||||
|
|
||||||
private final SharedPreferences prefs;
|
private final SharedPreferences prefs;
|
||||||
private final Gson gson;
|
private final Gson gson;
|
||||||
@@ -131,6 +132,9 @@ public class WallpaperPreferences {
|
|||||||
config.setFixedWallpaperUri(prefs.getString(KEY_FIXED_WALLPAPER_URI, null));
|
config.setFixedWallpaperUri(prefs.getString(KEY_FIXED_WALLPAPER_URI, null));
|
||||||
config.setFixedWallpaperEnabled(prefs.getBoolean(KEY_FIXED_WALLPAPER_ENABLED, false));
|
config.setFixedWallpaperEnabled(prefs.getBoolean(KEY_FIXED_WALLPAPER_ENABLED, false));
|
||||||
|
|
||||||
|
// Auto scan settings
|
||||||
|
config.setAutoScanIntervalHours(prefs.getInt(KEY_AUTO_SCAN_INTERVAL_HOURS, 0));
|
||||||
|
|
||||||
// 添加日志:记录从相册加载的图片和视频数量
|
// 添加日志:记录从相册加载的图片和视频数量
|
||||||
android.util.Log.i("WallpaperPreferences", "loadConfig: album=" + album.getName() +
|
android.util.Log.i("WallpaperPreferences", "loadConfig: album=" + album.getName() +
|
||||||
", folders=" + album.getFolders().size() +
|
", folders=" + album.getFolders().size() +
|
||||||
@@ -160,6 +164,9 @@ public class WallpaperPreferences {
|
|||||||
config.setFixedWallpaperUri(null);
|
config.setFixedWallpaperUri(null);
|
||||||
config.setFixedWallpaperEnabled(false);
|
config.setFixedWallpaperEnabled(false);
|
||||||
|
|
||||||
|
// Default auto scan settings
|
||||||
|
config.setAutoScanIntervalHours(0);
|
||||||
|
|
||||||
android.util.Log.w("WallpaperPreferences", "loadConfig: No active album found");
|
android.util.Log.w("WallpaperPreferences", "loadConfig: No active album found");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,6 +213,7 @@ public class WallpaperPreferences {
|
|||||||
.putBoolean(KEY_DOUBLE_TAP_ENABLED, config.isDoubleTapEnabled())
|
.putBoolean(KEY_DOUBLE_TAP_ENABLED, config.isDoubleTapEnabled())
|
||||||
.putString(KEY_FIXED_WALLPAPER_URI, config.getFixedWallpaperUri())
|
.putString(KEY_FIXED_WALLPAPER_URI, config.getFixedWallpaperUri())
|
||||||
.putBoolean(KEY_FIXED_WALLPAPER_ENABLED, config.isFixedWallpaperEnabled())
|
.putBoolean(KEY_FIXED_WALLPAPER_ENABLED, config.isFixedWallpaperEnabled())
|
||||||
|
.putInt(KEY_AUTO_SCAN_INTERVAL_HOURS, config.getAutoScanIntervalHours())
|
||||||
.apply();
|
.apply();
|
||||||
}
|
}
|
||||||
public void saveLastUri(String uri) {
|
public void saveLastUri(String uri) {
|
||||||
|
|||||||
@@ -354,6 +354,126 @@
|
|||||||
|
|
||||||
</com.google.android.material.card.MaterialCardView>
|
</com.google.android.material.card.MaterialCardView>
|
||||||
|
|
||||||
|
<!-- 自动扫描设置卡片 -->
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tvAutoScanLabel"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="@dimen/spacing_lg"
|
||||||
|
android:text="自动扫描"
|
||||||
|
android:textSize="@dimen/text_size_xxl"
|
||||||
|
android:textStyle="bold"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
app:layout_constraintTop_toBottomOf="@id/cardFixedWallpaper"
|
||||||
|
app:layout_constraintStart_toStartOf="parent" />
|
||||||
|
|
||||||
|
<com.google.android.material.card.MaterialCardView
|
||||||
|
android:id="@+id/cardAutoScan"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="@dimen/spacing_sm"
|
||||||
|
android:layout_marginBottom="@dimen/spacing_lg"
|
||||||
|
app:cardElevation="@dimen/card_elevation"
|
||||||
|
app:cardCornerRadius="@dimen/corner_radius_md"
|
||||||
|
app:cardBackgroundColor="@color/bg_card"
|
||||||
|
app:strokeColor="@color/glass_border"
|
||||||
|
app:strokeWidth="@dimen/glass_border_width"
|
||||||
|
app:layout_constraintTop_toBottomOf="@id/tvAutoScanLabel"
|
||||||
|
app:layout_constraintStart_toStartOf="parent"
|
||||||
|
app:layout_constraintEnd_toEndOf="parent">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:padding="@dimen/card_padding">
|
||||||
|
|
||||||
|
<!-- 自动扫描间隔选择 -->
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="自动扫描间隔"
|
||||||
|
android:textSize="@dimen/text_size_md"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textStyle="bold" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="@dimen/spacing_xs"
|
||||||
|
android:text="定期清除缓存并重新扫描相册文件夹,确保显示最新内容"
|
||||||
|
android:textSize="@dimen/text_size_sm"
|
||||||
|
android:textColor="@color/text_secondary"
|
||||||
|
android:lineSpacingExtra="4dp" />
|
||||||
|
|
||||||
|
<RadioGroup
|
||||||
|
android:id="@+id/radioGroupAutoScan"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="@dimen/spacing_md"
|
||||||
|
android:orientation="vertical">
|
||||||
|
|
||||||
|
<RadioButton
|
||||||
|
android:id="@+id/radioAutoScanDisabled"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="禁用(手动刷新)"
|
||||||
|
android:textSize="@dimen/text_size_md"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:minHeight="48dp" />
|
||||||
|
|
||||||
|
<RadioButton
|
||||||
|
android:id="@+id/radioAutoScan1Hour"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="每 1 小时"
|
||||||
|
android:textSize="@dimen/text_size_md"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:minHeight="48dp" />
|
||||||
|
|
||||||
|
<RadioButton
|
||||||
|
android:id="@+id/radioAutoScan6Hours"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="每 6 小时"
|
||||||
|
android:textSize="@dimen/text_size_md"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:minHeight="48dp" />
|
||||||
|
|
||||||
|
<RadioButton
|
||||||
|
android:id="@+id/radioAutoScan12Hours"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="每 12 小时"
|
||||||
|
android:textSize="@dimen/text_size_md"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:minHeight="48dp" />
|
||||||
|
|
||||||
|
<RadioButton
|
||||||
|
android:id="@+id/radioAutoScan24Hours"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="每 24 小时(推荐)"
|
||||||
|
android:textSize="@dimen/text_size_md"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:minHeight="48dp" />
|
||||||
|
|
||||||
|
</RadioGroup>
|
||||||
|
|
||||||
|
<!-- 提示信息 -->
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="@dimen/spacing_md"
|
||||||
|
android:text="注意:自动扫描会在后台定时运行,可能会消耗少量电量。建议选择较长的间隔时间。"
|
||||||
|
android:textSize="@dimen/text_size_sm"
|
||||||
|
android:textColor="@color/text_hint"
|
||||||
|
android:lineSpacingExtra="4dp" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
</com.google.android.material.card.MaterialCardView>
|
||||||
|
|
||||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||||
|
|
||||||
</androidx.core.widget.NestedScrollView>
|
</androidx.core.widget.NestedScrollView>
|
||||||
@@ -129,6 +129,18 @@
|
|||||||
android:drawablePadding="4dp"
|
android:drawablePadding="4dp"
|
||||||
android:drawableTint="@color/text_hint_modern" />
|
android:drawableTint="@color/text_hint_modern" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tvLastScanTime"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="未扫描"
|
||||||
|
android:textSize="@dimen/text_size_xs"
|
||||||
|
android:textColor="@color/text_hint_modern"
|
||||||
|
android:layout_marginStart="@dimen/spacing_md"
|
||||||
|
android:drawableStart="@drawable/ic_refresh"
|
||||||
|
android:drawablePadding="4dp"
|
||||||
|
android:drawableTint="@color/text_hint_modern" />
|
||||||
|
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|
||||||
<!-- Action Buttons -->
|
<!-- Action Buttons -->
|
||||||
|
|||||||
Reference in new issue
Block a user