perf: 优化媒体扫描和壁纸服务性能及架构

性能优化:
- 使用 MediaStore API 替代文件遍历扫描,大幅提升文件夹扫描速度
- 添加缩略图内存缓存(LruCache,10MB),减少磁盘 I/O
- 使用固定线程池(4线程)加载缩略图,防止创建过多线程

架构改进:
- AppConfig 新增 albumId 字段,建立配置与相册的关联
- 改进配置保存逻辑,按 albumId 保存到对应相册,防止异步操作覆盖数据
- 相册切换时自动启用相册并发送广播刷新壁纸服务
- 切换相册时清理当前壁纸状态,防止显示错误内容

Bug 修复:
- 新建相册时显式清空列表,防止数据泄漏
- VideoPlayer 防止过期 MediaPlayer 的回调事件
- 视频准备后应用缩放模式(CENTER_CROP / FIT)
- 停止视频时使用 release 而非 pause,完全释放资源
- 加载壁纸时检查相册是否仍为激活相册,防止保存过期数据

其他改进:
- 视频播放准备好后立即检查电池状态,支持"省电时暂停"功能
- 设置 Surface 格式为 TRANSLUCENT,更好地支持媒体播放器
- 壁纸服务添加重复更新检查,及时响应 pending 的更换请求
- 移除视频模式下的黑色背景绘制

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-27 11:07:52 +08:00
1 parent e4bc8e3915
commit 668133ff08
9 files changed
+289 -60

No files matched your search

