diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..427a8a5 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,12 @@ +{ + "permissions": { + "allow": [ + "WebSearch", + "Skill(superpowers:writing-plans)", + "Skill(superpowers:subagent-driven-development)", + "Bash(git init:*)", + "Bash(git add:*)", + "Bash(git commit:*)" + ] + } +} diff --git a/docs/plans/2025-01-20-auto-wallpaper-mvp.md b/docs/plans/2025-01-20-auto-wallpaper-mvp.md new file mode 100644 index 0000000..79303d6 --- /dev/null +++ b/docs/plans/2025-01-20-auto-wallpaper-mvp.md @@ -0,0 +1,2069 @@ +# 自动壁纸更换应用 MVP 实施计划 + +> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. + +**目标:** 构建一个自动壁纸更换 Android 应用,支持选择文件夹、顺序/随机模式、可配置更换间隔(最小1分钟),兼容鸿蒙 4.2 系统。 + +**架构:** 基于 `WallpaperService` 的 Live Wallpaper 实现,使用 `AlarmManager` 定时触发 Canvas 重绘,`SharedPreferences` + JSON 存储配置和图片索引。 + +**技术栈:** +- Java (不是 Kotlin) +- Android SDK (target API 31, 最低 API 24) +- Gradle 构建系统 +- IntelliJ IDEA +- Glide 图片加载库(或 BitmapFactory) +- SharedPreferences + JSON 文件存储 + +**应用信息:** +- 应用名:bzForGk2 +- 包名:cn.hugh.bz.gk2 + +--- + +## MVP 功能范围 + +### 第一阶段 MVP(本计划): +1. ✅ WallpaperService 核心框架 +2. ✅ 文件夹选择和图片扫描 +3. ✅ 顺序播放模式 +4. ✅ 随机播放模式 +5. ✅ AlarmManager 定时任务(1分钟间隔) +6. ✅ SharedPreferences 配置存储 +7. ✅ 设置页面 UI +8. ✅ 间隔时间选择(1-60分钟) +9. ✅ 播放模式切换 + +### 第二阶段(未来): +- 增量扫描优化 +- 图片元数据缓存 +- 播放历史记录 +- 主题和深色模式 + +--- + +## 项目结构 + +``` +bzForGk2/ +├── app/ +│ ├── src/ +│ │ ├── main/ +│ │ │ ├── java/cn/hugh/bz/gk2/ +│ │ │ │ ├── BzForGk2Application.java +│ │ │ │ ├── wallpaper/ +│ │ │ │ │ ├── AutoWallpaperService.java +│ │ │ │ │ ├── WallpaperEngine.java +│ │ │ │ │ ├── ImageLoader.java +│ │ │ │ │ └── WallpaperPreferences.java +│ │ │ │ ├── provider/ +│ │ │ │ │ └── FileProvider.java +│ │ │ │ ├── ui/ +│ │ │ │ │ ├── MainActivity.java +│ │ │ │ │ ├── SettingsActivity.java +│ │ │ │ │ ├── FolderPickerFragment.java +│ │ │ │ │ └── adapters/ +│ │ │ │ │ └── FolderAdapter.java +│ │ │ │ ├── model/ +│ │ │ │ │ ├── WallpaperImage.java +│ │ │ │ │ ├── PlayMode.java +│ │ │ │ │ └── AppConfig.java +│ │ │ │ ├── receiver/ +│ │ │ │ │ └── WallpaperChangeReceiver.java +│ │ │ │ └── utils/ +│ │ │ │ ├── ImageScanner.java +│ │ │ │ ├── AlarmScheduler.java +│ │ │ │ └── JsonHelper.java +│ │ │ ├── res/ +│ │ │ │ ├── layout/ +│ │ │ │ │ ├── activity_main.xml +│ │ │ │ │ ├── activity_settings.xml +│ │ │ │ │ ├── fragment_folder_picker.xml +│ │ │ │ │ ├── item_folder.xml +│ │ │ │ │ └── wallpaper_preview.xml +│ │ │ │ ├── values/ +│ │ │ │ │ ├── strings.xml +│ │ │ │ │ ├── colors.xml +│ │ │ │ │ └── dimens.xml +│ │ │ │ └── xml/ +│ │ │ │ └── wallpaper_info.xml +│ │ │ └── AndroidManifest.xml +│ │ └── test/java/cn/hugh/bz/gk2/ +│ ├── build.gradle +│ └── proguard-rules.pro +├── gradle/ +│ └── wrapper/ +│ └── gradle-wrapper.properties +├── build.gradle +├── settings.gradle +└── gradlew +``` + +--- + +## Task 1: 初始化 Android 项目结构 + +**目标:** 创建基础的 Android 项目骨架,配置 Gradle 构建文件。 + +**Files:** +- Create: `settings.gradle` +- Create: `build.gradle` +- Create: `app/build.gradle` +- Create: `gradle/wrapper/gradle-wrapper.properties` +- Create: `app/src/main/AndroidManifest.xml` + +### Step 1: 创建根级 settings.gradle + +```gradle +rootProject.name = "bzForGk2" +include ':app' +``` + +**Commit:** +```bash +git add settings.gradle +git commit -m "chore: initialize project settings" +``` + +### Step 2: 创建根级 build.gradle + +```gradle +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.1.0' + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} +``` + +**Commit:** +```bash +git add build.gradle +git commit -m "chore: add root build configuration" +``` + +### Step 3: 创建 app/build.gradle + +```gradle +plugins { + id 'com.android.application' +} + +android { + namespace 'cn.hugh.bz.gk2' + compileSdk 33 + + defaultConfig { + applicationId "cn.hugh.bz.gk2" + minSdk 24 + targetSdk 31 + versionCode 1 + versionName "1.0" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.6.1' + implementation 'com.google.android.material:material:1.9.0' + implementation 'androidx.constraintlayout:constraintlayout:2.1.4' + + // Glide for image loading + implementation 'com.github.bumptech.glide:glide:4.16.0' + annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0' + + // JSON parsing + implementation 'com.google.code.gson:gson:2.10.1' + + // Permissions + implementation 'androidx.core:core:1.12.0' +} +``` + +**Commit:** +```bash +git add app/build.gradle +git commit -m "chore: configure app module with dependencies" +``` + +### Step 4: 创建 AndroidManifest.xml + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +**Commit:** +```bash +git add app/src/main/AndroidManifest.xml +git commit -m "feat: add manifest with permissions and components" +``` + +--- + +## Task 2: 创建数据模型 + +**目标:** 创建应用所需的数据模型类。 + +**Files:** +- Create: `app/src/main/java/cn/hugh/bz/gk2/model/PlayMode.java` +- Create: `app/src/main/java/cn/hugh/bz/gk2/model/WallpaperImage.java` +- Create: `app/src/main/java/cn/hugh/bz/gk2/model/AppConfig.java` + +### Step 1: 创建 PlayMode 枚举 + +```java +package cn.hugh.bz.gk2.model; + +public enum PlayMode { + SEQUENTIAL("顺序播放"), + RANDOM("随机播放"); + + private final String displayName; + + PlayMode(String displayName) { + this.displayName = displayName; + } + + public String getDisplayName() { + return displayName; + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/model/PlayMode.java +git commit -m "feat: add PlayMode enum" +``` + +### Step 2: 创建 WallpaperImage 数据类 + +```java +package cn.hugh.bz.gk2.model; + +public class WallpaperImage { + private String uri; + private String folderPath; + private String name; + private long lastModified; + private long fileSize; + + public WallpaperImage(String uri, String folderPath, String name, + long lastModified, long fileSize) { + this.uri = uri; + this.folderPath = folderPath; + this.name = name; + this.lastModified = lastModified; + this.fileSize = fileSize; + } + + // Getters + public String getUri() { return uri; } + public String getFolderPath() { return folderPath; } + public String getName() { return name; } + public long getLastModified() { return lastModified; } + public long getFileSize() { return fileSize; } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/model/WallpaperImage.java +git commit -m "feat: add WallpaperImage model" +``` + +### Step 3: 创建 AppConfig 配置类 + +```java +package cn.hugh.bz.gk2.model; + +import java.util.List; + +public class AppConfig { + private List selectedFolders; + private PlayMode playMode; + private int intervalMinutes; + private boolean isEnabled; + private int currentIndex; + + public AppConfig() { + this.selectedFolders = new java.util.ArrayList<>(); + this.playMode = PlayMode.SEQUENTIAL; + this.intervalMinutes = 30; + this.isEnabled = false; + this.currentIndex = 0; + } + + // Getters and Setters + public List getSelectedFolders() { return selectedFolders; } + public void setSelectedFolders(List folders) { this.selectedFolders = folders; } + + public PlayMode getPlayMode() { return playMode; } + public void setPlayMode(PlayMode mode) { this.playMode = mode; } + + public int getIntervalMinutes() { return intervalMinutes; } + public void setIntervalMinutes(int minutes) { this.intervalMinutes = minutes; } + + public boolean isEnabled() { return isEnabled; } + public void setEnabled(boolean enabled) { isEnabled = enabled; } + + public int getCurrentIndex() { return currentIndex; } + public void setCurrentIndex(int index) { this.currentIndex = index; } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/model/AppConfig.java +git commit -m "feat: add AppConfig model" +``` + +--- + +## Task 3: 创建 SharedPreferences 管理类 + +**目标:** 创建用于持久化配置的工具类。 + +**Files:** +- Create: `app/src/main/java/cn/hugh/bz/gk2/wallpaper/WallpaperPreferences.java` + +### Step 1: 创建 WallpaperPreferences 类 + +```java +package cn.hugh.bz.gk2.wallpaper; + +import android.content.Context; +import android.content.SharedPreferences; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +import cn.hugh.bz.gk2.model.AppConfig; +import cn.hugh.bz.gk2.model.PlayMode; + +public class WallpaperPreferences { + private static final String PREFS_NAME = "wallpaper_prefs"; + private static final String KEY_FOLDERS = "selected_folders"; + private static final String KEY_PLAY_MODE = "play_mode"; + private static final String KEY_INTERVAL = "interval_minutes"; + private static final String KEY_ENABLED = "enabled"; + private static final String KEY_CURRENT_INDEX = "current_index"; + private static final String KEY_LAST_URI = "last_uri"; + + private final SharedPreferences prefs; + private final Gson gson; + + public WallpaperPreferences(Context context) { + this.prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); + this.gson = new Gson(); + } + + public AppConfig loadConfig() { + AppConfig config = new AppConfig(); + + String foldersJson = prefs.getString(KEY_FOLDERS, null); + if (foldersJson != null) { + Type listType = new TypeToken>(){}.getType(); + List folders = gson.fromJson(foldersJson, listType); + config.setSelectedFolders(folders); + } + + String modeString = prefs.getString(KEY_PLAY_MODE, PlayMode.SEQUENTIAL.name()); + config.setPlayMode(PlayMode.valueOf(modeString)); + + config.setIntervalMinutes(prefs.getInt(KEY_INTERVAL, 30)); + config.setEnabled(prefs.getBoolean(KEY_ENABLED, false)); + config.setCurrentIndex(prefs.getInt(KEY_CURRENT_INDEX, 0)); + + return config; + } + + public void saveConfig(AppConfig config) { + SharedPreferences.Editor editor = prefs.edit(); + + String foldersJson = gson.toJson(config.getSelectedFolders()); + editor.putString(KEY_FOLDERS, foldersJson); + editor.putString(KEY_PLAY_MODE, config.getPlayMode().name()); + editor.putInt(KEY_INTERVAL, config.getIntervalMinutes()); + editor.putBoolean(KEY_ENABLED, config.isEnabled()); + editor.putInt(KEY_CURRENT_INDEX, config.getCurrentIndex()); + + editor.apply(); + } + + public void saveLastUri(String uri) { + prefs.edit().putString(KEY_LAST_URI, uri).apply(); + } + + public String getLastUri() { + return prefs.getString(KEY_LAST_URI, null); + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/wallpaper/WallpaperPreferences.java +git commit -m "feat: add SharedPreferences manager" +``` + +--- + +## Task 4: 实现 WallpaperService 核心服务 + +**目标:** 实现 Live Wallpaper 核心服务,负责在 Canvas 上绘制图片。 + +**Files:** +- Create: `app/src/main/java/cn/hugh/bz/gk2/wallpaper/AutoWallpaperService.java` +- Create: `app/src/main/java/cn/hugh/bz/gk2/wallpaper/WallpaperEngine.java` +- Create: `app/src/main/java/cn/hugh/bz/gk2/wallpaper/ImageLoader.java` + +### Step 1: 创建 ImageLoader 类 + +```java +package cn.hugh.bz.gk2.wallpaper; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.util.Log; + +import java.io.File; + +public class ImageLoader { + private static final String TAG = "ImageLoader"; + private final Context context; + + public ImageLoader(Context context) { + this.context = context; + } + + public Bitmap loadImage(String uri, int maxWidth, int maxHeight) { + try { + File file = new File(uri); + if (!file.exists()) { + Log.e(TAG, "File not found: " + uri); + return null; + } + + // First decode with inJustDecodeBounds=true to check dimensions + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + BitmapFactory.decodeFile(file.getAbsolutePath(), options); + + // Calculate inSampleSize + options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight); + + // Decode bitmap with inSampleSize + options.inJustDecodeBounds = false; + options.inPreferredConfig = Bitmap.Config.RGB_565; + + Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); + + if (bitmap != null) { + // Scale to exact size if needed + bitmap = Bitmap.createScaledBitmap(bitmap, maxWidth, maxHeight, true); + } + + return bitmap; + } catch (Exception e) { + Log.e(TAG, "Failed to load image: " + uri, e); + return null; + } + } + + private int calculateInSampleSize(BitmapFactory.Options options, + int reqWidth, int reqHeight) { + final int height = options.outHeight; + final int width = options.outWidth; + int inSampleSize = 1; + + if (height > reqHeight || width > reqWidth) { + final int halfHeight = height / 2; + final int halfWidth = width / 2; + + while ((halfHeight / inSampleSize) >= reqHeight + && (halfWidth / inSampleSize) >= reqWidth) { + inSampleSize *= 2; + } + } + + return inSampleSize; + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/wallpaper/ImageLoader.java +git commit -m "feat: add image loader with sampling" +``` + +### Step 2: 创建 WallpaperEngine 类 + +```java +package cn.hugh.bz.gk2.wallpaper; + +import android.graphics.Canvas; +import android.os.Handler; +import android.os.Looper; +import android.service.wallpaper.WallpaperService; +import android.util.Log; +import android.view.SurfaceHolder; + +import cn.hugh.bz.gk2.model.AppConfig; +import cn.hugh.bz.gk2.model.PlayMode; +import cn.hugh.bz.gk2.model.WallpaperImage; +import cn.hugh.bz.gk2.utils.ImageScanner; +import cn.hugh.bz.gk2.utils.JsonHelper; + +public class WallpaperEngine extends WallpaperService.Engine { + private static final String TAG = "WallpaperEngine"; + + private final AutoWallpaperService service; + private final ImageLoader imageLoader; + private final WallpaperPreferences prefs; + private final Handler handler; + + private int width; + private int height; + private boolean visible = false; + + public WallpaperEngine(AutoWallpaperService service) { + this.service = service; + this.imageLoader = new ImageLoader(service); + this.prefs = new WallpaperPreferences(service); + this.handler = new Handler(Looper.getMainLooper()); + } + + @Override + public void onCreate(SurfaceHolder surfaceHolder) { + super.onCreate(surfaceHolder); + } + + @Override + public void onSurfaceChanged(SurfaceHolder holder, int format, + int width, int height) { + super.onSurfaceChanged(holder, format, width, height); + this.width = width; + this.height = height; + + if (visible) { + drawWallpaper(); + } + } + + @Override + public void onVisibilityChanged(boolean visible) { + super.onVisibilityChanged(visible); + this.visible = visible; + + if (visible) { + drawWallpaper(); + } else { + // Release resources when not visible + } + } + + @Override + public void onSurfaceDestroyed(SurfaceHolder holder) { + super.onSurfaceDestroyed(holder); + this.visible = false; + } + + public void refreshWallpaper() { + if (visible) { + handler.post(this::drawWallpaper); + } + } + + private void drawWallpaper() { + SurfaceHolder holder = getSurfaceHolder(); + if (holder == null || !holder.getSurface().isValid()) { + return; + } + + Canvas canvas = null; + try { + canvas = holder.lockCanvas(); + if (canvas != null) { + // Clear canvas + canvas.drawColor(android.graphics.Color.BLACK); + + // Load current wallpaper + AppConfig config = prefs.loadConfig(); + if (!config.isEnabled() || config.getSelectedFolders().isEmpty()) { + drawPlaceholder(canvas); + return; + } + + WallpaperImage image = getNextWallpaper(config); + if (image != null) { + drawImage(canvas, image.getUri()); + + // Save config + prefs.saveConfig(config); + prefs.saveLastUri(image.getUri()); + } else { + drawPlaceholder(canvas); + } + } + } catch (Exception e) { + Log.e(TAG, "Error drawing wallpaper", e); + } finally { + if (canvas != null) { + holder.unlockCanvasAndPost(canvas); + } + } + } + + private WallpaperImage getNextWallpaper(AppConfig config) { + ImageScanner scanner = new ImageScanner(); + String lastUri = prefs.getLastUri(); + + if (config.getPlayMode() == PlayMode.SEQUENTIAL) { + // Sequential mode + int index = config.getCurrentIndex(); + WallpaperImage image = scanner.getImageAtIndex(config.getSelectedFolders(), index); + if (image != null) { + config.setCurrentIndex(index + 1); + return image; + } + } else { + // Random mode + WallpaperImage image = scanner.getRandomImage(config.getSelectedFolders(), lastUri); + return image; + } + + return null; + } + + private void drawImage(Canvas canvas, String uri) { + Bitmap bitmap = imageLoader.loadImage(uri, width, height); + if (bitmap != null) { + // Center and scale the image + float scale = Math.max( + (float) width / bitmap.getWidth(), + (float) height / bitmap.getHeight() + ); + + float scaledWidth = bitmap.getWidth() * scale; + float scaledHeight = bitmap.getHeight() * scale; + + float left = (width - scaledWidth) / 2; + float top = (height - scaledHeight) / 2; + + canvas.drawBitmap(bitmap, null, + new android.graphics.RectF(left, top, left + scaledWidth, top + scaledHeight), + null); + } + } + + private void drawPlaceholder(Canvas canvas) { + // Draw placeholder text + android.Paint paint = new android.Paint(); + paint.setColor(android.graphics.Color.WHITE); + paint.setTextAlign(android.Paint.Align.CENTER); + paint.setTextSize(48); + + float centerX = width / 2f; + float centerY = height / 2f; + + canvas.drawText("请选择文件夹", centerX, centerY, paint); + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/wallpaper/WallpaperEngine.java +git commit -m "feat: add wallpaper engine with drawing logic" +``` + +### Step 3: 创建 AutoWallpaperService 类 + +```java +package cn.hugh.bz.gk2.wallpaper; + +import android.app.WallpaperManager; +import android.content.Intent; +import android.service.wallpaper.WallpaperService; + +import cn.hugh.bz.gk2.R; + +public class AutoWallpaperService extends WallpaperService { + + @Override + public Engine onCreateEngine() { + return new WallpaperEngine(this); + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/wallpaper/AutoWallpaperService.java +git commit -m "feat: add wallpaper service" +``` + +--- + +## Task 5: 实现 AlarmScheduler 定时调度 + +**目标:** 实现定时任务调度,支持 1-60 分钟间隔。 + +**Files:** +- Create: `app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java` + +### Step 1: 创建 AlarmScheduler 类 + +```java +package cn.hugh.bz.gk2.utils; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.Build; +import android.util.Log; + +import cn.hugh.bz.gk2.receiver.WallpaperChangeReceiver; + +public class AlarmScheduler { + private static final String TAG = "AlarmScheduler"; + private static final int REQUEST_CODE = 1000; + + private final Context context; + private final AlarmManager alarmManager; + + public AlarmScheduler(Context context) { + this.context = context; + this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + } + + public void scheduleWallpaperChange(long intervalMinutes) { + // Cancel existing alarm + cancelSchedule(); + + // Calculate interval in milliseconds + long intervalMillis = intervalMinutes * 60 * 1000; + long triggerAtMillis = System.currentTimeMillis() + intervalMillis; + + // Create pending intent + Intent intent = new Intent(context, WallpaperChangeReceiver.class); + intent.setAction(WallpaperChangeReceiver.ACTION_CHANGE_WALLPAPER); + + PendingIntent pendingIntent = PendingIntent.getBroadcast( + context, + REQUEST_CODE, + intent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE + ); + + // Schedule alarm + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + // Android 12+ needs exact alarm permission + if (alarmManager.canScheduleExactAlarms()) { + alarmManager.setExactAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + triggerAtMillis, + pendingIntent + ); + } else { + // Fallback to inexact alarm + alarmManager.setAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + triggerAtMillis, + pendingIntent + ); + } + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + alarmManager.setExactAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + triggerAtMillis, + pendingIntent + ); + } else { + alarmManager.setExact( + AlarmManager.RTC_WAKEUP, + triggerAtMillis, + pendingIntent + ); + } + + Log.i(TAG, "Scheduled wallpaper change every " + intervalMinutes + " minutes"); + } + + public void cancelSchedule() { + Intent intent = new Intent(context, WallpaperChangeReceiver.class); + intent.setAction(WallpaperChangeReceiver.ACTION_CHANGE_WALLPAPER); + + PendingIntent pendingIntent = PendingIntent.getBroadcast( + context, + REQUEST_CODE, + intent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE + ); + + alarmManager.cancel(pendingIntent); + Log.i(TAG, "Cancelled wallpaper change schedule"); + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/utils/AlarmScheduler.java +git commit -m "feat: add alarm scheduler with exact timing" +``` + +--- + +## Task 6: 实现 BroadcastReceiver 接收器 + +**目标:** 实现接收定时任务的广播接收器,触发壁纸更新。 + +**Files:** +- Create: `app/src/main/java/cn/hugh/bz/gk2/receiver/WallpaperChangeReceiver.java` + +### Step 1: 创建 WallpaperChangeReceiver 类 + +```java +package cn.hugh.bz.gk2.receiver; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.util.Log; + +import cn.hugh.bz.gk2.utils.AlarmScheduler; + +public class WallpaperChangeReceiver extends BroadcastReceiver { + private static final String TAG = "WallpaperChangeReceiver"; + public static final String ACTION_CHANGE_WALLPAPER = "cn.hugh.bz.gk2.ACTION_CHANGE_WALLPAPER"; + + @Override + public void onReceive(Context context, Intent intent) { + if (ACTION_CHANGE_WALLPAPER.equals(intent.getAction())) { + Log.i(TAG, "Received wallpaper change request"); + + // Refresh wallpaper + WallpaperRefreshHelper.refreshWallpaper(context); + + // Schedule next change + cn.hugh.bz.gk2.wallpaper.WallpaperPreferences prefs = + new cn.hugh.bz.gk2.wallpaper.WallpaperPreferences(context); + cn.hugh.bz.gk2.model.AppConfig config = prefs.loadConfig(); + + if (config.isEnabled()) { + AlarmScheduler scheduler = new AlarmScheduler(context); + scheduler.scheduleWallpaperChange(config.getIntervalMinutes()); + } + } + } +} + +// Helper class to refresh wallpaper +class WallpaperRefreshHelper { + static void refreshWallpaper(Context context) { + // Send broadcast to wallpaper service + Intent intent = new Intent("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER"); + context.sendBroadcast(intent); + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/receiver/WallpaperChangeReceiver.java +git commit -m "feat: add broadcast receiver for wallpaper changes" +``` + +### Step 2: 更新 AutoWallpaperService 支持刷新广播 + +```java +package cn.hugh.bz.gk2.wallpaper; + +import android.app.WallpaperManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.service.wallpaper.WallpaperService; + +import cn.hugh.bz.gk2.R; + +public class AutoWallpaperService extends WallpaperService { + + private WallpaperEngine engine; + + @Override + public void onCreate() { + super.onCreate(); + + // Register refresh receiver + IntentFilter filter = new IntentFilter("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER"); + registerReceiver(refreshReceiver, filter); + } + + @Override + public void onDestroy() { + unregisterReceiver(refreshReceiver); + super.onDestroy(); + } + + @Override + public Engine onCreateEngine() { + engine = new WallpaperEngine(this); + return engine; + } + + private final BroadcastReceiver refreshReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if ("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER".equals(intent.getAction())) { + if (engine != null) { + engine.refreshWallpaper(); + } + } + } + }; +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/wallpaper/AutoWallpaperService.java +git commit -m "feat: add refresh broadcast support to service" +``` + +--- + +## Task 7: 实现 ImageScanner 图片扫描工具 + +**目标:** 实现文件夹扫描和图片索引功能。 + +**Files:** +- Create: `app/src/main/java/cn/hugh/bz/gk2/utils/ImageScanner.java` +- Create: `app/src/main/java/cn/hugh/bz/gk2/utils/JsonHelper.java` + +### Step 1: 创建 JsonHelper 类 + +```java +package cn.hugh.bz.gk2.utils; + +import android.content.Context; +import android.util.Log; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import cn.hugh.bz.gk2.model.WallpaperImage; + +public class JsonHelper { + private static final String TAG = "JsonHelper"; + private static final String INDEX_DIR = "image_indices"; + + private final Context context; + private final Gson gson; + private final File indicesDir; + + public JsonHelper(Context context) { + this.context = context; + this.gson = new GsonBuilder().setPrettyPrinting().create(); + this.indicesDir = new File(context.getFilesDir(), INDEX_DIR); + if (!indicesDir.exists()) { + indicesDir.mkdirs(); + } + } + + public void saveIndex(String folderPath, List images) { + String fileName = getIndexFileName(folderPath); + File indexFile = new File(indicesDir, fileName); + + IndexData data = new IndexData(folderPath, new File(folderPath).getName(), + System.currentTimeMillis(), images.size(), images); + + try (FileWriter writer = new FileWriter(indexFile)) { + gson.toJson(data, writer); + Log.i(TAG, "Saved index: " + fileName + " with " + images.size() + " images"); + } catch (IOException e) { + Log.e(TAG, "Failed to save index", e); + } + } + + public List loadImageIndex(String folderPath) { + String fileName = getIndexFileName(folderPath); + File indexFile = new File(indicesDir, fileName); + + if (!indexFile.exists()) { + return null; + } + + try (FileReader reader = new FileReader(indexFile)) { + IndexData data = gson.fromJson(reader, IndexData.class); + return data.images; + } catch (IOException e) { + Log.e(TAG, "Failed to load index", e); + return null; + } + } + + private String getIndexFileName(String folderPath) { + int hash = folderPath.hashCode(); + return "folder_" + Math.abs(hash) + ".json"; + } + + public boolean needsRescan(String folderPath) { + List cached = loadImageIndex(folderPath); + if (cached == null) { + return true; + } + + File folder = new File(folderPath); + if (!folder.exists()) { + return false; + } + + String fileName = getIndexFileName(folderPath); + File indexFile = new File(indicesDir, fileName); + + return folder.lastModified() > indexFile.lastModified(); + } + + private static class IndexData { + String folderPath; + String folderName; + long lastScanned; + int imageCount; + List images; + + IndexData() {} + + IndexData(String folderPath, String folderName, long lastScanned, + int imageCount, List images) { + this.folderPath = folderPath; + this.folderName = folderName; + this.lastScanned = lastScanned; + this.imageCount = imageCount; + this.images = images; + } + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/utils/JsonHelper.java +git commit -m "feat: add JSON index storage" +``` + +### Step 2: 创建 ImageScanner 类 + +```java +package cn.hugh.bz.gk2.utils; + +import android.content.Context; +import android.util.Log; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; + +import cn.hugh.bz.gk2.model.WallpaperImage; + +public class ImageScanner { + private static final String TAG = "ImageScanner"; + private static final List IMAGE_EXTENSIONS = List.of("jpg", "jpeg", "png", "webp", "bmp"); + + private final Context context; + private final JsonHelper jsonHelper; + + public ImageScanner(Context context) { + this.context = context; + this.jsonHelper = new JsonHelper(context); + } + + public List scanFolder(String folderPath) { + if (!jsonHelper.needsRescan(folderPath)) { + List cached = jsonHelper.loadImageIndex(folderPath); + if (cached != null) { + Log.i(TAG, "Using cached index for: " + folderPath); + return cached; + } + } + + Log.i(TAG, "Scanning folder: " + folderPath); + + File folder = new File(folderPath); + if (!folder.exists() || !folder.isDirectory()) { + Log.e(TAG, "Folder not found or not a directory: " + folderPath); + return new ArrayList<>(); + } + + List images = new ArrayList<>(); + File[] files = folder.listFiles(); + + if (files == null) { + return images; + } + + for (File file : files) { + if (file.isFile() && isImageFile(file)) { + WallpaperImage image = new WallpaperImage( + file.getAbsolutePath(), + folderPath, + file.getName(), + file.lastModified(), + file.length() + ); + images.add(image); + } + } + + // Save to JSON + jsonHelper.saveIndex(folderPath, images); + + Log.i(TAG, "Found " + images.size() + " images in " + folderPath); + return images; + } + + private boolean isImageFile(File file) { + String name = file.getName().toLowerCase(); + for (String ext : IMAGE_EXTENSIONS) { + if (name.endsWith("." + ext)) { + return true; + } + } + return false; + } + + public WallpaperImage getImageAtIndex(List folders, int index) { + List allImages = loadAllImages(folders); + + if (allImages.isEmpty() || index < 0 || index >= allImages.size()) { + return null; + } + + return allImages.get(index); + } + + public WallpaperImage getRandomImage(List folders, String excludeUri) { + List allImages = loadAllImages(folders); + + if (allImages.isEmpty()) { + return null; + } + + // Filter out excluded image + List candidates = new ArrayList<>(); + for (WallpaperImage image : allImages) { + if (!image.getUri().equals(excludeUri)) { + candidates.add(image); + } + } + + if (candidates.isEmpty()) { + // All images are the same as excluded, return any + return allImages.get(0); + } + + Random random = new Random(); + return candidates.get(random.nextInt(candidates.size())); + } + + public int getTotalImageCount(List folders) { + return loadAllImages(folders).size(); + } + + private List loadAllImages(List folders) { + List allImages = new ArrayList<>(); + + for (String folder : folders) { + List images = jsonHelper.loadImageIndex(folder); + if (images != null) { + allImages.addAll(images); + } else { + // Scan if no cache + allImages.addAll(scanFolder(folder)); + } + } + + return allImages; + } +} +``` + +**Commit:** +```bash +git add app/src/main/java/cn/hugh/bz/gk2/utils/ImageScanner.java +git commit -m "feat: add image scanner with folder scanning" +``` + +--- + +## Task 8: 创建 MainActivity 主界面 + +**目标:** 创建主界面,显示当前壁纸预览和快速操作按钮。 + +**Files:** +- Create: `app/src/main/java/cn/hugh/bz/gk2/ui/MainActivity.java` +- Create: `app/src/main/res/layout/activity_main.xml` +- Create: `app/src/main/res/values/strings.xml` +- Create: `app/src/main/res/values/colors.xml` + +### Step 1: 创建 strings.xml + +```xml + + + 自动壁纸 + 自动更换您的桌面壁纸 + 设置 + 启用 + 禁用 + 立即更换 + 选择文件夹 + 运行中 + 已停止 + 下次更换:%d 分钟 + 未选择文件夹 + +``` + +**Commit:** +```bash +git add app/src/main/res/values/strings.xml +git commit -m "feat: add string resources" +``` + +### Step 2: 创建 colors.xml + +```xml + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + +``` + +**Commit:** +```bash +git add app/src/main/res/values/colors.xml +git commit -m "feat: add color resources" +``` + +### Step 3: 创建 activity_main.xml 布局 + +```xml + + + + + + + +