perf: 性能优化 - Glide 图片加载、异步扫描、进度显示

- 使用 Glide 替换自定义 ImageLoader,提升图片质量和缓存效率
- 添加 WallpaperGlideModule 配置 ARGB_8888 色彩格式
- FileLogger 改为异步写入,避免阻塞主线程
- ImageScanner 添加进度回调接口 ScanProgressCallback
- AutoWallpaperService 壁纸加载移至后台线程,添加 Bitmap 回收
- AlbumEditorActivity 添加文件夹扫描进度对话框
- AlbumEditorActivity/AlbumManagementFragment 修复图片数量显示

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Opus 4.5 committed 2026-01-25 14:21:26 +08:00
1 parent 96570fffcb
commit afc06d8e8b
10 files changed
+1081 -381

No files matched your search

-1
View File
@@ -1 +0,0 @@
/cache
-89
View File
@@ -1,89 +0,0 @@
# list of languages for which language servers are started; choose from:
# al bash clojure cpp csharp
# csharp_omnisharp dart elixir elm erlang
# fortran fsharp go groovy haskell
# java julia kotlin lua markdown
# matlab nix pascal perl php
# powershell python python_jedi r rego
# ruby ruby_solargraph rust scala swift
# terraform toml typescript typescript_vts vue
# yaml zig
# (This list may be outdated. For the current list, see values of Language enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Free Pascal/Lazarus, use pascal
# Special requirements:
# - csharp: Requires the presence of a .sln file in the project folder.
# - pascal: Requires Free Pascal Compiler (fpc) and optionally Lazarus.
# When using multiple languages, the first language server that supports a given file will be used for that file.
# The first language is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
languages:
- java
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# list of additional paths to ignore in all projects
# same syntax as gitignore, so you can use * and **
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project by name.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_lines`: Deletes a range of lines within a file.
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
# * `execute_shell_command`: Executes a shell command.
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
# * `initial_instructions`: Gets the initial instructions for the current project.
# Should only be used in settings where the system prompt cannot be set,
# e.g. in clients you have no control over, like Claude Desktop.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_at_line`: Inserts content at a given line in a file.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: Lists memories in Serena's project-specific memory store.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
# * `remove_project`: Removes a project from the Serena configuration.
# * `replace_lines`: Replaces a range of lines within a file with new content.
# * `replace_symbol_body`: Replaces the full definition of a symbol.
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
# * `switch_modes`: Activates modes by providing a list of their names
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
excluded_tools: []
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
project_name: "bzForGk2"
included_optional_tools: []
@@ -1,10 +1,14 @@
package cn.hugh.bz.gk2.ui;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
@@ -30,6 +34,8 @@ import java.util.List;
import cn.hugh.bz.gk2.R;
import cn.hugh.bz.gk2.model.Album;
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.wallpaper.AlbumPreferences;
/**
@@ -46,6 +52,8 @@ public class AlbumEditorActivity extends AppCompatActivity {
private EditText etAlbumName;
private MaterialButton btnAddFolder;
private RecyclerView rvFolders;
private MaterialButton btnAddImage;
private RecyclerView rvImages;
private RadioGroup rgPlayMode;
private RadioButton rbSequential;
private RadioButton rbRandom;
@@ -57,20 +65,85 @@ public class AlbumEditorActivity extends AppCompatActivity {
private Album album;
private String albumId;
private List<String> folders;
private List<String> imageUris;
private FolderAdapter folderAdapter;
private ImageAdapter imageAdapter;
private ActivityResultLauncher<Intent> folderPickerLauncher;
private ActivityResultLauncher<Intent> imagePickerLauncher;
// 扫描进度相关
private ImageScanner imageScanner;
private ProgressDialog progressDialog;
private Handler mainHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
android.util.Log.i("AlbumEditorActivity", "onCreate: starting");
setContentView(R.layout.activity_album_editor);
albumPrefs = new AlbumPreferences(this);
folders = new ArrayList<>();
imageUris = new ArrayList<>();
// 初始化扫描器和 Handler
imageScanner = new ImageScanner(this);
mainHandler = new Handler(Looper.getMainLooper());
initFolderPickerLauncher();
initImagePickerLauncher();
initViews();
loadAlbum();
android.util.Log.i("AlbumEditorActivity", "onCreate: completed, imageUris=" + imageUris.size());
}
@Override
protected void onDestroy() {
super.onDestroy();
// 关闭扫描器
if (imageScanner != null) {
imageScanner.shutdown();
}
// 关闭进度对话框
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
/**
* 初始化图片选择器
*/
private void initImagePickerLauncher() {
android.util.Log.i("AlbumEditorActivity", "initImagePickerLauncher: initializing image picker launcher");
imagePickerLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
android.util.Log.i("AlbumEditorActivity", "ActivityResult callback: resultCode=" + result.getResultCode() +
", hasData=" + (result.getData() != null));
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
Uri uri = result.getData().getData();
android.util.Log.i("AlbumEditorActivity", "ActivityResult: got URI=" + uri);
if (uri != null) {
try {
// 持久化 URI 权限
final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
getContentResolver().takePersistableUriPermission(uri, takeFlags);
android.util.Log.i("AlbumEditorActivity", "ActivityResult: URI permission granted");
String imageUri = uri.toString();
addImage(imageUri);
} catch (Exception e) {
android.util.Log.e("AlbumEditorActivity", "ActivityResult: error granting URI permission", e);
}
} else {
android.util.Log.w("AlbumEditorActivity", "ActivityResult: URI is null");
}
} else {
android.util.Log.w("AlbumEditorActivity", "ActivityResult: result not OK or no data");
}
}
);
android.util.Log.i("AlbumEditorActivity", "initImagePickerLauncher: launcher registered successfully");
}
/**
@@ -83,20 +156,105 @@ public class AlbumEditorActivity extends AppCompatActivity {
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
Uri uri = result.getData().getData();
if (uri != null) {
// 持久化 URI 权限
// 在后台线程处理权限获取,避免阻塞主线程
final Uri folderUri = uri;
// 显示进度对话框
showScanProgressDialog();
new Thread(() -> {
try {
// 持久化 URI 权限(可能耗时)
final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
getContentResolver().takePersistableUriPermission(uri, takeFlags);
getContentResolver().takePersistableUriPermission(folderUri, takeFlags);
// 保存完整的 URI 字符串
String folderUri = uri.toString();
addFolder(folderUri);
String folderUriString = folderUri.toString();
// 扫描文件夹并显示进度
scanFolderWithProgress(folderUriString);
} catch (Exception e) {
android.util.Log.e("AlbumEditorActivity", "Error taking URI permission", e);
mainHandler.post(() -> {
dismissProgressDialog();
Toast.makeText(this, "添加文件夹失败", Toast.LENGTH_SHORT).show();
});
}
}).start();
}
}
}
);
}
/**
* 显示扫描进度对话框
*/
private void showScanProgressDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("扫描文件夹");
progressDialog.setMessage("正在扫描图片...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.setCancelable(false);
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void dismissProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}
/**
* 带进度的文件夹扫描
*/
private void scanFolderWithProgress(String folderUri) {
imageScanner.scanFolderWithProgress(folderUri, new ImageScanner.ScanProgressCallback() {
@Override
public void onProgress(int current, int total, String currentFile) {
mainHandler.post(() -> {
if (progressDialog != null && progressDialog.isShowing()) {
int percent = total > 0 ? (current * 100 / total) : 0;
progressDialog.setProgress(percent);
progressDialog.setMessage("正在扫描: " + current + "/" + total);
}
});
}
@Override
public void onComplete(List<WallpaperImage> images) {
mainHandler.post(() -> {
dismissProgressDialog();
// 添加文件夹到列表
addFolder(folderUri);
// 显示扫描结果
Toast.makeText(AlbumEditorActivity.this,
"已添加文件夹,发现 " + images.size() + " 张图片",
Toast.LENGTH_SHORT).show();
});
}
@Override
public void onError(String error) {
mainHandler.post(() -> {
dismissProgressDialog();
Toast.makeText(AlbumEditorActivity.this,
"扫描失败: " + error,
Toast.LENGTH_SHORT).show();
});
}
});
}
private void initViews() {
btnBack = findViewById(R.id.btnBack);
tvTitle = findViewById(R.id.tvTitle);
@@ -104,6 +262,8 @@ public class AlbumEditorActivity extends AppCompatActivity {
etAlbumName = findViewById(R.id.etAlbumName);
btnAddFolder = findViewById(R.id.btnAddFolder);
rvFolders = findViewById(R.id.rvFolders);
btnAddImage = findViewById(R.id.btnAddImage);
rvImages = findViewById(R.id.rvImages);
rgPlayMode = findViewById(R.id.rgPlayMode);
rbSequential = findViewById(R.id.rbSequential);
rbRandom = findViewById(R.id.rbRandom);
@@ -120,6 +280,9 @@ public class AlbumEditorActivity extends AppCompatActivity {
// 添加文件夹按钮
btnAddFolder.setOnClickListener(v -> openFolderPicker());
// 添加图片按钮
btnAddImage.setOnClickListener(v -> openImagePicker());
// 播放模式
rgPlayMode.setOnCheckedChangeListener((group, checkedId) -> {
// 实时更新
@@ -144,8 +307,13 @@ public class AlbumEditorActivity extends AppCompatActivity {
// 文件夹列表
rvFolders.setLayoutManager(new LinearLayoutManager(this));
folderAdapter = new FolderAdapter(folders, this::removeFolder);
folderAdapter = new FolderAdapter(this, folders, this::removeFolder);
rvFolders.setAdapter(folderAdapter);
// 图片列表
rvImages.setLayoutManager(new LinearLayoutManager(this));
imageAdapter = new ImageAdapter(imageUris, this::removeImage);
rvImages.setAdapter(imageAdapter);
}
private void loadAlbum() {
@@ -162,6 +330,11 @@ public class AlbumEditorActivity extends AppCompatActivity {
folders = new ArrayList<>(album.getFolders());
folderAdapter.updateFolders(folders);
// 图片列表
List<String> albumImages = album.getImageUris();
imageUris = albumImages != null ? new ArrayList<>(albumImages) : new ArrayList<>();
imageAdapter.updateImages(imageUris);
// 播放模式
if (album.getPlayMode() == PlayMode.SEQUENTIAL) {
rbSequential.setChecked(true);
@@ -212,6 +385,35 @@ public class AlbumEditorActivity extends AppCompatActivity {
folderAdapter.updateFolders(folders);
}
private void openImagePicker() {
android.util.Log.i("AlbumEditorActivity", "openImagePicker: launching image picker");
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
imagePickerLauncher.launch(intent);
android.util.Log.i("AlbumEditorActivity", "openImagePicker: image picker launched");
}
private void addImage(String imageUri) {
android.util.Log.i("AlbumEditorActivity", "addImage called: imageUri=" + imageUri);
android.util.Log.i("AlbumEditorActivity", "addImage: current imageUris size=" + imageUris.size());
if (imageUri != null && !imageUris.contains(imageUri)) {
imageUris.add(imageUri);
imageAdapter.updateImages(imageUris);
android.util.Log.i("AlbumEditorActivity", "addImage: added successfully, new size=" + imageUris.size());
Toast.makeText(this, "已添加图片", Toast.LENGTH_SHORT).show();
} else {
android.util.Log.w("AlbumEditorActivity", "addImage: imageUri is null or already exists");
}
}
private void removeImage(String imageUri) {
imageUris.remove(imageUri);
imageAdapter.updateImages(imageUris);
}
private void saveAlbum() {
// 验证相册名称
String name = etAlbumName.getText().toString().trim();
@@ -227,9 +429,9 @@ public class AlbumEditorActivity extends AppCompatActivity {
return;
}
// 验证文件夹
if (folders.isEmpty()) {
Toast.makeText(this, "请至少选择一个文件夹", Toast.LENGTH_SHORT).show();
// 验证:至少要有文件夹或图片
if (folders.isEmpty() && imageUris.isEmpty()) {
Toast.makeText(this, "请至少选择一个文件夹或一张图片", Toast.LENGTH_SHORT).show();
return;
}
@@ -243,6 +445,7 @@ public class AlbumEditorActivity extends AppCompatActivity {
album.setName(name);
album.setFolders(new ArrayList<>(folders));
album.setImageUris(new ArrayList<>(imageUris));
// 播放模式
if (rbSequential.isChecked()) {
@@ -275,6 +478,11 @@ public class AlbumEditorActivity extends AppCompatActivity {
albumPrefs.saveAlbums(albums);
// 添加日志:确认保存的数据
android.util.Log.i("AlbumEditorActivity", "saveAlbum: name=" + album.getName() +
", folders=" + album.getFolders().size() +
", images=" + album.getImageUris().size());
Toast.makeText(this, "相册已保存", Toast.LENGTH_SHORT).show();
finish();
}
@@ -284,10 +492,12 @@ public class AlbumEditorActivity extends AppCompatActivity {
*/
private static class FolderAdapter extends RecyclerView.Adapter<FolderAdapter.ViewHolder> {
private final android.content.Context context;
private List<String> folders;
private final OnFolderRemoveListener removeListener;
public FolderAdapter(List<String> folders, OnFolderRemoveListener removeListener) {
public FolderAdapter(android.content.Context context, List<String> folders, OnFolderRemoveListener removeListener) {
this.context = context;
this.folders = folders != null ? folders : new ArrayList<>();
this.removeListener = removeListener;
}
@@ -317,22 +527,55 @@ public class AlbumEditorActivity extends AppCompatActivity {
class ViewHolder extends RecyclerView.ViewHolder {
private final TextView tvFolderName;
private final TextView tvFolderPath;
private final TextView tvImageCount;
private final Button btnRemove;
public ViewHolder(android.view.View itemView) {
super(itemView);
tvFolderName = itemView.findViewById(R.id.tvFolderName);
tvFolderPath = itemView.findViewById(R.id.tvFolderPath);
tvImageCount = itemView.findViewById(R.id.tvImageCount);
btnRemove = itemView.findViewById(R.id.btnRemove);
}
public void bind(String folderUri) {
// 显示文件夹 URI 的最后一部分
// 显示文件夹 URI 的最后一部分作为名称
String displayName = folderUri.substring(folderUri.lastIndexOf('/') + 1);
// URL 解码
try {
displayName = java.net.URLDecoder.decode(displayName, "UTF-8");
} catch (Exception e) {
// 忽略解码错误
}
if (displayName.isEmpty()) {
displayName = "文件夹";
}
tvFolderName.setText(displayName);
// 显示完整路径
if (tvFolderPath != null) {
tvFolderPath.setText(folderUri);
}
// 初始显示"扫描中..."
if (tvImageCount != null) {
tvImageCount.setText("扫描中...");
// 异步扫描图片数量
new Thread(() -> {
ImageScanner scanner = new ImageScanner(context);
List<WallpaperImage> images = scanner.scanFolder(folderUri);
int count = images != null ? images.size() : 0;
scanner.shutdown();
// 更新 UI
tvImageCount.post(() -> {
tvImageCount.setText(count + " 张图片");
});
}).start();
}
btnRemove.setOnClickListener(v -> {
if (removeListener != null) {
removeListener.onRemove(folderUri);
@@ -345,4 +588,74 @@ public class AlbumEditorActivity extends AppCompatActivity {
void onRemove(String folderUri);
}
}
/**
* 图片列表适配器(简化版)
*/
private static class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
private List<String> images;
private final OnImageRemoveListener removeListener;
public ImageAdapter(List<String> images, OnImageRemoveListener removeListener) {
this.images = images != null ? images : new ArrayList<>();
this.removeListener = removeListener;
}
public void updateImages(List<String> images) {
android.util.Log.i("AlbumEditorActivity", "ImageAdapter.updateImages: updating adapter with " +
(images != null ? images.size() : "null") + " images");
this.images = images != null ? images : new ArrayList<>();
notifyDataSetChanged();
android.util.Log.i("AlbumEditorActivity", "ImageAdapter.updateImages: notifyDataSetChanged called, getItemCount=" + getItemCount());
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
android.view.View view = android.view.LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_folder_card, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String imageUri = images.get(position);
holder.bind(imageUri);
}
@Override
public int getItemCount() {
return images.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private final TextView tvFolderName;
private final Button btnRemove;
public ViewHolder(android.view.View itemView) {
super(itemView);
tvFolderName = itemView.findViewById(R.id.tvFolderName);
btnRemove = itemView.findViewById(R.id.btnRemove);
}
public void bind(String imageUri) {
// 显示图片 URI 的最后一部分
String displayName = imageUri.substring(imageUri.lastIndexOf('/') + 1);
if (displayName.isEmpty()) {
displayName = "图片";
}
tvFolderName.setText(displayName);
btnRemove.setOnClickListener(v -> {
if (removeListener != null) {
removeListener.onRemove(imageUri);
}
});
}
}
interface OnImageRemoveListener {
void onRemove(String imageUri);
}
}
}
@@ -24,6 +24,8 @@ import java.util.List;
import cn.hugh.bz.gk2.R;
import cn.hugh.bz.gk2.model.Album;
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.wallpaper.AlbumPreferences;
/**
@@ -274,9 +276,30 @@ public class AlbumManagementFragment extends Fragment {
// 相册信息(文件夹数量和图片数量)
int folderCount = album.getFolders() != null ? album.getFolders().size() : 0;
// TODO: 计算实际图片数量
int imageCount = folderCount; // 暂时使用文件夹数量
tvAlbumInfo.setText(folderCount + " 个文件夹 · " + imageCount + " 张图片");
// 计算直接添加的图片数量
int directImageCount = album.getImageUris() != null ? album.getImageUris().size() : 0;
// 总图片数量 = 直接添加的图片 + 文件夹中的图片(异步计算)
tvAlbumInfo.setText(folderCount + " 个文件夹 · " + directImageCount + " 张图片");
// 异步计算文件夹中的图片数量
if (folderCount > 0) {
new Thread(() -> {
ImageScanner scanner = new ImageScanner(context);
int totalImages = directImageCount;
for (String folder : album.getFolders()) {
List<WallpaperImage> images = scanner.scanFolder(folder);
totalImages += images.size();
}
final int finalTotal = totalImages;
// 更新 UI
if (tvAlbumInfo != null) {
tvAlbumInfo.post(() ->
tvAlbumInfo.setText(folderCount + " 个文件夹 · " + finalTotal + " 张图片")
);
}
scanner.shutdown();
}).start();
}
// 播放模式
String modeText = album.getPlayMode() == PlayMode.SEQUENTIAL ? "顺序" : "随机";
@@ -1,7 +1,6 @@
package cn.hugh.bz.gk2.utils;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
@@ -10,10 +9,14 @@ import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* 文件日志记录器
* 将关键日志写入外部存储,便于调试
* 将关键日志异步写入外部存储,避免阻塞主线程
*/
public class FileLogger {
private static final String TAG = "FileLogger";
@@ -24,6 +27,11 @@ public class FileLogger {
private final File logFile;
private final SimpleDateFormat dateFormat;
// 异步写入相关
private final LinkedBlockingQueue<String> logQueue;
private final ExecutorService writeExecutor;
private volatile boolean isRunning = true;
private FileLogger(Context context) {
// 使用外部应用目录,不需要存储权限
File logDir = new File(context.getExternalFilesDir(null), "logs");
@@ -33,6 +41,18 @@ public class FileLogger {
this.logFile = new File(logDir, LOG_FILE_NAME);
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
// 初始化异步写入队列和执行器
this.logQueue = new LinkedBlockingQueue<>(1000); // 最多缓存 1000 条日志
this.writeExecutor = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "FileLogger-Writer");
t.setDaemon(true);
t.setPriority(Thread.MIN_PRIORITY);
return t;
});
// 启动后台写入线程
startWriteLoop();
}
public static synchronized FileLogger getInstance(Context context) {
@@ -43,7 +63,27 @@ public class FileLogger {
}
/**
* 写入日志
* 启动后台写入循环
*/
private void startWriteLoop() {
writeExecutor.submit(() -> {
while (isRunning || !logQueue.isEmpty()) {
try {
// 等待日志,最多等待 1 秒
String logLine = logQueue.poll(1, TimeUnit.SECONDS);
if (logLine != null) {
writeToFileInternal(logLine);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
}
/**
* 写入日志(非阻塞)
*/
public void log(String tag, String message) {
String timestamp = dateFormat.format(new Date());
@@ -52,12 +92,15 @@ public class FileLogger {
// 同时输出到 Logcat
Log.i(tag, message);
// 写入文件
writeToFile(logLine);
// 异步写入文件(非阻塞)
if (!logQueue.offer(logLine)) {
// 队列满了,丢弃日志(避免阻塞)
Log.w(TAG, "Log queue full, dropping log");
}
}
/**
* 写入警告日志
* 写入警告日志(非阻塞)
*/
public void warn(String tag, String message) {
String timestamp = dateFormat.format(new Date());
@@ -66,12 +109,12 @@ public class FileLogger {
// 同时输出到 Logcat
Log.w(tag, message);
// 写入文件
writeToFile(logLine);
// 异步写入文件
logQueue.offer(logLine);
}
/**
* 写入错误日志
* 写入错误日志(非阻塞)
*/
public void error(String tag, String message, Throwable throwable) {
String timestamp = dateFormat.format(new Date());
@@ -81,14 +124,14 @@ public class FileLogger {
// 同时输出到 Logcat
Log.e(tag, message, throwable);
// 写入文件
writeToFile(logLine);
// 异步写入文件
logQueue.offer(logLine);
}
/**
* 写入文件
* 内部写入文件方法(在后台线程执行)
*/
private synchronized void writeToFile(String logLine) {
private void writeToFileInternal(String logLine) {
try {
// 检查文件大小,超过限制则清空
if (logFile.exists() && logFile.length() > MAX_LOG_SIZE) {
@@ -141,4 +184,34 @@ public class FileLogger {
return "读取日志失败: " + e.getMessage();
}
}
/**
* 关闭日志记录器,释放资源
* 应在应用退出时调用
*/
public void shutdown() {
isRunning = false;
if (writeExecutor != null && !writeExecutor.isShutdown()) {
writeExecutor.shutdown();
try {
// 等待队列中的日志写入完成
if (!writeExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
writeExecutor.shutdownNow();
}
} catch (InterruptedException e) {
writeExecutor.shutdownNow();
Thread.currentThread().interrupt();
}
}
Log.i(TAG, "FileLogger shutdown complete");
}
/**
* 获取队列状态(用于调试)
*/
public String getQueueStats() {
return "Queue size: " + logQueue.size() + "/1000";
}
}
@@ -2,127 +2,112 @@ package cn.hugh.bz.gk2.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import androidx.documentfile.provider.DocumentFile;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* 图片加载工具类
* 用于加载和优化图片
* 使用 Glide 实现高质量图片加载,支持缓存和内存管理
*/
public class ImageLoader {
private static final String TAG = "ImageLoader";
private static final int LOAD_TIMEOUT_SECONDS = 30;
private final Context context;
public ImageLoader(Context context) {
this.context = context;
this.context = context.getApplicationContext();
}
/**
* 加载图片并进行采样优化
* 加载图片并进行优化
* 注意:此方法会阻塞线程,请勿在主线程调用
*
* @param uriString 图片 URI 字符串
* @param uriString 图片 URI 字符串(支持 content:// 和文件路径)
* @param reqWidth 请求的宽度
* @param reqHeight 请求的高度
* @return Bitmap 对象,失败返回 null
* @return Bitmap 对象,失败返回 null。调用者负责回收 Bitmap
*/
public Bitmap loadImage(String uriString, int reqWidth, int reqHeight) {
if (uriString == null || uriString.isEmpty()) {
Log.w(TAG, "loadImage: uriString is null or empty");
return null;
}
try {
Object loadSource;
if (uriString.startsWith("content://")) {
// 使用 DocumentFile API
Uri uri = Uri.parse(uriString);
DocumentFile file = DocumentFile.fromSingleUri(context, uri);
if (file != null && file.exists()) {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
if (inputStream != null) {
Bitmap bitmap = decodeSampledBitmapFromStream(inputStream, reqWidth, reqHeight);
inputStream.close();
return bitmap;
}
}
loadSource = Uri.parse(uriString);
} else {
// 使用传统 File API
File file = new File(uriString);
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
Bitmap bitmap = decodeSampledBitmapFromStream(fis, reqWidth, reqHeight);
fis.close();
if (!file.exists()) {
Log.e(TAG, "File not found: " + uriString);
return null;
}
loadSource = file;
}
RequestOptions options = new RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888) // 高色彩质量
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.override(reqWidth, reqHeight)
.centerCrop();
Bitmap bitmap = Glide.with(context)
.asBitmap()
.load(loadSource)
.apply(options)
.submit()
.get(LOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS);
if (bitmap != null) {
Log.i(TAG, "Loaded image: " + uriString + ", size: " +
bitmap.getWidth() + "x" + bitmap.getHeight() +
", config: " + bitmap.getConfig());
}
return bitmap;
}
}
} catch (ExecutionException e) {
Log.e(TAG, "ExecutionException loading image: " + uriString, e);
} catch (InterruptedException e) {
Log.e(TAG, "InterruptedException loading image: " + uriString, e);
Thread.currentThread().interrupt();
} catch (TimeoutException e) {
Log.e(TAG, "TimeoutException loading image (>" + LOAD_TIMEOUT_SECONDS + "s): " + uriString, e);
} catch (Exception e) {
Log.e(TAG, "Error loading image: " + uriString, e);
Log.e(TAG, "Unexpected error loading image: " + uriString, e);
}
return null;
}
/**
* 从输入流中加载并采样图片
* 清除 Glide 缓存
* 注意:磁盘缓存清理需要在后台线程执行
*/
private Bitmap decodeSampledBitmapFromStream(InputStream inputStream, int reqWidth, int reqHeight) {
public void clearCache() {
// 清除内存缓存(主线程)
Glide.get(context).clearMemory();
// 清除磁盘缓存(后台线程)
new Thread(() -> {
try {
// 第一次解析:只获取图片尺寸
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
byte[] buffer = readAllBytes(inputStream);
BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
// 计算采样率
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 第二次解析:加载图片
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
Glide.get(context).clearDiskCache();
Log.i(TAG, "Disk cache cleared");
} catch (Exception e) {
Log.e(TAG, "Error decoding bitmap from stream", e);
return null;
Log.e(TAG, "Error clearing disk cache", e);
}
}
/**
* 读取输入流的所有字节
*/
private byte[] readAllBytes(InputStream inputStream) throws Exception {
java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384]; // 16KB buffer
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
}
/**
* 计算采样率
*/
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;
// 计算最大的 2 的幂次方,使得采样后的尺寸大于等于请求尺寸
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}).start();
}
}
@@ -286,6 +286,155 @@ public class ImageScanner {
void onScanError(String error);
}
/**
* 扫描进度回调接口
*/
public interface ScanProgressCallback {
void onProgress(int current, int total, String currentFile);
void onComplete(List<WallpaperImage> images);
void onError(String error);
}
/**
* 带进度回调的文件夹扫描(异步)
* 每扫描 10 个文件报告一次进度
*
* @param folderPath 文件夹路径
* @param callback 进度回调
*/
public void scanFolderWithProgress(String folderPath, ScanProgressCallback callback) {
if (callback == null) {
return;
}
new Thread(() -> {
try {
List<WallpaperImage> images;
if (folderPath.startsWith("content://")) {
images = scanDocumentFolderWithProgress(folderPath, callback);
} else {
images = scanFileFolderWithProgress(folderPath, callback);
}
// 保存到缓存
jsonHelper.saveIndex(folderPath, images);
memoryCache.put(folderPath, images);
lastScanTime.put(folderPath, System.currentTimeMillis());
callback.onComplete(images);
} catch (Exception e) {
Log.e(TAG, "Error scanning folder with progress: " + folderPath, e);
callback.onError(e.getMessage());
}
}).start();
}
/**
* 带进度的 DocumentFile 文件夹扫描
*/
private List<WallpaperImage> scanDocumentFolderWithProgress(String folderPath, ScanProgressCallback callback) {
List<WallpaperImage> images = new ArrayList<>(1000);
try {
Uri folderUri = Uri.parse(folderPath);
DocumentFile folder = DocumentFile.fromTreeUri(context, folderUri);
if (folder == null || !folder.exists()) {
Log.e(TAG, "Folder not found: " + folderPath);
return images;
}
DocumentFile[] files = folder.listFiles();
if (files == null || files.length == 0) {
return images;
}
int total = files.length;
int progressInterval = 10; // 每 10 个文件报告一次进度
for (int i = 0; i < files.length && images.size() < MAX_SCAN_COUNT; i++) {
DocumentFile file = files[i];
// 报告进度
if (i % progressInterval == 0) {
String fileName = file.getName();
callback.onProgress(i, total, fileName != null ? fileName : "");
}
if (file.isFile() && isImageFileFast(file)) {
WallpaperImage image = new WallpaperImage(
file.getUri().toString(),
folderPath,
file.getName(),
file.lastModified(),
file.length()
);
images.add(image);
}
}
// 最终进度
callback.onProgress(total, total, "");
} catch (Exception e) {
Log.e(TAG, "Error scanning folder with progress: " + folderPath, e);
}
return images;
}
/**
* 带进度的 File 文件夹扫描
*/
private List<WallpaperImage> scanFileFolderWithProgress(String folderPath, ScanProgressCallback callback) {
List<WallpaperImage> images = new ArrayList<>(1000);
try {
File folder = new File(folderPath);
if (!folder.exists() || !folder.isDirectory()) {
Log.e(TAG, "Folder not found or not a directory: " + folderPath);
return images;
}
File[] files = folder.listFiles();
if (files == null || files.length == 0) {
return images;
}
int total = files.length;
int progressInterval = 10; // 每 10 个文件报告一次进度
for (int i = 0; i < files.length && images.size() < MAX_SCAN_COUNT; i++) {
File file = files[i];
// 报告进度
if (i % progressInterval == 0) {
callback.onProgress(i, total, file.getName());
}
if (file.isFile() && isImageFileFast(file)) {
WallpaperImage image = new WallpaperImage(
file.getAbsolutePath(),
folderPath,
file.getName(),
file.lastModified(),
file.length()
);
images.add(image);
}
}
// 最终进度
callback.onProgress(total, total, "");
} catch (Exception e) {
Log.e(TAG, "Error scanning folder with progress: " + folderPath, e);
}
return images;
}
public WallpaperImage getImageAtIndex(List<String> folders, int index) {
List<WallpaperImage> allImages = loadAllImages(folders);
@@ -0,0 +1,34 @@
package cn.hugh.bz.gk2.utils;
import android.content.Context;
import androidx.annotation.NonNull;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.request.RequestOptions;
/**
* Glide 全局配置模块
* 配置高色彩质量和缓存策略
*/
@GlideModule
public final class WallpaperGlideModule extends AppGlideModule {
@Override
public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
builder.setDefaultRequestOptions(
new RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888) // 高色彩质量,避免色带
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
);
}
@Override
public boolean isManifestParsingEnabled() {
return false;
}
}
@@ -10,6 +10,9 @@ import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;
import java.util.ArrayList;
import java.util.List;
import cn.hugh.bz.gk2.model.Album;
import cn.hugh.bz.gk2.model.AppConfig;
import cn.hugh.bz.gk2.model.PlayMode;
@@ -65,12 +68,15 @@ public class AutoWallpaperService extends WallpaperService {
private final AlbumPreferences albumPrefs;
private final Handler handler;
private final cn.hugh.bz.gk2.utils.FileLogger fileLogger;
private final java.util.concurrent.ExecutorService backgroundExecutor; // 后台线程执行器
private int width;
private int height;
private boolean visible = false;
private boolean forceChangeNext = false;
private boolean scheduledNext = false;
private android.graphics.Bitmap currentBitmap; // 跟踪当前 Bitmap,用于回收
private volatile boolean isLoadingWallpaper = false; // 防止重复加载
public WallpaperEngine() {
this.imageLoader = new ImageLoader(AutoWallpaperService.this);
@@ -79,6 +85,12 @@ public class AutoWallpaperService extends WallpaperService {
this.albumPrefs = new AlbumPreferences(AutoWallpaperService.this);
this.handler = new Handler(Looper.getMainLooper());
this.fileLogger = cn.hugh.bz.gk2.utils.FileLogger.getInstance(AutoWallpaperService.this);
// 创建单线程后台执行器,用于扫描和加载图片
this.backgroundExecutor = java.util.concurrent.Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "WallpaperLoader");
t.setPriority(Thread.MIN_PRIORITY);
return t;
});
}
@Override
@@ -116,6 +128,16 @@ public class AutoWallpaperService extends WallpaperService {
public void onSurfaceDestroyed(android.view.SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
this.visible = false;
// 回收 Bitmap 释放内存
if (currentBitmap != null && !currentBitmap.isRecycled()) {
currentBitmap.recycle();
currentBitmap = null;
Log.i(TAG, "Bitmap recycled on surface destroyed");
}
// 关闭后台执行器
if (backgroundExecutor != null && !backgroundExecutor.isShutdown()) {
backgroundExecutor.shutdownNow();
}
}
public void refreshWallpaper(boolean forceChange, boolean scheduled) {
@@ -139,27 +161,26 @@ public class AutoWallpaperService extends WallpaperService {
}
private void drawWallpaper() {
// 防止重复加载
if (isLoadingWallpaper) {
Log.i(TAG, "Already loading wallpaper, skipping");
return;
}
android.view.SurfaceHolder holder = getSurfaceHolder();
if (holder == null || !holder.getSurface().isValid()) {
return;
}
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
// Clear canvas
canvas.drawColor(Color.BLACK);
// Load current wallpaper
// Load current wallpaper config
AppConfig config = prefs.loadConfig();
if (!config.isEnabled() || config.getSelectedFolders().isEmpty()) {
drawPlaceholder(canvas);
if (!config.isEnabled() || (config.getSelectedFolders().isEmpty() && (config.getImageUris() == null || config.getImageUris().isEmpty()))) {
// 直接绘制占位符(不需要后台线程)
drawPlaceholderSync(holder);
return;
}
WallpaperImage image;
// 核心逻辑:根据触发来源决定是否更换壁纸
boolean shouldChange = false;
@@ -169,71 +190,187 @@ public class AutoWallpaperService extends WallpaperService {
fileLogger.log(TAG, statusMsg);
if (forceChangeNext) {
// 用户主动触发(如点击"立即更换"):强制更换
shouldChange = true;
String msg = "Forced change by user";
Log.i(TAG, msg);
fileLogger.log(TAG, msg);
fileLogger.log(TAG, "Forced change by user");
} else if (scheduledNext) {
// 定时器触发:必须更换(这是主要的自动更换机制)
shouldChange = true;
String msg = "Scheduled change";
Log.i(TAG, msg);
fileLogger.log(TAG, msg);
fileLogger.log(TAG, "Scheduled change");
} else if (config.isChangeOnReturnToHome()) {
// 返回桌面触发:根据配置决定
shouldChange = true;
String msg = "Change on return to home";
Log.i(TAG, msg);
fileLogger.log(TAG, msg);
}
if (shouldChange) {
// 获取下一张壁纸
image = getNextWallpaper(config);
if (image != null) {
String msg = "Drawing new wallpaper: " + image.getUri();
Log.i(TAG, msg);
fileLogger.log(TAG, msg);
drawImage(canvas, image.getUri());
prefs.saveConfig(config);
prefs.saveLastUri(image.getUri());
} else {
String warn = "No more wallpapers available";
Log.w(TAG, warn);
fileLogger.warn(TAG, warn);
drawPlaceholder(canvas);
}
} else {
// 不更换:使用当前壁纸
String msg = "Reusing current wallpaper";
Log.i(TAG, msg);
fileLogger.log(TAG, msg);
String lastUri = prefs.getLastUri();
if (lastUri != null) {
// 复用当前壁纸
drawImage(canvas, lastUri);
} else {
// 没有当前壁纸,使用下一张
Log.i(TAG, "No current wallpaper, getting next one");
image = getNextWallpaper(config);
if (image != null) {
drawImage(canvas, image.getUri());
prefs.saveConfig(config);
prefs.saveLastUri(image.getUri());
} else {
drawPlaceholder(canvas);
}
}
fileLogger.log(TAG, "Change on return to home");
}
// 重置标志
final boolean needChange = shouldChange;
forceChangeNext = false;
scheduledNext = false;
// 如果不需要更换且有缓存的 Bitmap,直接绘制
if (!needChange && currentBitmap != null && !currentBitmap.isRecycled()) {
drawBitmapSync(holder, currentBitmap);
return;
}
// 如果不需要更换,尝试使用上次的 URI
if (!needChange) {
String lastUri = prefs.getLastUri();
if (lastUri != null) {
// 在后台加载图片
loadAndDrawImageAsync(holder, lastUri, config, false);
return;
}
}
// 需要更换壁纸或没有缓存,在后台线程执行扫描和加载
isLoadingWallpaper = true;
backgroundExecutor.execute(() -> {
try {
WallpaperImage image = getNextWallpaper(config);
if (image != null) {
String msg = "Loading new wallpaper: " + image.getUri();
Log.i(TAG, msg);
fileLogger.log(TAG, msg);
// 在后台线程加载图片
android.graphics.Bitmap bitmap = imageLoader.loadImage(image.getUri(), width, height);
if (bitmap != null) {
// 切换到主线程绘制
handler.post(() -> {
// 回收旧 Bitmap
if (currentBitmap != null && !currentBitmap.isRecycled()) {
currentBitmap.recycle();
}
currentBitmap = bitmap;
drawBitmapSync(holder, bitmap);
// 保存配置和历史
prefs.saveConfig(config);
prefs.saveLastUri(image.getUri());
// 保存到历史记录
Album activeAlbum = albumPrefs.getActiveAlbum();
if (activeAlbum != null) {
historyManager.addHistory(
image.getUri(),
activeAlbum.getId(),
activeAlbum.getName(),
bitmap
);
}
isLoadingWallpaper = false;
});
} else {
handler.post(() -> {
drawPlaceholderSync(holder);
isLoadingWallpaper = false;
});
}
} else {
handler.post(() -> {
fileLogger.warn(TAG, "No more wallpapers available");
drawPlaceholderSync(holder);
isLoadingWallpaper = false;
});
}
} catch (Exception e) {
Log.e(TAG, "Error drawing wallpaper", e);
Log.e(TAG, "Error loading wallpaper", e);
handler.post(() -> {
isLoadingWallpaper = false;
});
}
});
}
/**
* 异步加载并绘制图片
*/
private void loadAndDrawImageAsync(android.view.SurfaceHolder holder, String uri, AppConfig config, boolean saveToHistory) {
isLoadingWallpaper = true;
backgroundExecutor.execute(() -> {
try {
android.graphics.Bitmap bitmap = imageLoader.loadImage(uri, width, height);
if (bitmap != null) {
handler.post(() -> {
if (currentBitmap != null && !currentBitmap.isRecycled()) {
currentBitmap.recycle();
}
currentBitmap = bitmap;
drawBitmapSync(holder, bitmap);
isLoadingWallpaper = false;
});
} else {
handler.post(() -> {
drawPlaceholderSync(holder);
isLoadingWallpaper = false;
});
}
} catch (Exception e) {
Log.e(TAG, "Error loading image async", e);
handler.post(() -> isLoadingWallpaper = false);
}
});
}
/**
* 同步绘制 Bitmap 到 Surface
*/
private void drawBitmapSync(android.view.SurfaceHolder holder, android.graphics.Bitmap bitmap) {
if (holder == null || !holder.getSurface().isValid() || bitmap == null || bitmap.isRecycled()) {
return;
}
Canvas canvas = null;
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();
float scale = Math.max(scaleX, scaleY);
float scaledWidth = bitmap.getWidth() * scale;
float scaledHeight = bitmap.getHeight() * scale;
float left = (width - scaledWidth) / 2f;
float top = (height - scaledHeight) / 2f;
canvas.drawBitmap(bitmap, null,
new RectF(left, top, left + scaledWidth, top + scaledHeight),
null);
}
} catch (Exception e) {
Log.e(TAG, "Error drawing bitmap", e);
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
/**
* 同步绘制占位符
*/
private void drawPlaceholderSync(android.view.SurfaceHolder holder) {
if (holder == null || !holder.getSurface().isValid()) {
return;
}
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
canvas.drawColor(Color.BLACK);
drawPlaceholder(canvas);
}
} catch (Exception e) {
Log.e(TAG, "Error drawing placeholder", e);
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
@@ -242,22 +379,98 @@ public class AutoWallpaperService extends WallpaperService {
}
private WallpaperImage getNextWallpaper(AppConfig config) {
ImageScanner scanner = new ImageScanner(AutoWallpaperService.this);
String lastUri = prefs.getLastUri();
String msg = "getNextWallpaper: playMode=" + config.getPlayMode() + ", lastUri=" + lastUri;
// 分别处理文件夹和直接图片 URI
List<WallpaperImage> allImages = new ArrayList<>();
// 1. 从文件夹扫描图片
List<String> folders = config.getSelectedFolders();
String folderLog = "Folder check: folders=" + (folders != null ? folders.size() : "null");
Log.i(TAG, folderLog);
fileLogger.log(TAG, folderLog);
if (folders != null && !folders.isEmpty()) {
ImageScanner scanner = new ImageScanner(AutoWallpaperService.this);
for (String folder : folders) {
String scanMsg = "Scanning folder: " + folder;
Log.i(TAG, scanMsg);
fileLogger.log(TAG, scanMsg);
List<WallpaperImage> folderImages = scanner.scanFolder(folder);
String scanResult = "Folder scan result: " + folderImages.size() + " images";
Log.i(TAG, scanResult);
fileLogger.log(TAG, scanResult);
allImages.addAll(folderImages);
}
}
// 2. 添加直接选择的图片 URI
List<String> imageUris = config.getImageUris();
String imageUriLog = "ImageUris check: imageUris=" + (imageUris != null ? imageUris.size() : "null");
Log.i(TAG, imageUriLog);
fileLogger.log(TAG, imageUriLog);
if (imageUris != null && !imageUris.isEmpty()) {
String processingMsg = "Processing " + imageUris.size() + " direct image URIs";
Log.i(TAG, processingMsg);
fileLogger.log(TAG, processingMsg);
for (int i = 0; i < imageUris.size(); i++) {
String uri = imageUris.get(i);
String uriMsg = " [" + i + "] " + uri;
Log.i(TAG, uriMsg);
fileLogger.log(TAG, uriMsg);
// 为直接图片 URI 创建 WallpaperImage 对象
String displayName = extractDisplayName(uri);
WallpaperImage image = new WallpaperImage(uri, null, displayName, System.currentTimeMillis(), 0);
allImages.add(image);
String addedMsg = " Added: " + displayName;
Log.i(TAG, addedMsg);
fileLogger.log(TAG, addedMsg);
}
} else {
String noImageMsg = "No direct image URIs found or imageUris is null/empty";
Log.w(TAG, noImageMsg);
fileLogger.warn(TAG, noImageMsg);
}
String msg = "getNextWallpaper: playMode=" + config.getPlayMode() + ", totalImages=" + allImages.size() +
", folders=" + (folders != null ? folders.size() : 0) +
", directImages=" + (imageUris != null ? imageUris.size() : 0) +
", lastUri=" + lastUri;
Log.i(TAG, msg);
fileLogger.log(TAG, msg);
if (allImages.isEmpty()) {
String warn = "getNextWallpaper: no images available!";
Log.w(TAG, warn);
fileLogger.warn(TAG, warn);
return null;
}
WallpaperImage image = null;
if (config.getPlayMode() == PlayMode.SEQUENTIAL) {
// Sequential mode
int index = config.getCurrentIndex();
String seqMsg = "getNextWallpaper: sequential mode, index=" + index;
// Reset index if out of bounds (循环播放)
if (index >= allImages.size() || index < 0) {
index = 0;
config.setCurrentIndex(0);
String resetMsg = "getNextWallpaper: index out of bounds, reset to 0";
Log.i(TAG, resetMsg);
fileLogger.log(TAG, resetMsg);
}
String seqMsg = "getNextWallpaper: sequential mode, index=" + index + ", total=" + allImages.size();
Log.i(TAG, seqMsg);
fileLogger.log(TAG, seqMsg);
image = scanner.getImageAtIndex(config.getSelectedFolders(), index);
if (image != null) {
if (index >= 0 && index < allImages.size()) {
image = allImages.get(index);
config.setCurrentIndex(index + 1);
String selectedMsg = "getNextWallpaper: selected image at index " + index + ": " + image.getUri();
Log.i(TAG, selectedMsg);
@@ -268,7 +481,23 @@ public class AutoWallpaperService extends WallpaperService {
String randMsg = "getNextWallpaper: random mode, excluding: " + lastUri;
Log.i(TAG, randMsg);
fileLogger.log(TAG, randMsg);
image = scanner.getRandomImage(config.getSelectedFolders(), lastUri);
// Filter out excluded image
List<WallpaperImage> candidates = new ArrayList<>();
for (WallpaperImage img : allImages) {
if (!img.getUri().equals(lastUri)) {
candidates.add(img);
}
}
if (candidates.isEmpty()) {
// All images are the same as excluded, return any
image = allImages.get(0);
} else {
java.util.Random random = new java.util.Random();
image = candidates.get(random.nextInt(candidates.size()));
}
if (image != null) {
String selectedMsg = "getNextWallpaper: selected random image: " + image.getUri();
Log.i(TAG, selectedMsg);
@@ -283,47 +512,28 @@ public class AutoWallpaperService extends WallpaperService {
}
return image;
}
/**
* 从图片 URI 中提取显示名称
*/
private String extractDisplayName(String uriString) {
try {
android.net.Uri uri = android.net.Uri.parse(uriString);
String path = uri.getLastPathSegment();
if (path != null && path.contains(":")) {
String[] parts = path.split(":");
if (parts.length > 1) path = parts[1];
}
private void drawImage(Canvas canvas, String uri) {
Log.d(TAG, "Drawing image: " + uri + ", canvas size: " + width + "x" + height);
android.graphics.Bitmap bitmap = imageLoader.loadImage(uri, width, height);
if (bitmap != null) {
Log.d(TAG, "Bitmap loaded: " + bitmap.getWidth() + "x" + bitmap.getHeight());
// Calculate scale to cover the entire screen while maintaining aspect ratio
float scaleX = (float) width / bitmap.getWidth();
float scaleY = (float) height / bitmap.getHeight();
float scale = Math.max(scaleX, scaleY);
float scaledWidth = bitmap.getWidth() * scale;
float scaledHeight = bitmap.getHeight() * scale;
// Center the image
float left = (width - scaledWidth) / 2f;
float top = (height - scaledHeight) / 2f;
Log.d(TAG, "Drawing at: left=" + left + ", top=" + top +
", size=" + scaledWidth + "x" + scaledHeight);
canvas.drawBitmap(bitmap, null,
new RectF(left, top, left + scaledWidth, top + scaledHeight),
null);
// 保存到历史记录
Album activeAlbum = albumPrefs.getActiveAlbum();
if (activeAlbum != null) {
historyManager.addHistory(
uri,
activeAlbum.getId(),
activeAlbum.getName(),
bitmap
);
}
} else {
Log.e(TAG, "Failed to load bitmap: " + uri);
if (path != null && path.contains("/")) {
String[] segments = path.split("/");
path = segments[segments.length - 1];
}
return path != null ? path : "选中图片";
} catch (Exception e) {
return "选中图片";
}
}
private void drawPlaceholder(Canvas canvas) {
// Draw placeholder text
@@ -2,109 +2,112 @@ package cn.hugh.bz.gk2.wallpaper;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* 壁纸图片加载器
* 使用 Glide 实现高质量图片加载,支持缓存和内存管理
*/
public class ImageLoader {
private static final String TAG = "ImageLoader";
private static final int LOAD_TIMEOUT_SECONDS = 30;
private final Context context;
public ImageLoader(Context context) {
this.context = context;
this.context = context.getApplicationContext();
}
/**
* 同步加载图片
* 注意:此方法会阻塞线程,请勿在主线程调用
*
* @param uriString 图片 URI 字符串(支持 content:// 和文件路径)
* @param maxWidth 目标宽度
* @param maxHeight 目标高度
* @return Bitmap 对象,加载失败返回 null。调用者负责回收 Bitmap
*/
public Bitmap loadImage(String uriString, int maxWidth, int maxHeight) {
if (uriString == null || uriString.isEmpty()) {
Log.w(TAG, "loadImage: uriString is null or empty");
return null;
}
try {
// 检查是否是 content:// URI
Object loadSource;
if (uriString.startsWith("content://")) {
return loadFromUri(Uri.parse(uriString), maxWidth, maxHeight);
loadSource = Uri.parse(uriString);
} else {
return loadFromFile(uriString, maxWidth, maxHeight);
}
} catch (Exception e) {
Log.e(TAG, "Failed to load image: " + uriString, e);
return null;
}
}
private Bitmap loadFromUri(Uri uri, int maxWidth, int maxHeight) {
try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
// Decode bitmap with inSampleSize
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
// Reopen stream for actual decode
try (InputStream inputStream2 = context.getContentResolver().openInputStream(uri)) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream2, null, options);
Log.i(TAG, "Loaded image from URI: " + uri + ", size: " +
(bitmap != null ? bitmap.getWidth() + "x" + bitmap.getHeight() : "null"));
return bitmap;
}
} catch (Exception e) {
Log.e(TAG, "Failed to load from URI: " + uri, e);
return null;
}
}
private Bitmap loadFromFile(String filePath, int maxWidth, int maxHeight) {
try {
File file = new File(filePath);
File file = new File(uriString);
if (!file.exists()) {
Log.e(TAG, "File not found: " + filePath);
Log.e(TAG, "File not found: " + uriString);
return null;
}
loadSource = file;
}
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
RequestOptions options = new RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888) // 高色彩质量
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.override(maxWidth, maxHeight)
.centerCrop();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
Bitmap bitmap = Glide.with(context)
.asBitmap()
.load(loadSource)
.apply(options)
.submit()
.get(LOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS);
// Decode bitmap with inSampleSize
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
if (bitmap != null) {
Log.i(TAG, "Loaded image: " + uriString + ", size: " +
bitmap.getWidth() + "x" + bitmap.getHeight() +
", config: " + bitmap.getConfig());
}
return bitmap;
} catch (ExecutionException e) {
Log.e(TAG, "ExecutionException loading image: " + uriString, e);
} catch (InterruptedException e) {
Log.e(TAG, "InterruptedException loading image: " + uriString, e);
Thread.currentThread().interrupt();
} catch (TimeoutException e) {
Log.e(TAG, "TimeoutException loading image (>" + LOAD_TIMEOUT_SECONDS + "s): " + uriString, e);
} catch (Exception e) {
Log.e(TAG, "Failed to load from file: " + filePath, e);
Log.e(TAG, "Unexpected error loading image: " + uriString, e);
}
return null;
}
/**
* 清除 Glide 缓存
* 注意:磁盘缓存清理需要在后台线程执行
*/
public void clearCache() {
// 清除内存缓存(主线程)
Glide.get(context).clearMemory();
// 清除磁盘缓存(后台线程)
new Thread(() -> {
try {
Glide.get(context).clearDiskCache();
Log.i(TAG, "Disk cache cleared");
} catch (Exception e) {
Log.e(TAG, "Error clearing disk cache", e);
}
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;
}).start();
}
}