feat: 重构为 Fragment + 底部导航架构,新增当前壁纸页面和现代化 UI 设计
- 使用 ViewPager2 + BottomNavigationView 实现三个标签页(主页、壁纸、设置) - 主页采用 Material Design 3 风格,卡片式布局,视觉层次清晰 - 新增当前壁纸页面,支持大图预览、立即更换、下一张切换、相册打开 - 设置页面改为实时保存,移除保存按钮提升用户体验 - 修复立即更换和定时器功能,统一壁纸更换逻辑 - 新增 ImageLoader 工具类,优化图片加载和内存管理 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a5797b08a8
commit
24dd91aceb
29 files changed
+1782
-506
No files matched your search
@@ -9,17 +9,27 @@ 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";
|
||||
// 内部广播:用于通知壁纸服务更换壁纸(避免循环)
|
||||
private static final String ACTION_REFRESH_WALLPAPER_SERVICE = "cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER_SERVICE";
|
||||
public static final String EXTRA_FORCE_CHANGE = "force_change";
|
||||
|
||||
@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);
|
||||
// 提取 force_change 标志,默认为 true(用户主动触发的更换)
|
||||
boolean forceChange = intent.getBooleanExtra(EXTRA_FORCE_CHANGE, true);
|
||||
Log.i(TAG, "Force change: " + forceChange);
|
||||
|
||||
// Schedule next change
|
||||
// 转发广播给 AutoWallpaperService,使用不同的 ACTION 避免循环
|
||||
Intent serviceIntent = new Intent(ACTION_REFRESH_WALLPAPER_SERVICE);
|
||||
serviceIntent.putExtra(EXTRA_FORCE_CHANGE, forceChange);
|
||||
context.sendBroadcast(serviceIntent);
|
||||
|
||||
// 如果服务已启用,调度下一次更换
|
||||
cn.hugh.bz.gk2.wallpaper.WallpaperPreferences prefs =
|
||||
new cn.hugh.bz.gk2.wallpaper.WallpaperPreferences(context);
|
||||
cn.hugh.bz.gk2.model.AppConfig config = prefs.loadConfig();
|
||||
@@ -32,11 +42,3 @@ public class WallpaperChangeReceiver extends BroadcastReceiver {
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package cn.hugh.bz.gk2.ui;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.Button;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.Fragment;
|
||||
|
||||
import cn.hugh.bz.gk2.R;
|
||||
import cn.hugh.bz.gk2.utils.ImageLoader;
|
||||
import cn.hugh.bz.gk2.wallpaper.WallpaperPreferences;
|
||||
|
||||
/**
|
||||
* 当前壁纸 Fragment
|
||||
* 显示当前壁纸大图预览、壁纸信息和操作按钮
|
||||
*/
|
||||
public class CurrentWallpaperFragment extends Fragment {
|
||||
|
||||
private ImageView ivWallpaper;
|
||||
private TextView tvWallpaperPath;
|
||||
private TextView tvWallpaperSize;
|
||||
private Button btnChangeNow;
|
||||
private Button btnNext;
|
||||
private Button btnOpenInGallery;
|
||||
|
||||
private WallpaperPreferences prefs;
|
||||
private ImageLoader imageLoader;
|
||||
private cn.hugh.bz.gk2.utils.ImageScanner scanner;
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
|
||||
return inflater.inflate(R.layout.fragment_current_wallpaper, container, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
|
||||
prefs = new WallpaperPreferences(requireContext());
|
||||
imageLoader = new ImageLoader(requireContext());
|
||||
scanner = new cn.hugh.bz.gk2.utils.ImageScanner(requireContext());
|
||||
|
||||
initViews(view);
|
||||
loadCurrentWallpaper();
|
||||
}
|
||||
|
||||
private void initViews(View view) {
|
||||
ivWallpaper = view.findViewById(R.id.ivWallpaper);
|
||||
tvWallpaperPath = view.findViewById(R.id.tvWallpaperPath);
|
||||
tvWallpaperSize = view.findViewById(R.id.tvWallpaperSize);
|
||||
btnChangeNow = view.findViewById(R.id.btnChangeNow);
|
||||
btnNext = view.findViewById(R.id.btnNext);
|
||||
btnOpenInGallery = view.findViewById(R.id.btnOpenInGallery);
|
||||
|
||||
btnChangeNow.setOnClickListener(v -> changeWallpaperNow());
|
||||
btnNext.setOnClickListener(v -> showNextWallpaper());
|
||||
btnOpenInGallery.setOnClickListener(v -> openInGallery());
|
||||
ivWallpaper.setOnClickListener(v -> openInGallery());
|
||||
}
|
||||
|
||||
private void loadCurrentWallpaper() {
|
||||
String currentUri = prefs.getLastUri();
|
||||
|
||||
if (currentUri == null || currentUri.isEmpty()) {
|
||||
showNoWallpaper();
|
||||
return;
|
||||
}
|
||||
|
||||
// 显示加载状态
|
||||
tvWallpaperPath.setText("正在加载壁纸...");
|
||||
|
||||
// 在后台线程加载图片
|
||||
new Thread(() -> {
|
||||
Bitmap bitmap = imageLoader.loadImage(currentUri, 1080, 1920);
|
||||
|
||||
requireActivity().runOnUiThread(() -> {
|
||||
if (bitmap != null) {
|
||||
ivWallpaper.setImageBitmap(bitmap);
|
||||
tvWallpaperPath.setText(getDisplayName(currentUri));
|
||||
tvWallpaperSize.setText(bitmap.getWidth() + " x " + bitmap.getHeight());
|
||||
} else {
|
||||
showError();
|
||||
}
|
||||
});
|
||||
}).start();
|
||||
}
|
||||
|
||||
private void showNoWallpaper() {
|
||||
ivWallpaper.setImageDrawable(null);
|
||||
tvWallpaperPath.setText("尚未设置壁纸");
|
||||
tvWallpaperSize.setText("");
|
||||
btnChangeNow.setEnabled(false);
|
||||
btnNext.setEnabled(false);
|
||||
btnOpenInGallery.setEnabled(false);
|
||||
}
|
||||
|
||||
private void showError() {
|
||||
ivWallpaper.setImageDrawable(null);
|
||||
tvWallpaperPath.setText("加载壁纸失败");
|
||||
tvWallpaperSize.setText("");
|
||||
btnChangeNow.setEnabled(false);
|
||||
btnNext.setEnabled(false);
|
||||
btnOpenInGallery.setEnabled(false);
|
||||
}
|
||||
|
||||
private void changeWallpaperNow() {
|
||||
cn.hugh.bz.gk2.model.AppConfig config = prefs.loadConfig();
|
||||
|
||||
if (config.getSelectedFolders().isEmpty()) {
|
||||
Toast.makeText(requireContext(), "请先选择文件夹", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
// 直接获取下一张壁纸,与"下一张"按钮相同的逻辑
|
||||
cn.hugh.bz.gk2.model.WallpaperImage nextImage = null;
|
||||
String lastUri = prefs.getLastUri();
|
||||
|
||||
if (config.getPlayMode() == cn.hugh.bz.gk2.model.PlayMode.SEQUENTIAL) {
|
||||
// 顺序模式:获取下一张
|
||||
int index = config.getCurrentIndex();
|
||||
nextImage = scanner.getImageAtIndex(config.getSelectedFolders(), index);
|
||||
if (nextImage != null) {
|
||||
config.setCurrentIndex(index + 1);
|
||||
}
|
||||
} else {
|
||||
// 随机模式:随机选择一张
|
||||
nextImage = scanner.getRandomImage(config.getSelectedFolders(), lastUri);
|
||||
}
|
||||
|
||||
if (nextImage != null) {
|
||||
// 保存新壁纸配置
|
||||
prefs.saveConfig(config);
|
||||
prefs.saveLastUri(nextImage.getUri());
|
||||
|
||||
// 发送广播通知壁纸服务更新显示
|
||||
Intent intent = new Intent("cn.hugh.bz.gk2.ACTION_CHANGE_WALLPAPER");
|
||||
intent.putExtra("force_change", false); // 只通知更新,不重新选择壁纸
|
||||
requireActivity().sendBroadcast(intent);
|
||||
|
||||
Toast.makeText(requireContext(), "壁纸已更换", Toast.LENGTH_SHORT).show();
|
||||
|
||||
// 延迟刷新预览
|
||||
new Handler(Looper.getMainLooper()).postDelayed(() -> {
|
||||
loadCurrentWallpaper();
|
||||
}, 500);
|
||||
} else {
|
||||
Toast.makeText(requireContext(), "没有更多壁纸了", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void showNextWallpaper() {
|
||||
cn.hugh.bz.gk2.model.AppConfig config = prefs.loadConfig();
|
||||
|
||||
if (config.getSelectedFolders().isEmpty()) {
|
||||
Toast.makeText(requireContext(), "请先选择文件夹", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
cn.hugh.bz.gk2.model.WallpaperImage nextImage = null;
|
||||
String lastUri = prefs.getLastUri();
|
||||
|
||||
if (config.getPlayMode() == cn.hugh.bz.gk2.model.PlayMode.SEQUENTIAL) {
|
||||
// 顺序模式:获取下一张
|
||||
int index = config.getCurrentIndex();
|
||||
nextImage = scanner.getImageAtIndex(config.getSelectedFolders(), index);
|
||||
if (nextImage != null) {
|
||||
config.setCurrentIndex(index + 1);
|
||||
}
|
||||
} else {
|
||||
// 随机模式:随机选择一张
|
||||
nextImage = scanner.getRandomImage(config.getSelectedFolders(), lastUri);
|
||||
}
|
||||
|
||||
if (nextImage != null) {
|
||||
// 保存新壁纸配置
|
||||
prefs.saveConfig(config);
|
||||
prefs.saveLastUri(nextImage.getUri());
|
||||
|
||||
// 发送广播通知壁纸服务更新显示
|
||||
Intent intent = new Intent("cn.hugh.bz.gk2.ACTION_CHANGE_WALLPAPER");
|
||||
intent.putExtra("force_change", false); // 只通知更新,不重新选择壁纸
|
||||
requireActivity().sendBroadcast(intent);
|
||||
|
||||
Toast.makeText(requireContext(), "已切换到下一张", Toast.LENGTH_SHORT).show();
|
||||
|
||||
// 延迟刷新预览
|
||||
new Handler(Looper.getMainLooper()).postDelayed(() -> {
|
||||
loadCurrentWallpaper();
|
||||
}, 500);
|
||||
} else {
|
||||
Toast.makeText(requireContext(), "没有更多壁纸了", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void openInGallery() {
|
||||
String currentUri = prefs.getLastUri();
|
||||
if (currentUri != null) {
|
||||
try {
|
||||
Uri uri = Uri.parse(currentUri);
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
|
||||
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
startActivity(intent);
|
||||
} catch (Exception e) {
|
||||
Toast.makeText(requireContext(), "无法打开相册", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getDisplayName(String uriString) {
|
||||
if (uriString == null || uriString.isEmpty()) {
|
||||
return "未知壁纸";
|
||||
}
|
||||
|
||||
try {
|
||||
Uri uri = Uri.parse(uriString);
|
||||
String path = uri.getLastPathSegment();
|
||||
if (path != null) {
|
||||
// 处理 content://com.android.externalstorage.documents/tree/primary%3ADCIM 这种格式
|
||||
if (path.contains(":")) {
|
||||
String[] parts = path.split(":");
|
||||
if (parts.length > 1) {
|
||||
path = parts[1];
|
||||
}
|
||||
}
|
||||
// 移除文件扩展名
|
||||
if (path.contains("/")) {
|
||||
String[] segments = path.split("/");
|
||||
path = segments[segments.length - 1];
|
||||
}
|
||||
return path;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
return "当前壁纸";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
loadCurrentWallpaper();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
// 释放图片资源
|
||||
if (ivWallpaper != null) {
|
||||
ivWallpaper.setImageDrawable(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package cn.hugh.bz.gk2.ui;
|
||||
|
||||
import android.app.WallpaperManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.Button;
|
||||
import android.widget.ListView;
|
||||
import android.widget.ProgressBar;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.documentfile.provider.DocumentFile;
|
||||
import androidx.fragment.app.Fragment;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import cn.hugh.bz.gk2.R;
|
||||
import cn.hugh.bz.gk2.model.AppConfig;
|
||||
import cn.hugh.bz.gk2.model.PlayMode;
|
||||
import cn.hugh.bz.gk2.utils.AlarmScheduler;
|
||||
import cn.hugh.bz.gk2.utils.ImageScanner;
|
||||
import cn.hugh.bz.gk2.wallpaper.WallpaperPreferences;
|
||||
|
||||
/**
|
||||
* 主页 Fragment
|
||||
* 负责显示服务状态、文件夹选择、启用/禁用服务等功能
|
||||
*/
|
||||
public class HomeFragment extends Fragment {
|
||||
|
||||
private TextView tvStatus;
|
||||
private View statusIndicator;
|
||||
private TextView tvFolderInfo;
|
||||
private Button btnToggle;
|
||||
private Button btnChangeNow;
|
||||
private Button btnSelectFolders;
|
||||
private ListView lvFolders;
|
||||
private ProgressBar progressBar;
|
||||
|
||||
private WallpaperPreferences prefs;
|
||||
private AppConfig config;
|
||||
private ImageScanner scanner;
|
||||
private FolderAdapter folderAdapter;
|
||||
|
||||
// 文件夹选择回调接口
|
||||
public interface FolderPickerCallback {
|
||||
void launchFolderPicker(FolderPickerResultCallback callback);
|
||||
}
|
||||
|
||||
public interface FolderPickerResultCallback {
|
||||
void onFolderPicked(String uri);
|
||||
}
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
|
||||
return inflater.inflate(R.layout.fragment_home, container, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
|
||||
prefs = new WallpaperPreferences(requireContext());
|
||||
config = prefs.loadConfig();
|
||||
scanner = new ImageScanner(requireContext());
|
||||
|
||||
initViews(view);
|
||||
updateUI();
|
||||
|
||||
// 首次启动显示引导
|
||||
showFirstRunGuide();
|
||||
}
|
||||
|
||||
/**
|
||||
* 首次启动显示使用指南
|
||||
*/
|
||||
private void showFirstRunGuide() {
|
||||
boolean hasShownGuide = prefs.getBoolean("first_run_guide_shown", false);
|
||||
|
||||
if (!hasShownGuide) {
|
||||
new AlertDialog.Builder(requireContext())
|
||||
.setTitle("欢迎使用 BzForGk2")
|
||||
.setMessage(
|
||||
"使用步骤:\n\n" +
|
||||
"1. 点击「选择文件夹」添加图片文件夹\n" +
|
||||
"2. 点击「启用」按钮\n" +
|
||||
"3. 在弹出的壁纸选择界面选择「BzForGk2」\n" +
|
||||
"4. 设置完成!壁纸会自动更换"
|
||||
)
|
||||
.setPositiveButton("知道了", (dialog, which) -> {
|
||||
prefs.putBoolean("first_run_guide_shown", true);
|
||||
})
|
||||
.setCancelable(false)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
private void initViews(View view) {
|
||||
tvStatus = view.findViewById(R.id.tvStatus);
|
||||
statusIndicator = view.findViewById(R.id.statusIndicator);
|
||||
tvFolderInfo = view.findViewById(R.id.tvFolderInfo);
|
||||
btnToggle = view.findViewById(R.id.btnToggle);
|
||||
btnChangeNow = view.findViewById(R.id.btnChangeNow);
|
||||
btnSelectFolders = view.findViewById(R.id.btnSelectFolders);
|
||||
lvFolders = view.findViewById(R.id.lvFolders);
|
||||
progressBar = view.findViewById(R.id.progressBar);
|
||||
|
||||
// 设置文件夹列表适配器
|
||||
folderAdapter = new FolderAdapter(requireContext(), config.getSelectedFolders(), this::removeFolder);
|
||||
lvFolders.setAdapter(folderAdapter);
|
||||
|
||||
btnToggle.setOnClickListener(v -> toggleService());
|
||||
btnChangeNow.setOnClickListener(v -> changeWallpaperNow());
|
||||
btnSelectFolders.setOnClickListener(v -> openFolderPicker());
|
||||
}
|
||||
|
||||
private void toggleService() {
|
||||
if (config.getSelectedFolders().isEmpty()) {
|
||||
Toast.makeText(requireContext(), "请先选择文件夹", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
boolean newState = !config.isEnabled();
|
||||
|
||||
if (newState) {
|
||||
// 每次启用都弹出壁纸设置引导
|
||||
showSetWallpaperDialog();
|
||||
// 注意:不在这里设置 enabled,而是在用户设置壁纸后再设置
|
||||
} else {
|
||||
config.setEnabled(newState);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
AlarmScheduler scheduler = new AlarmScheduler(requireContext());
|
||||
scheduler.cancelSchedule();
|
||||
Toast.makeText(requireContext(), "已禁用", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
updateUI();
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示引导设置壁纸的对话框
|
||||
*/
|
||||
private void showSetWallpaperDialog() {
|
||||
new AlertDialog.Builder(requireContext())
|
||||
.setTitle("设置动态壁纸")
|
||||
.setMessage("点击\"确定\"后将打开壁纸选择界面,请选择\"BzForGk2\"作为动态壁纸。\n\n设置完成后返回应用即可自动启用。")
|
||||
.setPositiveButton("确定", (dialog, which) -> {
|
||||
openWallpaperSelector();
|
||||
// 启用服务
|
||||
config.setEnabled(true);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
AlarmScheduler scheduler = new AlarmScheduler(requireContext());
|
||||
scheduler.scheduleWallpaperChange(config.getIntervalMinutes());
|
||||
|
||||
Toast.makeText(requireContext(), "已启用,请选择壁纸", Toast.LENGTH_LONG).show();
|
||||
updateUI();
|
||||
})
|
||||
.setNegativeButton("取消", null)
|
||||
.show();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开系统壁纸选择界面
|
||||
*/
|
||||
private void openWallpaperSelector() {
|
||||
try {
|
||||
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
|
||||
intent.putExtra(
|
||||
WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
|
||||
new android.content.ComponentName(requireContext(), cn.hugh.bz.gk2.wallpaper.AutoWallpaperService.class)
|
||||
);
|
||||
startActivity(intent);
|
||||
} catch (Exception e) {
|
||||
// 如果上述方法失败,尝试打开壁纸选择器
|
||||
try {
|
||||
Intent intent = new Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
|
||||
startActivity(intent);
|
||||
Toast.makeText(requireContext(), "请选择 BzForGk2 动态壁纸", Toast.LENGTH_LONG).show();
|
||||
} catch (Exception ex) {
|
||||
// 最后的备用方案:打开壁纸设置页面
|
||||
try {
|
||||
Intent intent = new Intent("android.settings.WALLPAPER_SETTINGS");
|
||||
startActivity(intent);
|
||||
Toast.makeText(requireContext(), "请选择 动态壁纸 → BzForGk2", Toast.LENGTH_LONG).show();
|
||||
} catch (Exception exc) {
|
||||
Toast.makeText(requireContext(), "无法打开壁纸设置,请手动去系统设置中选择", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void changeWallpaperNow() {
|
||||
if (config.getSelectedFolders().isEmpty()) {
|
||||
Toast.makeText(requireContext(), "请先选择文件夹", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
// 直接获取下一张壁纸,与"下一张"按钮相同的逻辑
|
||||
cn.hugh.bz.gk2.model.WallpaperImage nextImage = null;
|
||||
String lastUri = prefs.getLastUri();
|
||||
|
||||
if (config.getPlayMode() == cn.hugh.bz.gk2.model.PlayMode.SEQUENTIAL) {
|
||||
// 顺序模式:获取下一张
|
||||
int index = config.getCurrentIndex();
|
||||
nextImage = scanner.getImageAtIndex(config.getSelectedFolders(), index);
|
||||
if (nextImage != null) {
|
||||
config.setCurrentIndex(index + 1);
|
||||
}
|
||||
} else {
|
||||
// 随机模式:随机选择一张
|
||||
nextImage = scanner.getRandomImage(config.getSelectedFolders(), lastUri);
|
||||
}
|
||||
|
||||
if (nextImage != null) {
|
||||
// 保存新壁纸配置
|
||||
prefs.saveConfig(config);
|
||||
prefs.saveLastUri(nextImage.getUri());
|
||||
|
||||
// 发送广播通知壁纸服务更新显示
|
||||
Intent intent = new Intent("cn.hugh.bz.gk2.ACTION_CHANGE_WALLPAPER");
|
||||
intent.putExtra("force_change", false); // 只通知更新,不重新选择壁纸
|
||||
requireActivity().sendBroadcast(intent);
|
||||
|
||||
Toast.makeText(requireContext(), "壁纸已更换", Toast.LENGTH_SHORT).show();
|
||||
} else {
|
||||
Toast.makeText(requireContext(), "没有更多壁纸了", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void openFolderPicker() {
|
||||
// 通过 MainActivity 启动文件夹选择器
|
||||
if (getActivity() instanceof FolderPickerCallback) {
|
||||
((FolderPickerCallback) getActivity()).launchFolderPicker(uri -> {
|
||||
addFolder(uri);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void addFolder(String folderPath) {
|
||||
if (folderPath == null || config.getSelectedFolders().contains(folderPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
config.getSelectedFolders().add(folderPath);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
// 异步扫描文件夹
|
||||
Toast.makeText(requireContext(), "正在扫描文件夹...", Toast.LENGTH_SHORT).show();
|
||||
new Thread(() -> {
|
||||
scanner.scanFolder(folderPath);
|
||||
requireActivity().runOnUiThread(() -> {
|
||||
updateUI();
|
||||
Toast.makeText(requireContext(), "已添加文件夹", Toast.LENGTH_SHORT).show();
|
||||
});
|
||||
}).start();
|
||||
}
|
||||
|
||||
private void removeFolder(int position) {
|
||||
if (position >= 0 && position < config.getSelectedFolders().size()) {
|
||||
String folderPath = config.getSelectedFolders().get(position);
|
||||
config.getSelectedFolders().remove(position);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
updateUI();
|
||||
Toast.makeText(requireContext(), "已移除文件夹", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateUI() {
|
||||
// Update status
|
||||
if (config.isEnabled()) {
|
||||
tvStatus.setText(R.string.status_enabled);
|
||||
btnToggle.setText(R.string.disable);
|
||||
btnChangeNow.setEnabled(true);
|
||||
// 更新状态指示器
|
||||
if (statusIndicator != null) {
|
||||
statusIndicator.setBackgroundResource(R.drawable.status_indicator_enabled);
|
||||
}
|
||||
} else {
|
||||
tvStatus.setText(R.string.status_disabled);
|
||||
btnToggle.setText(R.string.enable);
|
||||
btnChangeNow.setEnabled(false);
|
||||
// 更新状态指示器
|
||||
if (statusIndicator != null) {
|
||||
statusIndicator.setBackgroundResource(R.drawable.status_indicator_disabled);
|
||||
}
|
||||
}
|
||||
|
||||
// Update folder info - 使用缓存的数量,不重新扫描
|
||||
if (config.getSelectedFolders().isEmpty()) {
|
||||
tvFolderInfo.setText(R.string.no_folders);
|
||||
progressBar.setVisibility(View.GONE);
|
||||
} else {
|
||||
// 显示进度条
|
||||
progressBar.setVisibility(View.VISIBLE);
|
||||
progressBar.setIndeterminate(true);
|
||||
|
||||
// 异步获取图片数量
|
||||
tvFolderInfo.setText(String.format("已选择 %d 个文件夹,正在统计图片...",
|
||||
config.getSelectedFolders().size()));
|
||||
|
||||
new Thread(() -> {
|
||||
int imageCount = scanner.getTotalImageCount(config.getSelectedFolders());
|
||||
requireActivity().runOnUiThread(() -> {
|
||||
tvFolderInfo.setText(String.format("已选择 %d 个文件夹,共 %d 张图片",
|
||||
config.getSelectedFolders().size(), imageCount));
|
||||
progressBar.setVisibility(View.GONE);
|
||||
});
|
||||
}).start();
|
||||
}
|
||||
|
||||
// Update folder list adapter
|
||||
if (folderAdapter != null) {
|
||||
folderAdapter.updateFolders(config.getSelectedFolders());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
config = prefs.loadConfig();
|
||||
updateUI();
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件夹列表适配器
|
||||
*/
|
||||
private static class FolderAdapter extends ArrayAdapter<String> {
|
||||
private final Context context;
|
||||
private List<String> folders;
|
||||
private final java.util.Map<String, Integer> imageCounts = new java.util.HashMap<>();
|
||||
private ImageScanner scanner;
|
||||
private OnFolderRemoveListener removeListener;
|
||||
|
||||
public interface OnFolderRemoveListener {
|
||||
void onFolderRemove(int position);
|
||||
}
|
||||
|
||||
public FolderAdapter(Context context, List<String> folders, OnFolderRemoveListener listener) {
|
||||
super(context, R.layout.item_folder_card, folders);
|
||||
this.context = context;
|
||||
this.folders = new ArrayList<>(folders);
|
||||
this.scanner = new ImageScanner(context);
|
||||
this.removeListener = listener;
|
||||
// 异步加载图片数量
|
||||
loadImageCounts();
|
||||
}
|
||||
|
||||
public void updateFolders(List<String> newFolders) {
|
||||
this.folders = new ArrayList<>(newFolders);
|
||||
clear();
|
||||
addAll(newFolders);
|
||||
// 异步加载图片数量
|
||||
loadImageCounts();
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
private void loadImageCounts() {
|
||||
new Thread(() -> {
|
||||
for (String folderUri : folders) {
|
||||
if (!imageCounts.containsKey(folderUri)) {
|
||||
int count = scanner.scanFolder(folderUri).size();
|
||||
imageCounts.put(folderUri, count);
|
||||
// 在主线程更新 UI
|
||||
new android.os.Handler(android.os.Looper.getMainLooper()).post(() ->
|
||||
notifyDataSetChanged()
|
||||
);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
|
||||
ViewHolder holder;
|
||||
if (convertView == null) {
|
||||
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
|
||||
convertView = inflater.inflate(R.layout.item_folder_card, parent, false);
|
||||
holder = new ViewHolder();
|
||||
holder.tvFolderName = convertView.findViewById(R.id.tvFolderName);
|
||||
holder.tvFolderPath = convertView.findViewById(R.id.tvFolderPath);
|
||||
holder.tvImageCount = convertView.findViewById(R.id.tvImageCount);
|
||||
holder.btnRemove = convertView.findViewById(R.id.btnRemove);
|
||||
convertView.setTag(holder);
|
||||
} else {
|
||||
holder = (ViewHolder) convertView.getTag();
|
||||
}
|
||||
|
||||
String folderUri = folders.get(position);
|
||||
|
||||
// 解析 URI 获取文件夹名称
|
||||
Uri uri = Uri.parse(folderUri);
|
||||
String folderName = getLastPathSegment(uri);
|
||||
holder.tvFolderName.setText(folderName);
|
||||
holder.tvFolderPath.setText(folderUri);
|
||||
|
||||
// 使用缓存的图片数量
|
||||
Integer count = imageCounts.get(folderUri);
|
||||
if (count != null) {
|
||||
holder.tvImageCount.setText(count + " 张图片");
|
||||
} else {
|
||||
holder.tvImageCount.setText("正在扫描...");
|
||||
}
|
||||
|
||||
// 移除按钮
|
||||
final int positionFinal = position;
|
||||
holder.btnRemove.setOnClickListener(v -> {
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle("移除文件夹")
|
||||
.setMessage("确定要移除这个文件夹吗?")
|
||||
.setPositiveButton("确定", (dialog, which) -> {
|
||||
if (removeListener != null) {
|
||||
removeListener.onFolderRemove(positionFinal);
|
||||
}
|
||||
})
|
||||
.setNegativeButton("取消", null)
|
||||
.show();
|
||||
});
|
||||
|
||||
return convertView;
|
||||
}
|
||||
|
||||
private String getLastPathSegment(Uri uri) {
|
||||
String path = uri.getLastPathSegment();
|
||||
if (path != null) {
|
||||
// 处理 content://com.android.externalstorage.documents/tree/primary%3ADCIM 这种格式
|
||||
if (path.contains(":")) {
|
||||
String[] parts = path.split(":");
|
||||
if (parts.length > 1) {
|
||||
return parts[1];
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
return "未知文件夹";
|
||||
}
|
||||
|
||||
// ViewHolder 模式优化
|
||||
private static class ViewHolder {
|
||||
TextView tvFolderName;
|
||||
TextView tvFolderPath;
|
||||
TextView tvImageCount;
|
||||
Button btnRemove;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,424 +1,102 @@
|
||||
package cn.hugh.bz.gk2.ui;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.WallpaperManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.Button;
|
||||
import android.widget.ListView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.activity.result.ActivityResultLauncher;
|
||||
import androidx.activity.result.contract.ActivityResultContracts;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.documentfile.provider.DocumentFile;
|
||||
import androidx.viewpager2.widget.ViewPager2;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.google.android.material.bottomnavigation.BottomNavigationView;
|
||||
import com.google.android.material.navigation.NavigationBarView;
|
||||
|
||||
import cn.hugh.bz.gk2.R;
|
||||
import cn.hugh.bz.gk2.model.AppConfig;
|
||||
import cn.hugh.bz.gk2.model.PlayMode;
|
||||
import cn.hugh.bz.gk2.utils.AlarmScheduler;
|
||||
import cn.hugh.bz.gk2.utils.ImageScanner;
|
||||
import cn.hugh.bz.gk2.wallpaper.WallpaperPreferences;
|
||||
|
||||
public class MainActivity extends AppCompatActivity {
|
||||
/**
|
||||
* 主 Activity
|
||||
* 作为 Fragment 容器,托管 ViewPager2 和 BottomNavigationView
|
||||
*/
|
||||
public class MainActivity extends AppCompatActivity implements HomeFragment.FolderPickerCallback {
|
||||
|
||||
private TextView tvStatus;
|
||||
private TextView tvFolderInfo;
|
||||
private Button btnToggle;
|
||||
private Button btnChangeNow;
|
||||
private Button btnSelectFolders;
|
||||
private Button btnSettings;
|
||||
private ListView lvFolders;
|
||||
private android.widget.ProgressBar progressBar;
|
||||
|
||||
private WallpaperPreferences prefs;
|
||||
private AppConfig config;
|
||||
private ImageScanner scanner;
|
||||
private FolderAdapter folderAdapter;
|
||||
private ViewPager2 viewPager;
|
||||
private BottomNavigationView bottomNav;
|
||||
private ViewPagerAdapter adapter;
|
||||
|
||||
// Folder picker launcher
|
||||
private final ActivityResultLauncher<Intent> folderPickerLauncher =
|
||||
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
|
||||
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
|
||||
Uri uri = result.getData().getData();
|
||||
if (uri != null) {
|
||||
// 持久化 URI 权限
|
||||
final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION |
|
||||
Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
|
||||
getContentResolver().takePersistableUriPermission(uri, takeFlags);
|
||||
|
||||
// 保存完整的 URI 字符串
|
||||
String folderUri = uri.toString();
|
||||
addFolder(folderUri);
|
||||
}
|
||||
}
|
||||
});
|
||||
private ActivityResultLauncher<Intent> folderPickerLauncher;
|
||||
private HomeFragment.FolderPickerResultCallback currentCallback;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_main);
|
||||
|
||||
prefs = new WallpaperPreferences(this);
|
||||
config = prefs.loadConfig();
|
||||
scanner = new ImageScanner(this);
|
||||
|
||||
initFolderPickerLauncher();
|
||||
initViews();
|
||||
updateUI();
|
||||
|
||||
// 首次启动显示引导
|
||||
showFirstRunGuide();
|
||||
setupViewPager();
|
||||
setupBottomNav();
|
||||
}
|
||||
|
||||
/**
|
||||
* 首次启动显示使用指南
|
||||
* 初始化文件夹选择器
|
||||
*/
|
||||
private void showFirstRunGuide() {
|
||||
boolean hasShownGuide = prefs.getBoolean("first_run_guide_shown", false);
|
||||
private void initFolderPickerLauncher() {
|
||||
folderPickerLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.StartActivityForResult(),
|
||||
result -> {
|
||||
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
|
||||
Uri uri = result.getData().getData();
|
||||
if (uri != null) {
|
||||
// 持久化 URI 权限
|
||||
final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION |
|
||||
Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
|
||||
getContentResolver().takePersistableUriPermission(uri, takeFlags);
|
||||
|
||||
if (!hasShownGuide) {
|
||||
new AlertDialog.Builder(this)
|
||||
.setTitle("欢迎使用 BzForGk2")
|
||||
.setMessage(
|
||||
"使用步骤:\n\n" +
|
||||
"1. 点击「选择文件夹」添加图片文件夹\n" +
|
||||
"2. 点击「启用」按钮\n" +
|
||||
"3. 在弹出的壁纸选择界面选择「BzForGk2」\n" +
|
||||
"4. 设置完成!壁纸会自动更换"
|
||||
)
|
||||
.setPositiveButton("知道了", (dialog, which) -> {
|
||||
prefs.putBoolean("first_run_guide_shown", true);
|
||||
})
|
||||
.setCancelable(false)
|
||||
.show();
|
||||
}
|
||||
// 保存完整的 URI 字符串
|
||||
String folderUri = uri.toString();
|
||||
|
||||
// 回调给 HomeFragment
|
||||
if (currentCallback != null) {
|
||||
currentCallback.onFolderPicked(folderUri);
|
||||
currentCallback = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private void initViews() {
|
||||
tvStatus = findViewById(R.id.tvStatus);
|
||||
tvFolderInfo = findViewById(R.id.tvFolderInfo);
|
||||
btnToggle = findViewById(R.id.btnToggle);
|
||||
btnChangeNow = findViewById(R.id.btnChangeNow);
|
||||
btnSelectFolders = findViewById(R.id.btnSelectFolders);
|
||||
btnSettings = findViewById(R.id.btnSettings);
|
||||
lvFolders = findViewById(R.id.lvFolders);
|
||||
progressBar = findViewById(R.id.progressBar);
|
||||
|
||||
// 设置文件夹列表适配器
|
||||
folderAdapter = new FolderAdapter(this, config.getSelectedFolders());
|
||||
lvFolders.setAdapter(folderAdapter);
|
||||
|
||||
btnToggle.setOnClickListener(v -> toggleService());
|
||||
btnChangeNow.setOnClickListener(v -> changeWallpaperNow());
|
||||
btnSelectFolders.setOnClickListener(v -> openFolderPicker());
|
||||
btnSettings.setOnClickListener(v -> openSettings());
|
||||
viewPager = findViewById(R.id.viewPager);
|
||||
bottomNav = findViewById(R.id.bottomNav);
|
||||
}
|
||||
|
||||
private void toggleService() {
|
||||
if (config.getSelectedFolders().isEmpty()) {
|
||||
Toast.makeText(this, "请先选择文件夹", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
private void setupViewPager() {
|
||||
adapter = new ViewPagerAdapter(this);
|
||||
viewPager.setAdapter(adapter);
|
||||
viewPager.setUserInputEnabled(false); // 禁用滑动切换,只能通过底部导航切换
|
||||
}
|
||||
|
||||
boolean newState = !config.isEnabled();
|
||||
|
||||
if (newState) {
|
||||
// 每次启用都弹出壁纸设置引导
|
||||
showSetWallpaperDialog();
|
||||
// 注意:不在这里设置 enabled,而是在用户设置壁纸后再设置
|
||||
} else {
|
||||
config.setEnabled(newState);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
AlarmScheduler scheduler = new AlarmScheduler(this);
|
||||
scheduler.cancelSchedule();
|
||||
Toast.makeText(this, "已禁用", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
updateUI();
|
||||
private void setupBottomNav() {
|
||||
bottomNav.setOnItemSelectedListener(item -> {
|
||||
int position = item.getOrder();
|
||||
viewPager.setCurrentItem(position, false);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查当前壁纸是否是本应用的壁纸
|
||||
* 实现 HomeFragment.FolderPickerCallback 接口
|
||||
* 启动文件夹选择器
|
||||
*/
|
||||
private boolean isWallpaperActive() {
|
||||
// 简化检查:检查是否有壁纸设置记录
|
||||
return prefs.getBoolean("wallpaper_set", false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示引导设置壁纸的对话框
|
||||
*/
|
||||
private void showSetWallpaperDialog() {
|
||||
new AlertDialog.Builder(this)
|
||||
.setTitle("设置动态壁纸")
|
||||
.setMessage("点击\"确定\"后将打开壁纸选择界面,请选择\"BzForGk2\"作为动态壁纸。\n\n设置完成后返回应用即可自动启用。")
|
||||
.setPositiveButton("确定", (dialog, which) -> {
|
||||
openWallpaperSelector();
|
||||
// 启用服务
|
||||
config.setEnabled(true);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
AlarmScheduler scheduler = new AlarmScheduler(this);
|
||||
scheduler.scheduleWallpaperChange(config.getIntervalMinutes());
|
||||
|
||||
Toast.makeText(this, "已启用,请选择壁纸", Toast.LENGTH_LONG).show();
|
||||
updateUI();
|
||||
})
|
||||
.setNegativeButton("取消", null)
|
||||
.show();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开系统壁纸选择界面
|
||||
*/
|
||||
private void openWallpaperSelector() {
|
||||
try {
|
||||
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
|
||||
intent.putExtra(
|
||||
WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
|
||||
new android.content.ComponentName(this, cn.hugh.bz.gk2.wallpaper.AutoWallpaperService.class)
|
||||
);
|
||||
startActivity(intent);
|
||||
} catch (Exception e) {
|
||||
// 如果上述方法失败,尝试打开壁纸选择器
|
||||
try {
|
||||
Intent intent = new Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
|
||||
startActivity(intent);
|
||||
Toast.makeText(this, "请选择 BzForGk2 动态壁纸", Toast.LENGTH_LONG).show();
|
||||
} catch (Exception ex) {
|
||||
// 最后的备用方案:打开壁纸设置页面
|
||||
try {
|
||||
Intent intent = new Intent("android.settings.WALLPAPER_SETTINGS");
|
||||
startActivity(intent);
|
||||
Toast.makeText(this, "请选择 动态壁纸 → BzForGk2", Toast.LENGTH_LONG).show();
|
||||
} catch (Exception exc) {
|
||||
Toast.makeText(this, "无法打开壁纸设置,请手动去系统设置中选择", Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void changeWallpaperNow() {
|
||||
if (config.getSelectedFolders().isEmpty()) {
|
||||
Toast.makeText(this, "请先选择文件夹", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
// Trigger wallpaper refresh
|
||||
Intent intent = new Intent("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER");
|
||||
sendBroadcast(intent);
|
||||
|
||||
Toast.makeText(this, "壁纸已更换", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
private void openFolderPicker() {
|
||||
@Override
|
||||
public void launchFolderPicker(HomeFragment.FolderPickerResultCallback callback) {
|
||||
this.currentCallback = callback;
|
||||
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
|
||||
folderPickerLauncher.launch(intent);
|
||||
}
|
||||
|
||||
private void openSettings() {
|
||||
Intent intent = new Intent(this, SettingsActivity.class);
|
||||
startActivity(intent);
|
||||
}
|
||||
|
||||
private void addFolder(String folderPath) {
|
||||
if (folderPath == null || config.getSelectedFolders().contains(folderPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
config.getSelectedFolders().add(folderPath);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
// 异步扫描文件夹
|
||||
Toast.makeText(this, "正在扫描文件夹...", Toast.LENGTH_SHORT).show();
|
||||
new Thread(() -> {
|
||||
scanner.scanFolder(folderPath);
|
||||
runOnUiThread(() -> {
|
||||
updateUI();
|
||||
Toast.makeText(this, "已添加文件夹", Toast.LENGTH_SHORT).show();
|
||||
});
|
||||
}).start();
|
||||
}
|
||||
|
||||
private void removeFolder(int position) {
|
||||
if (position >= 0 && position < config.getSelectedFolders().size()) {
|
||||
String folderPath = config.getSelectedFolders().get(position);
|
||||
config.getSelectedFolders().remove(position);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
updateUI();
|
||||
Toast.makeText(this, "已移除文件夹", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateUI() {
|
||||
// Update status
|
||||
if (config.isEnabled()) {
|
||||
tvStatus.setText(R.string.status_enabled);
|
||||
btnToggle.setText(R.string.disable);
|
||||
btnChangeNow.setEnabled(true);
|
||||
} else {
|
||||
tvStatus.setText(R.string.status_disabled);
|
||||
btnToggle.setText(R.string.enable);
|
||||
btnChangeNow.setEnabled(false);
|
||||
}
|
||||
|
||||
// Update folder info - 使用缓存的数量,不重新扫描
|
||||
if (config.getSelectedFolders().isEmpty()) {
|
||||
tvFolderInfo.setText(R.string.no_folders);
|
||||
progressBar.setVisibility(android.view.View.GONE);
|
||||
} else {
|
||||
// 显示进度条
|
||||
progressBar.setVisibility(android.view.View.VISIBLE);
|
||||
progressBar.setIndeterminate(true);
|
||||
|
||||
// 异步获取图片数量
|
||||
tvFolderInfo.setText(String.format("已选择 %d 个文件夹,正在统计图片...",
|
||||
config.getSelectedFolders().size()));
|
||||
|
||||
new Thread(() -> {
|
||||
int imageCount = scanner.getTotalImageCount(config.getSelectedFolders());
|
||||
runOnUiThread(() -> {
|
||||
tvFolderInfo.setText(String.format("已选择 %d 个文件夹,共 %d 张图片",
|
||||
config.getSelectedFolders().size(), imageCount));
|
||||
progressBar.setVisibility(android.view.View.GONE);
|
||||
});
|
||||
}).start();
|
||||
}
|
||||
|
||||
// Update folder list adapter
|
||||
if (folderAdapter != null) {
|
||||
folderAdapter.updateFolders(config.getSelectedFolders());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
config = prefs.loadConfig();
|
||||
updateUI();
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件夹列表适配器
|
||||
*/
|
||||
private class FolderAdapter extends ArrayAdapter<String> {
|
||||
private final Context context;
|
||||
private List<String> folders;
|
||||
private final java.util.Map<String, Integer> imageCounts = new java.util.HashMap<>();
|
||||
|
||||
public FolderAdapter(Context context, List<String> folders) {
|
||||
super(context, R.layout.item_folder, folders);
|
||||
this.context = context;
|
||||
this.folders = new ArrayList<>(folders);
|
||||
// 异步加载图片数量
|
||||
loadImageCounts();
|
||||
}
|
||||
|
||||
public void updateFolders(List<String> newFolders) {
|
||||
this.folders = new ArrayList<>(newFolders);
|
||||
clear();
|
||||
addAll(newFolders);
|
||||
// 异步加载图片数量
|
||||
loadImageCounts();
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
private void loadImageCounts() {
|
||||
new Thread(() -> {
|
||||
for (String folderUri : folders) {
|
||||
if (!imageCounts.containsKey(folderUri)) {
|
||||
int count = scanner.scanFolder(folderUri).size();
|
||||
imageCounts.put(folderUri, count);
|
||||
runOnUiThread(() -> notifyDataSetChanged());
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
|
||||
ViewHolder holder;
|
||||
if (convertView == null) {
|
||||
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
|
||||
convertView = inflater.inflate(R.layout.item_folder, parent, false);
|
||||
holder = new ViewHolder();
|
||||
holder.tvFolderName = convertView.findViewById(R.id.tvFolderName);
|
||||
holder.tvFolderPath = convertView.findViewById(R.id.tvFolderPath);
|
||||
holder.tvImageCount = convertView.findViewById(R.id.tvImageCount);
|
||||
holder.btnRemove = convertView.findViewById(R.id.btnRemove);
|
||||
convertView.setTag(holder);
|
||||
} else {
|
||||
holder = (ViewHolder) convertView.getTag();
|
||||
}
|
||||
|
||||
String folderUri = folders.get(position);
|
||||
|
||||
// 解析 URI 获取文件夹名称
|
||||
Uri uri = Uri.parse(folderUri);
|
||||
String folderName = getLastPathSegment(uri);
|
||||
holder.tvFolderName.setText(folderName);
|
||||
holder.tvFolderPath.setText(folderUri);
|
||||
|
||||
// 使用缓存的图片数量
|
||||
Integer count = imageCounts.get(folderUri);
|
||||
if (count != null) {
|
||||
holder.tvImageCount.setText(count + " 张图片");
|
||||
} else {
|
||||
holder.tvImageCount.setText("正在扫描...");
|
||||
}
|
||||
|
||||
// 移除按钮
|
||||
holder.btnRemove.setOnClickListener(v -> {
|
||||
new AlertDialog.Builder(context)
|
||||
.setTitle("移除文件夹")
|
||||
.setMessage("确定要移除这个文件夹吗?")
|
||||
.setPositiveButton("确定", (dialog, which) -> {
|
||||
removeFolder(position);
|
||||
})
|
||||
.setNegativeButton("取消", null)
|
||||
.show();
|
||||
});
|
||||
|
||||
return convertView;
|
||||
}
|
||||
|
||||
private String getLastPathSegment(Uri uri) {
|
||||
String path = uri.getLastPathSegment();
|
||||
if (path != null) {
|
||||
// 处理 content://com.android.externalstorage.documents/tree/primary%3ADCIM 这种格式
|
||||
if (path.contains(":")) {
|
||||
String[] parts = path.split(":");
|
||||
if (parts.length > 1) {
|
||||
return parts[1];
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
return "未知文件夹";
|
||||
}
|
||||
|
||||
// ViewHolder 模式优化
|
||||
private class ViewHolder {
|
||||
TextView tvFolderName;
|
||||
TextView tvFolderPath;
|
||||
TextView tvImageCount;
|
||||
Button btnRemove;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package cn.hugh.bz.gk2.ui;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.widget.RadioButton;
|
||||
import android.widget.RadioGroup;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.Switch;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.Fragment;
|
||||
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import cn.hugh.bz.gk2.R;
|
||||
import cn.hugh.bz.gk2.model.AppConfig;
|
||||
import cn.hugh.bz.gk2.model.PlayMode;
|
||||
import cn.hugh.bz.gk2.utils.AlarmScheduler;
|
||||
import cn.hugh.bz.gk2.wallpaper.WallpaperPreferences;
|
||||
|
||||
/**
|
||||
* 设置 Fragment
|
||||
* 负责播放模式、更换间隔、返回桌面更换等设置
|
||||
* 所有设置实时保存,无需保存按钮
|
||||
*/
|
||||
public class SettingsFragment extends Fragment {
|
||||
|
||||
private RadioButton rbSequential;
|
||||
private RadioButton rbRandom;
|
||||
private RadioGroup rgPlayMode;
|
||||
private SeekBar seekBarInterval;
|
||||
private TextView tvIntervalValue;
|
||||
private Switch switchChangeOnReturn;
|
||||
|
||||
private WallpaperPreferences prefs;
|
||||
private AppConfig config;
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
|
||||
return inflater.inflate(R.layout.fragment_settings, container, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
|
||||
prefs = new WallpaperPreferences(requireContext());
|
||||
config = prefs.loadConfig();
|
||||
|
||||
initViews(view);
|
||||
loadConfig();
|
||||
}
|
||||
|
||||
private void initViews(View view) {
|
||||
rbSequential = view.findViewById(R.id.rbSequential);
|
||||
rbRandom = view.findViewById(R.id.rbRandom);
|
||||
rgPlayMode = view.findViewById(R.id.rgPlayMode);
|
||||
seekBarInterval = view.findViewById(R.id.seekBarInterval);
|
||||
tvIntervalValue = view.findViewById(R.id.tvIntervalValue);
|
||||
switchChangeOnReturn = view.findViewById(R.id.switchChangeOnReturn);
|
||||
|
||||
// 播放模式切换监听器(实时保存)
|
||||
rgPlayMode.setOnCheckedChangeListener((group, checkedId) -> {
|
||||
PlayMode playMode = rbSequential.isChecked() ? PlayMode.SEQUENTIAL : PlayMode.RANDOM;
|
||||
config.setPlayMode(playMode);
|
||||
prefs.saveConfig(config);
|
||||
});
|
||||
|
||||
// 间隔调节监听器(实时保存)
|
||||
seekBarInterval.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override
|
||||
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
|
||||
tvIntervalValue.setText(progress + " 分钟");
|
||||
|
||||
// 实时保存配置
|
||||
config.setIntervalMinutes(progress);
|
||||
prefs.saveConfig(config);
|
||||
|
||||
// 如果服务已启用,重新调度定时器
|
||||
if (config.isEnabled() && fromUser) {
|
||||
AlarmScheduler scheduler = new AlarmScheduler(requireContext());
|
||||
scheduler.scheduleWallpaperChange(progress);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStartTrackingTouch(SeekBar seekBar) {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStopTrackingTouch(SeekBar seekBar) {
|
||||
// Do nothing
|
||||
}
|
||||
});
|
||||
|
||||
// 返回桌面更换开关监听器(实时保存)
|
||||
switchChangeOnReturn.setOnCheckedChangeListener((buttonView, isChecked) -> {
|
||||
config.setChangeOnReturnToHome(isChecked);
|
||||
prefs.saveConfig(config);
|
||||
});
|
||||
}
|
||||
|
||||
private void loadConfig() {
|
||||
rbSequential.setChecked(config.getPlayMode() == PlayMode.SEQUENTIAL);
|
||||
rbRandom.setChecked(config.getPlayMode() == PlayMode.RANDOM);
|
||||
seekBarInterval.setProgress(config.getIntervalMinutes());
|
||||
tvIntervalValue.setText(config.getIntervalMinutes() + " 分钟");
|
||||
switchChangeOnReturn.setChecked(config.isChangeOnReturnToHome());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
config = prefs.loadConfig();
|
||||
loadConfig();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package cn.hugh.bz.gk2.ui;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.fragment.app.FragmentActivity;
|
||||
import androidx.viewpager2.adapter.FragmentStateAdapter;
|
||||
|
||||
/**
|
||||
* ViewPager2 适配器,用于管理三个 Fragment 页面
|
||||
*/
|
||||
public class ViewPagerAdapter extends FragmentStateAdapter {
|
||||
private static final int NUM_PAGES = 3;
|
||||
|
||||
public ViewPagerAdapter(FragmentActivity fa) {
|
||||
super(fa);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Fragment createFragment(int position) {
|
||||
switch (position) {
|
||||
case 0:
|
||||
return new HomeFragment();
|
||||
case 1:
|
||||
return new CurrentWallpaperFragment();
|
||||
case 2:
|
||||
return new SettingsFragment();
|
||||
default:
|
||||
return new HomeFragment();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return NUM_PAGES;
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ public class AlarmScheduler {
|
||||
// Create pending intent
|
||||
Intent intent = new Intent(context, WallpaperChangeReceiver.class);
|
||||
intent.setAction(WallpaperChangeReceiver.ACTION_CHANGE_WALLPAPER);
|
||||
// 定时器触发的更换不是强制更换,会根据配置决定是否更换
|
||||
intent.putExtra(WallpaperChangeReceiver.EXTRA_FORCE_CHANGE, false);
|
||||
|
||||
PendingIntent pendingIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
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 java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* 图片加载工具类
|
||||
* 用于加载和优化图片
|
||||
*/
|
||||
public class ImageLoader {
|
||||
private static final String TAG = "ImageLoader";
|
||||
|
||||
private final Context context;
|
||||
|
||||
public ImageLoader(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载图片并进行采样优化
|
||||
*
|
||||
* @param uriString 图片 URI 字符串
|
||||
* @param reqWidth 请求的宽度
|
||||
* @param reqHeight 请求的高度
|
||||
* @return Bitmap 对象,失败返回 null
|
||||
*/
|
||||
public Bitmap loadImage(String uriString, int reqWidth, int reqHeight) {
|
||||
if (uriString == null || uriString.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
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;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 使用传统 File API
|
||||
File file = new File(uriString);
|
||||
if (file.exists()) {
|
||||
FileInputStream fis = new FileInputStream(file);
|
||||
Bitmap bitmap = decodeSampledBitmapFromStream(fis, reqWidth, reqHeight);
|
||||
fis.close();
|
||||
return bitmap;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error loading image: " + uriString, e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从输入流中加载并采样图片
|
||||
*/
|
||||
private Bitmap decodeSampledBitmapFromStream(InputStream inputStream, int reqWidth, int reqHeight) {
|
||||
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);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error decoding bitmap from stream", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取输入流的所有字节
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
super.onCreate();
|
||||
|
||||
// Register refresh receiver
|
||||
android.content.IntentFilter filter = new android.content.IntentFilter("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER");
|
||||
android.content.IntentFilter filter = new android.content.IntentFilter("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER_SERVICE");
|
||||
registerReceiver(refreshReceiver, filter);
|
||||
}
|
||||
|
||||
@@ -44,9 +44,10 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
private final android.content.BroadcastReceiver refreshReceiver = new android.content.BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(android.content.Context context, android.content.Intent intent) {
|
||||
if ("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER".equals(intent.getAction())) {
|
||||
if ("cn.hugh.bz.gk2.ACTION_REFRESH_WALLPAPER_SERVICE".equals(intent.getAction())) {
|
||||
if (engine != null) {
|
||||
engine.refreshWallpaper();
|
||||
boolean forceChange = intent.getBooleanExtra("force_change", false);
|
||||
engine.refreshWallpaper(forceChange);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,6 +61,7 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
private int width;
|
||||
private int height;
|
||||
private boolean visible = false;
|
||||
private boolean forceChangeNext = false;
|
||||
|
||||
public WallpaperEngine() {
|
||||
this.imageLoader = new ImageLoader(AutoWallpaperService.this);
|
||||
@@ -104,7 +106,10 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
this.visible = false;
|
||||
}
|
||||
|
||||
public void refreshWallpaper() {
|
||||
public void refreshWallpaper(boolean forceChange) {
|
||||
if (forceChange) {
|
||||
forceChangeNext = true;
|
||||
}
|
||||
if (visible) {
|
||||
handler.post(this::drawWallpaper);
|
||||
}
|
||||
@@ -133,8 +138,10 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
WallpaperImage image;
|
||||
|
||||
// 核心逻辑:根据配置决定是否更换壁纸
|
||||
if (config.isChangeOnReturnToHome()) {
|
||||
// 开启状态:每次返回桌面都更换到下一张
|
||||
boolean shouldChange = forceChangeNext || config.isChangeOnReturnToHome();
|
||||
|
||||
if (shouldChange) {
|
||||
// 强制更换或开启返回桌面更换:获取下一张壁纸
|
||||
image = getNextWallpaper(config);
|
||||
|
||||
if (image != null) {
|
||||
@@ -162,6 +169,9 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重置强制更换标志
|
||||
forceChangeNext = false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error drawing wallpaper", e);
|
||||
|
||||
Reference in new issue
Block a user