diff --git a/CLAUDE.md b/CLAUDE.md
index 893b0e4..2ae8bcb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -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/ # 工具类
│ ├── AlarmScheduler.java # 定时任务调度
│ ├── MediaScanner.java # 媒体扫描器
+│ ├── ScanTaskManager.java # 扫描任务管理器(线程池)
│ ├── ThumbnailHelper.java # 缩略图工具
│ ├── WallpaperServiceHelper.java # 服务状态检测
│ ├── BackgroundHelper.java # 背景图片辅助
@@ -92,7 +96,8 @@ cn.hugh.bz.gk2/
│ ├── JsonHelper.java
│ └── WallpaperGlideModule.java
├── receiver/ # 广播接收器
-│ └── WallpaperChangeReceiver.java # 壁纸更换接收器
+│ ├── WallpaperChangeReceiver.java # 壁纸更换接收器
+│ └── CacheScanReceiver.java # 缓存扫描接收器
└── bridge/ # 桥接层(预留)
└── modules/
```
@@ -115,6 +120,7 @@ cn.hugh.bz.gk2/
3. **返回桌面更换**(`changeOnReturn`):壁纸可见时自动更换
4. **双击切换**:在桌面双击触发快速切换(可在设置中开关)
5. **视频播放完成**(`videoCompleted`):视频壁纸播放完成后自动切换到下一个媒体
+6. **四指点击**:四指或更多手指点击桌面,显示通知打开固定壁纸并禁用 app
**关键状态标志**:
- `forceChangeNext`:用户强制更换标志
@@ -132,6 +138,7 @@ cn.hugh.bz.gk2/
- 每个相册有独立的文件夹列表、播放模式、更换间隔等配置
- 支持默认相册(ID 为 "default",不可删除)
- 通过 `AlbumPreferences` 持久化到 SharedPreferences(JSON 格式)
+- 记录最近扫描时间(`lastScanTime`),用于显示数据新鲜度
**激活机制**:
- 同一时间只有一个相册处于激活状态
@@ -198,7 +205,100 @@ onCompletion() 回调 → 触发 AutoWallpaperService 切换下一个壁纸
- Fragment 通过 `MainActivity` 的回调接口启动文件夹/图片选择器
- 使用 `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 及以下)
@@ -417,6 +517,93 @@ adb shell tail -f /sdcard/Android/data/cn.hugh.bz.gk2/files/wallpaper_log.txt
- 在 `SettingsFragment` 中添加开关控件
- 在 `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` 枚举中添加新模式
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index a6e7758..05b6462 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -58,6 +58,16 @@
+
+
+
+
+
+
+
imageUris; // 图片URI列表(与 folders 同级)
private List videoUris; // 视频URI列表(与 imageUris 同级)
+ private long lastScanTime; // 最近扫描时间
public Album() {
this.id = UUID.randomUUID().toString();
@@ -36,6 +37,7 @@ public class Album implements Serializable {
this.enabled = true;
this.imageUris = new ArrayList<>();
this.videoUris = new ArrayList<>();
+ this.lastScanTime = 0;
}
// Getters and Setters
@@ -135,6 +137,14 @@ public class Album implements Serializable {
this.videoUris = videoUris;
}
+ public long getLastScanTime() {
+ return lastScanTime;
+ }
+
+ public void setLastScanTime(long lastScanTime) {
+ this.lastScanTime = lastScanTime;
+ }
+
/**
* 判断是否为默认相册
*/
diff --git a/app/src/main/java/cn/hugh/bz/gk2/model/AppConfig.java b/app/src/main/java/cn/hugh/bz/gk2/model/AppConfig.java
index 227ec38..d0c2f69 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/model/AppConfig.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/model/AppConfig.java
@@ -18,6 +18,7 @@ public class AppConfig {
private boolean doubleTapEnabled;
private String fixedWallpaperUri;
private boolean isFixedWallpaperEnabled;
+ private int autoScanIntervalHours; // 自动扫描间隔(小时),0 表示禁用
public AppConfig() {
this.selectedFolders = new java.util.ArrayList<>();
@@ -31,6 +32,7 @@ public class AppConfig {
this.videoPauseOnBattery = true;
this.doubleTapEnabled = true;
this.isFixedWallpaperEnabled = false;
+ this.autoScanIntervalHours = 0; // 默认禁用自动扫描
}
// Getters and Setters
@@ -79,6 +81,9 @@ public class AppConfig {
public boolean isFixedWallpaperEnabled() { return isFixedWallpaperEnabled; }
public void setFixedWallpaperEnabled(boolean isFixedWallpaperEnabled) { this.isFixedWallpaperEnabled = isFixedWallpaperEnabled; }
+ public int getAutoScanIntervalHours() { return autoScanIntervalHours; }
+ public void setAutoScanIntervalHours(int autoScanIntervalHours) { this.autoScanIntervalHours = autoScanIntervalHours; }
+
/**
* 检查是否有可用的媒体源(文件夹、图片或视频)
*/
diff --git a/app/src/main/java/cn/hugh/bz/gk2/receiver/CacheScanReceiver.java b/app/src/main/java/cn/hugh/bz/gk2/receiver/CacheScanReceiver.java
new file mode 100644
index 0000000..cfeda52
--- /dev/null
+++ b/app/src/main/java/cn/hugh/bz/gk2/receiver/CacheScanReceiver.java
@@ -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 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 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);
+ }
+}
diff --git a/app/src/main/java/cn/hugh/bz/gk2/ui/AlbumEditorActivity.java b/app/src/main/java/cn/hugh/bz/gk2/ui/AlbumEditorActivity.java
index 5a20f7f..b76f75a 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/ui/AlbumEditorActivity.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/ui/AlbumEditorActivity.java
@@ -42,6 +42,7 @@ import cn.hugh.bz.gk2.model.MediaType;
import cn.hugh.bz.gk2.model.PlayMode;
import cn.hugh.bz.gk2.model.WallpaperMedia;
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.wallpaper.AlbumPreferences;
@@ -83,6 +84,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
private MediaScanner mediaScanner;
private ProgressDialog progressDialog;
private Handler mainHandler;
+ private ScanTaskManager scanTaskManager;
// 文件夹图片数量缓存
private final java.util.Map folderImageCountCache = new java.util.HashMap<>();
@@ -101,6 +103,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
// 初始化扫描器和 Handler
mediaScanner = new MediaScanner(this);
mainHandler = new Handler(Looper.getMainLooper());
+ scanTaskManager = ScanTaskManager.getInstance(this);
initFolderPickerLauncher();
initImagePickerLauncher();
@@ -112,6 +115,10 @@ public class AlbumEditorActivity extends AppCompatActivity {
@Override
protected void onDestroy() {
super.onDestroy();
+ // 取消所有扫描任务
+ if (scanTaskManager != null) {
+ scanTaskManager.cancelAllTasks();
+ }
// 关闭扫描器
if (mediaScanner != null) {
mediaScanner.shutdown();
@@ -358,7 +365,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
// 文件夹列表
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);
// 媒体列表(图片和视频)
@@ -491,28 +498,38 @@ public class AlbumEditorActivity extends AppCompatActivity {
/**
* 预加载所有文件夹的图片数量(编辑现有相册时)
- * 在后台线程中并行扫描所有文件夹
+ * 使用 ScanTaskManager 管理扫描任务
*/
private void preloadFolderImageCounts() {
if (folders.isEmpty()) {
return;
}
- new Thread(() -> {
- MediaScanner scanner = new MediaScanner(this);
- for (String folderUri : folders) {
- // 检查是否已有缓存
- if (!folderImageCountCache.containsKey(folderUri)) {
- // 扫描文件夹
- List mediaList = scanner.scanFolder(folderUri);
- int count = mediaList != null ? mediaList.size() : 0;
+ // 使用 ScanTaskManager 异步扫描所有文件夹
+ for (String folderUri : folders) {
+ // 检查是否已有缓存
+ if (!folderImageCountCache.containsKey(folderUri)) {
+ scanTaskManager.scanFolderAsync(folderUri, new ScanTaskManager.ScanCallback() {
+ @Override
+ public void onScanComplete(String folderPath, List mediaList) {
+ int count = mediaList != null ? mediaList.size() : 0;
+ // 缓存结果
+ folderImageCountCache.put(folderUri, count);
+ // 通知适配器更新(如果需要)
+ mainHandler.post(() -> {
+ if (folderAdapter != null) {
+ folderAdapter.notifyDataSetChanged();
+ }
+ });
+ }
- // 缓存结果
- folderImageCountCache.put(folderUri, count);
- }
+ @Override
+ public void onScanError(String folderPath, String error) {
+ android.util.Log.e("AlbumEditorActivity", "Error scanning folder: " + error);
+ }
+ });
}
- scanner.shutdown();
- }).start();
+ }
}
private void openFolderPicker() {
@@ -644,14 +661,17 @@ public class AlbumEditorActivity extends AppCompatActivity {
private List folders;
private final OnFolderRemoveListener removeListener;
private final java.util.Map imageCountCache;
+ private final ScanTaskManager scanTaskManager;
public FolderAdapter(android.content.Context context, List folders,
OnFolderRemoveListener removeListener,
- java.util.Map imageCountCache) {
+ java.util.Map imageCountCache,
+ ScanTaskManager scanTaskManager) {
this.context = context;
this.folders = folders != null ? folders : new ArrayList<>();
this.removeListener = removeListener;
this.imageCountCache = imageCountCache != null ? imageCountCache : new java.util.HashMap<>();
+ this.scanTaskManager = scanTaskManager;
}
public void updateFolders(List folders) {
@@ -721,21 +741,29 @@ public class AlbumEditorActivity extends AppCompatActivity {
// 首次显示,标记为待扫描
tvImageCount.setText("扫描中...");
- // 异步扫描(只扫描一次)
- new Thread(() -> {
- MediaScanner scanner = new MediaScanner(context);
- List mediaList = scanner.scanFolder(folderUri);
- int count = mediaList != null ? mediaList.size() : 0;
+ // 使用 ScanTaskManager 异步扫描
+ scanTaskManager.scanFolderAsync(folderUri, new ScanTaskManager.ScanCallback() {
+ @Override
+ public void onScanComplete(String folderPath, List mediaList) {
+ int count = mediaList != null ? mediaList.size() : 0;
- // 更新缓存
- imageCountCache.put(folderUri, count);
- scanner.shutdown();
+ // 更新缓存
+ imageCountCache.put(folderUri, count);
- // 更新 UI
- tvImageCount.post(() -> {
- tvImageCount.setText(count + " 个文件");
- });
- }).start();
+ // 更新 UI(在主线程)
+ tvImageCount.post(() -> {
+ tvImageCount.setText(count + " 个文件");
+ });
+ }
+
+ @Override
+ public void onScanError(String folderPath, String error) {
+ // 更新 UI 显示错误
+ tvImageCount.post(() -> {
+ tvImageCount.setText("扫描失败");
+ });
+ }
+ });
}
}
diff --git a/app/src/main/java/cn/hugh/bz/gk2/ui/AlbumManagementFragment.java b/app/src/main/java/cn/hugh/bz/gk2/ui/AlbumManagementFragment.java
index 47882be..ee179c9 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/ui/AlbumManagementFragment.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/ui/AlbumManagementFragment.java
@@ -27,6 +27,7 @@ import cn.hugh.bz.gk2.model.PlayMode;
import cn.hugh.bz.gk2.model.WallpaperMedia;
import cn.hugh.bz.gk2.utils.BackgroundHelper;
import cn.hugh.bz.gk2.utils.MediaScanner;
+import cn.hugh.bz.gk2.utils.ScanTaskManager;
import cn.hugh.bz.gk2.wallpaper.AlbumPreferences;
/**
@@ -42,6 +43,7 @@ public class AlbumManagementFragment extends Fragment {
private AlbumPreferences albumPrefs;
private AlbumAdapter adapter;
private List albums;
+ private ScanTaskManager scanTaskManager;
// 目标相册ID(用于从历史页面跳转)
public static String targetAlbumId = null;
@@ -50,6 +52,7 @@ public class AlbumManagementFragment extends Fragment {
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
albumPrefs = new AlbumPreferences(requireContext());
+ scanTaskManager = ScanTaskManager.getInstance(requireContext());
}
@Nullable
@@ -91,7 +94,7 @@ public class AlbumManagementFragment extends Fragment {
public void onDelete(Album album) {
deleteAlbum(album);
}
- });
+ }, scanTaskManager);
rvAlbums.setAdapter(adapter);
// 创建相册按钮
@@ -218,6 +221,15 @@ public class AlbumManagementFragment extends Fragment {
targetAlbumId = null;
}
+ @Override
+ public void onDestroyView() {
+ super.onDestroyView();
+ // 取消所有正在执行的扫描任务
+ if (scanTaskManager != null) {
+ scanTaskManager.cancelAllTasks();
+ }
+ }
+
/**
* 相册列表适配器
*/
@@ -227,12 +239,14 @@ public class AlbumManagementFragment extends Fragment {
private List albums;
private final AlbumCallback callback;
private final AlbumPreferences prefs;
+ private final ScanTaskManager scanTaskManager;
- public AlbumAdapter(Context context, List albums, AlbumCallback callback) {
+ public AlbumAdapter(Context context, List albums, AlbumCallback callback, ScanTaskManager scanTaskManager) {
this.context = context;
this.albums = albums != null ? albums : new ArrayList<>();
this.callback = callback;
this.prefs = new AlbumPreferences(context);
+ this.scanTaskManager = scanTaskManager;
}
public void updateAlbums(List albums) {
@@ -264,6 +278,7 @@ public class AlbumManagementFragment extends Fragment {
private final TextView tvAlbumInfo;
private final TextView tvPlayMode;
private final TextView tvInterval;
+ private final TextView tvLastScanTime;
private final MaterialButton btnEdit;
private final MaterialButton btnSwitch;
private final MaterialButton btnDelete;
@@ -275,6 +290,7 @@ public class AlbumManagementFragment extends Fragment {
tvAlbumInfo = itemView.findViewById(R.id.tvAlbumInfo);
tvPlayMode = itemView.findViewById(R.id.tvPlayMode);
tvInterval = itemView.findViewById(R.id.tvInterval);
+ tvLastScanTime = itemView.findViewById(R.id.tvLastScanTime);
btnEdit = itemView.findViewById(R.id.btnEdit);
btnSwitch = itemView.findViewById(R.id.btnSwitch);
btnDelete = itemView.findViewById(R.id.btnDelete);
@@ -304,27 +320,32 @@ public class AlbumManagementFragment extends Fragment {
// 异步计算文件夹中的媒体数量并显示更详细的信息
if (folderCount > 0) {
- new Thread(() -> {
- MediaScanner scanner = new MediaScanner(context);
- int totalImages = directImageCount;
- int totalVideos = directVideoCount;
-
- for (String folder : album.getFolders()) {
- List mediaList = scanner.scanFolder(folder);
- for (WallpaperMedia m : mediaList) {
- if (m.isVideo()) totalVideos++;
- else totalImages++;
+ // 先显示缓存的扫描时间
+ updateLastScanTime(album);
+
+ // 使用 ScanTaskManager 异步扫描
+ scanTaskManager.scanFoldersAsync(album.getFolders(), new ScanTaskManager.MultiFolderScanCallback() {
+ @Override
+ public void onAllComplete(int totalImages, int totalVideos) {
+ // 加上直接添加的图片和视频
+ int finalImages = totalImages + directImageCount;
+ 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() + " 分钟");
+ // 最近扫描时间
+ updateLastScanTime(album);
+
// 默认相册不显示删除按钮
if (album.isDefault()) {
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 {
diff --git a/app/src/main/java/cn/hugh/bz/gk2/ui/SettingsFragment.java b/app/src/main/java/cn/hugh/bz/gk2/ui/SettingsFragment.java
index a82d2aa..ff99f2f 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/ui/SettingsFragment.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/ui/SettingsFragment.java
@@ -57,6 +57,14 @@ public class SettingsFragment extends Fragment {
private MaterialButton btnClearFixedWallpaper;
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 pickImageLauncher;
private ActivityResultLauncher pickFixedWallpaperLauncher;
@@ -82,6 +90,7 @@ public class SettingsFragment extends Fragment {
loadVideoSettings();
loadDoubleTapSettings();
loadFixedWallpaperSettings();
+ loadAutoScanSettings();
}
private void initViews(View view) {
@@ -138,9 +147,18 @@ public class SettingsFragment extends Fragment {
btnClearFixedWallpaper = view.findViewById(R.id.btnClearFixedWallpaper);
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();
setupDoubleTapListener();
setupFixedWallpaperListeners();
+ setupAutoScanListener();
}
private void setupVideoSettingsListeners() {
@@ -416,6 +434,71 @@ public class SettingsFragment extends Fragment {
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
public void onResume() {
super.onResume();
@@ -423,5 +506,6 @@ public class SettingsFragment extends Fragment {
loadVideoSettings();
loadDoubleTapSettings();
loadFixedWallpaperSettings();
+ loadAutoScanSettings();
}
}
diff --git a/app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java b/app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java
index 158ac68..5e2a000 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java
@@ -12,6 +12,7 @@ import cn.hugh.bz.gk2.receiver.WallpaperChangeReceiver;
public class AlarmScheduler {
private static final String TAG = "AlarmScheduler";
private static final int REQUEST_CODE = 1000;
+ private static final int CACHE_SCAN_REQUEST_CODE = 1001;
private final Context context;
private final AlarmManager alarmManager;
@@ -134,4 +135,115 @@ public class AlarmScheduler {
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);
+ }
+ }
}
diff --git a/app/src/main/java/cn/hugh/bz/gk2/utils/JsonHelper.java b/app/src/main/java/cn/hugh/bz/gk2/utils/JsonHelper.java
index b725c86..566dcd0 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/utils/JsonHelper.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/utils/JsonHelper.java
@@ -85,6 +85,43 @@ public class JsonHelper {
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 {
String folderPath;
String folderName;
diff --git a/app/src/main/java/cn/hugh/bz/gk2/utils/MediaScanner.java b/app/src/main/java/cn/hugh/bz/gk2/utils/MediaScanner.java
index 58c45c8..4d36cd1 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/utils/MediaScanner.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/utils/MediaScanner.java
@@ -656,4 +656,42 @@ public class MediaScanner {
return "LRU Cache: " + memoryCache.size() + " entries, " +
"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 rescanFolder(String folderPath) {
+ clearCache(folderPath);
+ return scanFolder(folderPath);
+ }
}
\ No newline at end of file
diff --git a/app/src/main/java/cn/hugh/bz/gk2/utils/ScanTaskManager.java b/app/src/main/java/cn/hugh/bz/gk2/utils/ScanTaskManager.java
new file mode 100644
index 0000000..339fbb2
--- /dev/null
+++ b/app/src/main/java/cn/hugh/bz/gk2/utils/ScanTaskManager.java
@@ -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> 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 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 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 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> 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 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 mediaList);
+ void onScanError(String folderPath, String error);
+ }
+
+ /**
+ * 多文件夹扫描回调接口
+ */
+ public interface MultiFolderScanCallback {
+ void onAllComplete(int totalImages, int totalVideos);
+ }
+}
diff --git a/app/src/main/java/cn/hugh/bz/gk2/wallpaper/AutoWallpaperService.java b/app/src/main/java/cn/hugh/bz/gk2/wallpaper/AutoWallpaperService.java
index 9c8075f..4009641 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/wallpaper/AutoWallpaperService.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/wallpaper/AutoWallpaperService.java
@@ -669,6 +669,9 @@ public class AutoWallpaperService extends WallpaperService {
fileLogger.log(TAG, scanResult);
allMedia.addAll(folderMedia);
}
+
+ // 更新当前相册的最近扫描时间
+ updateAlbumLastScanTime(config.getAlbumId());
}
// 2. 添加直接选择的图片 URI
@@ -822,6 +825,31 @@ public class AutoWallpaperService extends WallpaperService {
/**
* 从媒体 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) {
try {
android.net.Uri uri = android.net.Uri.parse(uriString);
diff --git a/app/src/main/java/cn/hugh/bz/gk2/wallpaper/WallpaperPreferences.java b/app/src/main/java/cn/hugh/bz/gk2/wallpaper/WallpaperPreferences.java
index cf99258..8c07157 100644
--- a/app/src/main/java/cn/hugh/bz/gk2/wallpaper/WallpaperPreferences.java
+++ b/app/src/main/java/cn/hugh/bz/gk2/wallpaper/WallpaperPreferences.java
@@ -23,6 +23,7 @@ public class WallpaperPreferences {
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_ENABLED = "fixed_wallpaper_enabled";
+ private static final String KEY_AUTO_SCAN_INTERVAL_HOURS = "auto_scan_interval_hours";
private final SharedPreferences prefs;
private final Gson gson;
@@ -131,6 +132,9 @@ public class WallpaperPreferences {
config.setFixedWallpaperUri(prefs.getString(KEY_FIXED_WALLPAPER_URI, null));
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() +
", folders=" + album.getFolders().size() +
@@ -160,6 +164,9 @@ public class WallpaperPreferences {
config.setFixedWallpaperUri(null);
config.setFixedWallpaperEnabled(false);
+ // Default auto scan settings
+ config.setAutoScanIntervalHours(0);
+
android.util.Log.w("WallpaperPreferences", "loadConfig: No active album found");
}
@@ -206,6 +213,7 @@ public class WallpaperPreferences {
.putBoolean(KEY_DOUBLE_TAP_ENABLED, config.isDoubleTapEnabled())
.putString(KEY_FIXED_WALLPAPER_URI, config.getFixedWallpaperUri())
.putBoolean(KEY_FIXED_WALLPAPER_ENABLED, config.isFixedWallpaperEnabled())
+ .putInt(KEY_AUTO_SCAN_INTERVAL_HOURS, config.getAutoScanIntervalHours())
.apply();
}
public void saveLastUri(String uri) {
diff --git a/app/src/main/res/layout/fragment_settings.xml b/app/src/main/res/layout/fragment_settings.xml
index 1abcd8f..dbbcd5e 100644
--- a/app/src/main/res/layout/fragment_settings.xml
+++ b/app/src/main/res/layout/fragment_settings.xml
@@ -354,6 +354,126 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/item_album_card.xml b/app/src/main/res/layout/item_album_card.xml
index f56ecf8..475db2f 100644
--- a/app/src/main/res/layout/item_album_card.xml
+++ b/app/src/main/res/layout/item_album_card.xml
@@ -129,6 +129,18 @@
android:drawablePadding="4dp"
android:drawableTint="@color/text_hint_modern" />
+
+