@@ -33,7 +33,7 @@ public class Album implements Serializable {
this.changeOnReturnToHome = true;
this.lastUri = null;
this.createdTime = System.currentTimeMillis();
this.enabled = false;
this.enabled = true;
this.imageUris = new ArrayList<>();
this.videoUris = new ArrayList<>();
}
@@ -3,6 +3,7 @@ package cn.hugh.bz.gk2.model;
import java.util.List;
public class AppConfig {
private String albumId;
private List<String> selectedFolders;
private PlayMode playMode;
private int intervalMinutes;
@@ -28,6 +29,9 @@ public class AppConfig {
}
// Getters and Setters
public String getAlbumId() { return albumId; }
public void setAlbumId(String albumId) { this.albumId = albumId; }
public List<String> getSelectedFolders() { return selectedFolders; }
public void setSelectedFolders(List<String> folders) { this.selectedFolders = folders; }
@@ -473,6 +473,11 @@ public class AlbumEditorActivity extends AppCompatActivity {
// 创建新相册
tvTitle.setText("新建相册");
album = new Album();
// Explicitly clear lists for new album to avoid data leakage
folders = new ArrayList<>();
imageUris = new ArrayList<>();
videoUris = new ArrayList<>();
// 默认值
rbSequential.setChecked(true);
@@ -611,6 +616,15 @@ public class AlbumEditorActivity extends AppCompatActivity {
albumPrefs.saveAlbums(albums);
// Check if the modified album is the active one
if (album.getId().equals(albumPrefs.getActiveAlbumId())) {
// Send broadcast to refresh wallpaper service
Intent intent = new Intent("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER_SERVICE");
intent.putExtra("force_change", true);
sendBroadcast(intent);
android.util.Log.i("AlbumEditorActivity", "Sent refresh broadcast for active album");
}
// 添加日志:确认保存的数据
android.util.Log.i("AlbumEditorActivity", "saveAlbum: name=" + album.getName() +
", folders=" + album.getFolders().size() +
@@ -745,6 +759,10 @@ public class AlbumEditorActivity extends AppCompatActivity {
private List<WallpaperMedia> mediaList;
private android.content.Context context;
private OnMediaClickListener listener;
// Use a static executor for thumbnail loading to prevent creating too many threads
private static final java.util.concurrent.ExecutorService thumbnailExecutor =
java.util.concurrent.Executors.newFixedThreadPool(4);
public interface OnMediaClickListener {
void onMediaClick(WallpaperMedia media);
@@ -810,7 +828,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
duration.setVisibility(View.VISIBLE);
} else {
// 尝试异步获取时长
new Thread(() -> {
thumbnailExecutor.execute(() -> {
long d = ThumbnailHelper.getVideoDuration(context, media.getUri());
if (d > 0) {
media.setDuration(d);
@@ -820,7 +838,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
duration.setVisibility(View.VISIBLE);
});
}
}).start();
});
}
}
@@ -853,13 +871,13 @@ public class AlbumEditorActivity extends AppCompatActivity {
thumbnail.setImageBitmap(cached);
} else {
// 异步生成缩略图
new Thread(() -> {
thumbnailExecutor.execute(() -> {
Bitmap thumb = ThumbnailHelper.generateVideoThumbnail(context, media.getUri());
if (thumb != null) {
ThumbnailHelper.saveThumbnailToCache(context, media.getUri(), thumb);
itemView.post(() -> thumbnail.setImageBitmap(thumb));
}
}).start();
});
}
}
}
@@ -125,10 +125,18 @@ public class AlbumManagementFragment extends Fragment {
}
private void switchToAlbum(Album album) {
// Ensure album is enabled when switching to it
if (!album.isEnabled()) {
album.setEnabled(true);
albumPrefs.updateAlbum(album);
}
albumPrefs.setActiveAlbumId(album.getId());
// TODO: 通知壁纸服务重新加载相册
// 需要发送广播或使用其他机制通知服务
// Notify wallpaper service to refresh
Intent intent = new Intent("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER_SERVICE");
intent.putExtra("force_change", true);
requireContext().sendBroadcast(intent);
Toast.makeText(requireContext(), "已切换到:" + album.getName(), Toast.LENGTH_SHORT).show();
loadAlbums(); // 刷新列表以更新"当前"徽章
@@ -1,7 +1,10 @@
package cn.hugh.bz.gk2.utils;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.util.LruCache;
@@ -98,11 +101,18 @@ public class MediaScanner {
long startTime = System.currentTimeMillis();
List<WallpaperMedia> mediaList = new ArrayList<>();
// 检查是否是 URI 格式
if (folderPath.startsWith("content://")) {
mediaList = scanDocumentFolder(folderPath);
} else {
mediaList = scanFileFolder(folderPath);
// 优先使用 MediaStore 扫描(速度最快)
if (!folderPath.startsWith("content://")) {
mediaList = scanFolderUsingMediaStore(folderPath);
}
// 如果 MediaStore 扫描结果为空(可能未索引),或者是 content URI,回退到文件遍历
if (mediaList.isEmpty()) {
if (folderPath.startsWith("content://")) {
mediaList = scanDocumentFolder(folderPath);
} else {
mediaList = scanFileFolder(folderPath);
}
}
long scanTime = System.currentTimeMillis() - startTime;
@@ -116,6 +126,95 @@ public class MediaScanner {
return mediaList;
}
/**
* 使用 MediaStore 扫描文件夹(极大提升速度)
*/
private List<WallpaperMedia> scanFolderUsingMediaStore(String folderPath) {
List<WallpaperMedia> mediaList = new ArrayList<>();
File folder = new File(folderPath);
if (!folder.exists() || !folder.isDirectory()) {
return mediaList;
}
// 查询图片
queryMediaStore(folderPath, MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_MODIFIED, MediaType.IMAGE, mediaList);
// 查询视频
queryMediaStore(folderPath, MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
MediaStore.Video.Media.DATA, MediaStore.Video.Media.DATE_MODIFIED, MediaType.VIDEO, mediaList);
// 按修改时间排序
Collections.sort(mediaList, (o1, o2) -> Long.compare(o2.getLastModified(), o1.getLastModified()));
return mediaList;
}
private void queryMediaStore(String folderPath, Uri contentUri, String dataColumn, String dateColumn,
MediaType type, List<WallpaperMedia> resultList) {
String[] projection = {
dataColumn,
MediaStore.MediaColumns.DISPLAY_NAME,
dateColumn,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns._ID
};
// 构建查询条件:路径匹配
// 注意:DATA 字段在 Android 10+ 可能受限,但对于应用私有目录或有权限的公共目录仍有效
// 更通用的方式是使用 RELATIVE_PATH,但只在 Android 10+ 可用
// 这里使用 DATA like 'folderPath%' 来匹配
String selection = dataColumn + " like ?";
String[] selectionArgs = new String[]{folderPath + "%"};
try (Cursor cursor = context.getContentResolver().query(
contentUri,
projection,
selection,
selectionArgs,
null
)) {
if (cursor != null) {
int dataIndex = cursor.getColumnIndexOrThrow(dataColumn);
int nameIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
int dateIndex = cursor.getColumnIndexOrThrow(dateColumn);
int sizeIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.SIZE);
int idIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID);
while (cursor.moveToNext()) {
String path = cursor.getString(dataIndex);
// 确保文件直接位于该文件夹下,而不是子文件夹(如果需要递归,去掉此检查)
// 这里假设不递归,或者是为了精确匹配文件夹
if (path != null && new File(path).getParent().equals(folderPath)) {
String name = cursor.getString(nameIndex);
long date = cursor.getLong(dateIndex) * 1000; // MediaStore stores in seconds
long size = cursor.getLong(sizeIndex);
long id = cursor.getLong(idIndex);
// 构建 content URI
Uri itemUri = ContentUris.withAppendedId(contentUri, id);
WallpaperMedia media = new WallpaperMedia(
itemUri.toString(), // 使用 Content URI
folderPath,
name,
date,
size,
type
);
// 对于视频,可以尝试获取时长(可选,这里先不获取以保持速度)
resultList.add(media);
}
}
}
} catch (Exception e) {
Log.e(TAG, "Error querying MediaStore", e);
}
}
/**
* 扫描 DocumentFile 格式的文件夹(优化版)
*/
@@ -2,9 +2,11 @@ package cn.hugh.bz.gk2.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.util.Log;
import android.util.LruCache;
import java.io.File;
import java.io.FileOutputStream;
@@ -14,6 +16,15 @@ public class ThumbnailHelper {
private static final int THUMBNAIL_WIDTH = 200;
private static final int THUMBNAIL_HEIGHT = 200;
// Memory cache for thumbnails (max 10MB)
private static final int MEMORY_CACHE_SIZE = 10 * 1024 * 1024;
private static final LruCache<String, Bitmap> memoryCache = new LruCache<String, Bitmap>(MEMORY_CACHE_SIZE) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
/**
* 生成视频缩略图
*
@@ -149,6 +160,11 @@ public class ThumbnailHelper {
* 保存缩略图到本地缓存
*/
public static File saveThumbnailToCache(Context context, String videoUri, Bitmap thumbnail) {
if (thumbnail == null) return null;
// Add to memory cache
memoryCache.put(videoUri, thumbnail);
try {
File cacheDir = new File(context.getCacheDir(), "video_thumbnails");
if (!cacheDir.exists()) {
@@ -175,14 +191,25 @@ public class ThumbnailHelper {
* 从缓存加载缩略图
*/
public static Bitmap loadThumbnailFromCache(Context context, String videoUri) {
// Check memory cache first
Bitmap cachedBitmap = memoryCache.get(videoUri);
if (cachedBitmap != null) {
return cachedBitmap;
}
try {
File cacheDir = new File(context.getCacheDir(), "video_thumbnails");
String fileName = String.valueOf(videoUri.hashCode()) + ".jpg";
File thumbnailFile = new File(cacheDir, fileName);
if (thumbnailFile.exists()) {
Log.i(TAG, "Loaded thumbnail from cache: " + thumbnailFile.getAbsolutePath());
return android.graphics.BitmapFactory.decodeFile(thumbnailFile.getAbsolutePath());
Log.i(TAG, "Loaded thumbnail from disk cache: " + thumbnailFile.getAbsolutePath());
Bitmap bitmap = BitmapFactory.decodeFile(thumbnailFile.getAbsolutePath());
if (bitmap != null) {
// Add to memory cache
memoryCache.put(videoUri, bitmap);
}
return bitmap;
}
} catch (Exception e) {
Log.e(TAG, "Error loading thumbnail from cache", e);
@@ -158,6 +158,9 @@ public class AutoWallpaperService extends WallpaperService {
@Override
public void onPrepared() {
Log.i(TAG, "Video prepared and playing");
// Check battery status immediately after start to handle "pause on battery" policy
// while still ensuring the first frame is rendered
handler.post(() -> checkBatteryAndPauseIfNeeded());
}
@Override
@@ -172,10 +175,23 @@ public class AutoWallpaperService extends WallpaperService {
});
}
private void checkBatteryAndPauseIfNeeded() {
if (isPlayingVideo && visible) {
AppConfig config = prefs.loadConfig();
if (config.isVideoPauseOnBattery() && !isCharging) {
videoPlayer.pause();
fileLogger.log(TAG, "Video paused immediately (on battery)");
}
}
}
@Override
public void onCreate(android.view.SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
// Set pixel format to support media player
surfaceHolder.setFormat(android.graphics.PixelFormat.TRANSLUCENT);
// 更新服务活跃时间
WallpaperServiceHelper.updateActiveTime(AutoWallpaperService.this);
@@ -349,6 +365,11 @@ public class AutoWallpaperService extends WallpaperService {
return;
}
}
} else {
// Changing wallpaper (e.g. switched album), clear current state
stopVideo();
stopImageDisplay();
currentMedia = null;
}
// 需要更换壁纸或没有缓存,在后台线程执行扫描和加载
@@ -372,6 +393,11 @@ public class AutoWallpaperService extends WallpaperService {
prefs.saveLastUri(media.getUri());
isLoadingWallpaper = false;
// Check if another update is pending
if (forceChangeNext || scheduledNext) {
drawWallpaper();
}
});
} else {
// 在后台线程加载图片
@@ -390,7 +416,14 @@ public class AutoWallpaperService extends WallpaperService {
drawBitmapSync(holder, bitmap);
// 保存配置和历史
prefs.saveConfig(config);
// 增加安全性校验:仅当加载的相册仍是当前激活相册时才保存(防止异步覆盖)
String activeId = albumPrefs.getActiveAlbumId();
if (config.getAlbumId() != null && config.getAlbumId().equals(activeId)) {
prefs.saveConfig(config);
} else {
Log.w(TAG, "Active album changed during load, skipping save to avoid corruption");
}
prefs.saveLastUri(media.getUri());
// 保存到历史记录
@@ -406,11 +439,21 @@ public class AutoWallpaperService extends WallpaperService {
currentMedia = media;
isLoadingWallpaper = false;
// Check if another update is pending
if (forceChangeNext || scheduledNext) {
drawWallpaper();
}
});
} else {
handler.post(() -> {
drawPlaceholderSync(holder);
isLoadingWallpaper = false;
// Check if another update is pending
if (forceChangeNext || scheduledNext) {
drawWallpaper();
}
});
}
}
@@ -419,12 +462,22 @@ public class AutoWallpaperService extends WallpaperService {
fileLogger.warn(TAG, "No more wallpapers available");
drawPlaceholderSync(holder);
isLoadingWallpaper = false;
// Check if another update is pending
if (forceChangeNext || scheduledNext) {
drawWallpaper();
}
});
}
} catch (Exception e) {
Log.e(TAG, "Error loading wallpaper", e);
handler.post(() -> {
isLoadingWallpaper = false;
// Check if another update is pending
if (forceChangeNext || scheduledNext) {
drawWallpaper();
}
});
}
});
@@ -474,8 +527,6 @@ public class AutoWallpaperService extends WallpaperService {
try {
canvas = holder.lockCanvas();
if (canvas != null) {
canvas.drawColor(Color.BLACK);
// Calculate scale to cover the entire screen
float scaleX = (float) width / bitmap.getWidth();
float scaleY = (float) height / bitmap.getHeight();
@@ -717,7 +768,7 @@ public class AutoWallpaperService extends WallpaperService {
private void stopVideo() {
if (isPlayingVideo) {
videoPlayer.pause();
videoPlayer.release();
isPlayingVideo = false;
}
}
@@ -734,10 +785,10 @@ public class AutoWallpaperService extends WallpaperService {
boolean hasImages = config.getImageUris() != null && !config.getImageUris().isEmpty();
boolean hasVideos = config.isVideoEnabled() && config.getVideoUris() != null && !config.getVideoUris().isEmpty();
android.util.Log.i(TAG, "hasAvailableMedia: folders=" + hasFolders +
", hasImages=" + hasImages +
", hasVideos=" + hasVideos +
", videoEnabled=" + config.isVideoEnabled() +
android.util.Log.i(TAG, "hasAvailableMedia: folders=" + hasFolders +
", hasImages=" + hasImages +
", hasVideos=" + hasVideos +
", videoEnabled=" + config.isVideoEnabled() +
", videoUris=" + (config.getVideoUris() != null ? config.getVideoUris().size() : 0));
return hasFolders || hasImages || hasVideos;
@@ -41,6 +41,7 @@ public class VideoPlayer {
public void play(Context context, String uri) {
release();
Log.i(TAG, "Playing video: " + uri);
try {
mediaPlayer = new MediaPlayer();
@@ -52,7 +53,19 @@ public class VideoPlayer {
mediaPlayer.setVolume(volume, volume);
mediaPlayer.setOnPreparedListener(mp -> {
if (mediaPlayer != mp) {
Log.w(TAG, "Ignoring onPrepared from stale MediaPlayer");
return;
}
isPrepared = true;
// Apply scaling mode
if (scaleType == VideoScaleType.CENTER_CROP) {
mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
} else {
mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT);
}
mp.setVolume(volume, volume);
mp.start();
Log.i(TAG, "Video prepared and started");
@@ -62,6 +75,10 @@ public class VideoPlayer {
});
mediaPlayer.setOnErrorListener((mp, what, extra) -> {
if (mediaPlayer != mp) {
Log.w(TAG, "Ignoring onError from stale MediaPlayer");
return true;
}
Log.e(TAG, "MediaPlayer error: what=" + what + ", extra=" + extra);
if (callback != null) {
callback.onError("Playback error: " + what);
@@ -70,6 +87,10 @@ public class VideoPlayer {
});
mediaPlayer.setOnCompletionListener(mp -> {
if (mediaPlayer != mp) {
Log.w(TAG, "Ignoring onCompletion from stale MediaPlayer");
return;
}
Log.i(TAG, "Video completed");
if (callback != null) {
callback.onCompletion();
@@ -102,6 +102,7 @@ public class WallpaperPreferences {
if (album != null) {
// 从相册读取配置
config.setAlbumId(album.getId());
config.setSelectedFolders(new ArrayList<>(album.getFolders()));
config.setPlayMode(album.getPlayMode());
config.setIntervalMinutes(album.getIntervalMinutes());
@@ -148,45 +149,45 @@ public class WallpaperPreferences {
return config;
}
/**
* 保存配置到当前激活的相册
*/
public void saveConfig(AppConfig config) {
// 获取当前激活的相册
Album album = albumPrefs.getActiveAlbum();
if (album == null) {
// 如果没有激活的相册,使用默认相册
album = albumPrefs.createDefaultAlbumIfNeeded();
/**
* 保存配置到指定的相册
*/
public void saveConfig(AppConfig config) {
if (config.getAlbumId() == null) {
android.util.Log.e("WallpaperPreferences", "saveConfig: albumId is null, cannot save");
return;
}
// 获取对应的相册
Album album = albumPrefs.findAlbumById(config.getAlbumId());
if (album == null) {
android.util.Log.e("WallpaperPreferences", "saveConfig: album not found: " + config.getAlbumId());
return;
}
// 更新相册配置
album.setFolders(new ArrayList<>(config.getSelectedFolders()));
album.setPlayMode(config.getPlayMode());
album.setIntervalMinutes(config.getIntervalMinutes());
album.setEnabled(config.isEnabled());
album.setCurrentIndex(config.getCurrentIndex());
album.setChangeOnReturnToHome(config.isChangeOnReturnToHome());
album.setImageUris(new ArrayList<>(config.getImageUris()));
List<String> videoUris = config.getVideoUris();
album.setVideoUris(videoUris != null ? new ArrayList<>(videoUris) : new ArrayList<>());
// 保存相册
android.util.Log.i("WallpaperPreferences", "saveConfig: saved to album=" + album.getName() + " (id=" + album.getId() + ")");
albumPrefs.updateAlbum(album);
// Save global video settings to SharedPreferences
prefs.edit()
.putBoolean(KEY_VIDEO_ENABLED, config.isVideoEnabled())
.putBoolean(KEY_VIDEO_MUTED, config.isVideoMuted())
.putBoolean(KEY_VIDEO_PAUSE_ON_BATTERY, config.isVideoPauseOnBattery())
.apply();
}
// 更新相册配置
album.setFolders(new ArrayList<>(config.getSelectedFolders()));
album.setPlayMode(config.getPlayMode());
album.setIntervalMinutes(config.getIntervalMinutes());
album.setEnabled(config.isEnabled());
album.setCurrentIndex(config.getCurrentIndex());
album.setChangeOnReturnToHome(config.isChangeOnReturnToHome());
album.setImageUris(new ArrayList<>(config.getImageUris()));
List<String> videoUris = config.getVideoUris();
album.setVideoUris(videoUris != null ? new ArrayList<>(videoUris) : new ArrayList<>());
// 保存相册
android.util.Log.i("WallpaperPreferences", "saveConfig: album=" + album.getName() +
", folders=" + album.getFolders().size() +
", images=" + album.getImageUris().size() +
", videos=" + album.getVideoUris().size());
albumPrefs.updateAlbum(album);
// Save global video settings to SharedPreferences
prefs.edit()
.putBoolean(KEY_VIDEO_ENABLED, config.isVideoEnabled())
.putBoolean(KEY_VIDEO_MUTED, config.isVideoMuted())
.putBoolean(KEY_VIDEO_PAUSE_ON_BATTERY, config.isVideoPauseOnBattery())
.apply();
}
public void saveLastUri(String uri) {
prefs.edit().putString(KEY_LAST_URI, uri).apply();