源码整理,最新像素背景位图缓存功能调试完成。

This commit is contained in:
2025-12-24 21:21:38 +08:00
parent f4a485f1ff
commit bf9479c53f
7 changed files with 337 additions and 426 deletions

View File

@@ -1,8 +1,8 @@
#Created by .winboll/winboll_app_build.gradle #Created by .winboll/winboll_app_build.gradle
#Wed Dec 24 13:05:44 GMT 2025 #Wed Dec 24 13:18:30 GMT 2025
stageCount=29 stageCount=29
libraryProject= libraryProject=
baseVersion=15.14 baseVersion=15.14
publishVersion=15.14.28 publishVersion=15.14.28
buildCount=103 buildCount=104
baseBetaVersion=15.14.29 baseBetaVersion=15.14.29

View File

@@ -46,8 +46,7 @@ import java.io.File;
* @Author 豆包&ZhanGSKen<zhangsken@qq.com> * @Author 豆包&ZhanGSKen<zhangsken@qq.com>
*/ */
public class BackgroundSettingsActivity extends WinBoLLActivity { public class BackgroundSettingsActivity extends WinBoLLActivity {
// ====================== 常量定义(按功能分类)======================
// ====================== 常量定义(按功能分类置顶)======================
public static final String TAG = "BackgroundSettingsActivity"; public static final String TAG = "BackgroundSettingsActivity";
// 系统版本常量 // 系统版本常量
private static final int SDK_VERSION_TIRAMISU = 33; private static final int SDK_VERSION_TIRAMISU = 33;
@@ -86,7 +85,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
LogUtils.d(TAG, "生命周期 onCreate() 开始初始化"); LogUtils.d(TAG, "onCreate() 开始初始化");
setContentView(R.layout.activity_background_settings); setContentView(R.layout.activity_background_settings);
// 初始化核心组件 // 初始化核心组件
@@ -94,20 +93,20 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
// 初始化界面与事件 // 初始化界面与事件
initToolbar(); initToolbar();
initClickListeners(); initClickListeners();
LogUtils.d(TAG, "初始化 界面与事件绑定完成"); LogUtils.d(TAG, "界面与事件绑定完成");
// 处理分享意图或初始化预览 // 处理分享意图或初始化预览
handleIntentOrPreview(); handleIntentOrPreview();
// 初始化预览环境并刷新 // 初始化预览环境并刷新
initPreviewEnvironment(); initPreviewEnvironment();
LogUtils.d(TAG, "生命周期 onCreate() 初始化完成"); LogUtils.d(TAG, "onCreate() 初始化完成");
} }
@Override @Override
protected void onPostCreate(Bundle savedInstanceState) { protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState); super.onPostCreate(savedInstanceState);
LogUtils.d(TAG, "生命周期 onPostCreate() 执行双重刷新预览"); LogUtils.d(TAG, "onPostCreate() 执行双重刷新预览");
// 监听视图布局完成事件 // 监听视图布局完成事件
mBackgroundView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { mBackgroundView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@@ -139,24 +138,24 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
LogUtils.d(TAG, String.format("回调触发 onActivityResult() | requestCode=%d | resultCode=%d", requestCode, resultCode)); LogUtils.d(TAG, String.format("onActivityResult() | requestCode=%d | resultCode=%d", requestCode, resultCode));
try { try {
if (resultCode != RESULT_OK) { if (resultCode != RESULT_OK) {
LogUtils.d(TAG, "回调处理 结果非RESULT_OK执行取消逻辑"); LogUtils.d(TAG, "结果非RESULT_OK执行取消逻辑");
handleOperationCancelOrFail(); handleOperationCancelOrFail();
return; return;
} }
handleActivityResult(requestCode, data); handleActivityResult(requestCode, data);
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, String.format("回调异常 onActivityResult() | requestCode=%d | 异常信息=%s", requestCode, e.getMessage())); LogUtils.e(TAG, String.format("onActivityResult() 异常 | requestCode=%d | 异常信息=%s", requestCode, e.getMessage()));
ToastUtils.show("操作失败"); ToastUtils.show("操作失败");
} }
} }
@Override @Override
public void finish() { public void finish() {
LogUtils.d(TAG, String.format("生命周期 finish() 触发 | isCommitSettings=%b | isPreviewBackgroundChanged=%b", isCommitSettings, isPreviewBackgroundChanged)); LogUtils.d(TAG, String.format("finish() | isCommitSettings=%b | isPreviewBackgroundChanged=%b", isCommitSettings, isPreviewBackgroundChanged));
if (isCommitSettings) { if (isCommitSettings) {
super.finish(); super.finish();
} else { } else {
@@ -168,7 +167,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
@Override @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults); super.onRequestPermissionsResult(requestCode, permissions, grantResults);
LogUtils.d(TAG, String.format("权限回调 onRequestPermissionsResult() | requestCode=%d | 权限数量=%d", requestCode, permissions.length)); LogUtils.d(TAG, String.format("onRequestPermissionsResult() | requestCode=%d | 权限数量=%d", requestCode, permissions.length));
if (requestCode == REQUEST_CAMERA_PERMISSION) { if (requestCode == REQUEST_CAMERA_PERMISSION) {
handleCameraPermissionResult(grantResults); handleCameraPermissionResult(grantResults);
} }
@@ -176,9 +175,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
// ====================== 界面初始化方法Toolbar + 点击事件)====================== // ====================== 界面初始化方法Toolbar + 点击事件)======================
private void initToolbar() { private void initToolbar() {
LogUtils.d(TAG, "initToolbar() 开始初始化");
mToolbar = findViewById(R.id.toolbar); mToolbar = findViewById(R.id.toolbar);
if (mToolbar == null) { if (mToolbar == null) {
LogUtils.e(TAG, "初始化异常 initToolbar() | Toolbar未找到"); LogUtils.e(TAG, "initToolbar() | Toolbar未找到");
return; return;
} }
setSupportActionBar(mToolbar); setSupportActionBar(mToolbar);
@@ -192,11 +192,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
finish(); finish();
} }
}); });
LogUtils.d(TAG, "界面初始化 initToolbar() | 配置完成"); LogUtils.d(TAG, "initToolbar() 配置完成");
} }
private void initClickListeners() { private void initClickListeners() {
LogUtils.d(TAG, "界面初始化 initClickListeners() | 开始绑定按钮点击事件"); LogUtils.d(TAG, "initClickListeners() 开始绑定按钮点击事件");
// 绑定所有按钮点击事件 // 绑定所有按钮点击事件
bindClickListener(R.id.activitybackgroundsettingsAButton1, onOriginNullClickListener); bindClickListener(R.id.activitybackgroundsettingsAButton1, onOriginNullClickListener);
bindClickListener(R.id.activitybackgroundsettingsAButton2, onReceivedPictureClickListener); bindClickListener(R.id.activitybackgroundsettingsAButton2, onReceivedPictureClickListener);
@@ -208,17 +208,18 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
bindClickListener(R.id.activitybackgroundsettingsAButton8, onPixelPickerClickListener); bindClickListener(R.id.activitybackgroundsettingsAButton8, onPixelPickerClickListener);
bindClickListener(R.id.activitybackgroundsettingsAButton9, onColorPaletteClickListener); bindClickListener(R.id.activitybackgroundsettingsAButton9, onColorPaletteClickListener);
bindClickListener(R.id.activitybackgroundsettingsAButton10, onCleanPixelClickListener); bindClickListener(R.id.activitybackgroundsettingsAButton10, onCleanPixelClickListener);
LogUtils.d(TAG, "界面初始化 initClickListeners() | 按钮点击事件绑定完成"); LogUtils.d(TAG, "initClickListeners() 按钮点击事件绑定完成");
} }
// 通用按钮绑定工具方法 // 通用按钮绑定工具方法
private void bindClickListener(int resId, View.OnClickListener listener) { private void bindClickListener(int resId, View.OnClickListener listener) {
LogUtils.d(TAG, String.format("bindClickListener() | resId=%d", resId));
View view = findViewById(resId); View view = findViewById(resId);
if (view != null) { if (view != null) {
view.setOnClickListener(listener); view.setOnClickListener(listener);
LogUtils.d(TAG, String.format("绑定成功 bindClickListener() | resId=%d", resId)); LogUtils.d(TAG, String.format("bindClickListener() | resId=%d 绑定成功", resId));
} else { } else {
LogUtils.e(TAG, String.format("绑定异常 bindClickListener() | 未找到视图:%d", resId)); LogUtils.e(TAG, String.format("bindClickListener() | 未找到视图:%d", resId));
} }
} }
@@ -226,10 +227,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onOriginNullClickListener = new View.OnClickListener() { private View.OnClickListener onOriginNullClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onOriginNullClickListener() | 取消背景图片"); LogUtils.d(TAG, "onOriginNullClickListener() | 取消背景图片");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onOriginNullClickListener() | 预览Bean为空"); LogUtils.e(TAG, "onOriginNullClickListener() | 预览Bean为空");
return; return;
} }
previewBean.setIsUseBackgroundFile(false); previewBean.setIsUseBackgroundFile(false);
@@ -242,7 +243,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onSelectPictureClickListener = new View.OnClickListener() { private View.OnClickListener onSelectPictureClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onSelectPictureClickListener() | 选择图片"); LogUtils.d(TAG, "onSelectPictureClickListener() | 选择图片");
launchImageSelector(); launchImageSelector();
} }
}; };
@@ -250,7 +251,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onNetworkBackgroundDialog = new View.OnClickListener() { private View.OnClickListener onNetworkBackgroundDialog = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onNetworkBackgroundDialog() | 打开网络背景对话框"); LogUtils.d(TAG, "onNetworkBackgroundDialog() | 打开网络背景对话框");
NetworkBackgroundDialog networkBackgroundDialog = new NetworkBackgroundDialog(BackgroundSettingsActivity.this, new NetworkBackgroundDialog.OnDialogClickListener() { NetworkBackgroundDialog networkBackgroundDialog = new NetworkBackgroundDialog(BackgroundSettingsActivity.this, new NetworkBackgroundDialog.OnDialogClickListener() {
@Override @Override
public void onConfirm(String szConfirmFilePath) { public void onConfirm(String szConfirmFilePath) {
@@ -273,7 +274,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onCropPictureClickListener = new View.OnClickListener() { private View.OnClickListener onCropPictureClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onCropPictureClickListener() | 固定比例裁剪"); LogUtils.d(TAG, "onCropPictureClickListener() | 固定比例裁剪");
startImageCrop(false); startImageCrop(false);
} }
}; };
@@ -281,7 +282,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onCropFreePictureClickListener = new View.OnClickListener() { private View.OnClickListener onCropFreePictureClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onCropFreePictureClickListener() | 自由裁剪"); LogUtils.d(TAG, "onCropFreePictureClickListener() | 自由裁剪");
startImageCrop(true); startImageCrop(true);
} }
}; };
@@ -289,11 +290,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onTakePhotoClickListener = new View.OnClickListener() { private View.OnClickListener onTakePhotoClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onTakePhotoClickListener() | 拍照"); LogUtils.d(TAG, "onTakePhotoClickListener() | 拍照");
// 动态申请相机权限 // 动态申请相机权限
if (ContextCompat.checkSelfPermission(BackgroundSettingsActivity.this, Manifest.permission.CAMERA) if (ContextCompat.checkSelfPermission(BackgroundSettingsActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) { != PackageManager.PERMISSION_GRANTED) {
LogUtils.d(TAG, "拍照准备 onTakePhotoClickListener() | 相机权限未授予,发起申请"); LogUtils.d(TAG, "拍照准备 | 相机权限未授予,发起申请");
ActivityCompat.requestPermissions( ActivityCompat.requestPermissions(
BackgroundSettingsActivity.this, BackgroundSettingsActivity.this,
new String[]{Manifest.permission.CAMERA}, new String[]{Manifest.permission.CAMERA},
@@ -307,10 +308,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onReceivedPictureClickListener = new View.OnClickListener() { private View.OnClickListener onReceivedPictureClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onReceivedPictureClickListener() | 恢复收到的图片"); LogUtils.d(TAG, "onReceivedPictureClickListener() | 恢复收到的图片");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onReceivedPictureClickListener() | 预览Bean为空"); LogUtils.e(TAG, "onReceivedPictureClickListener() | 预览Bean为空");
return; return;
} }
previewBean.setIsUseBackgroundFile(true); previewBean.setIsUseBackgroundFile(true);
@@ -323,10 +324,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onPixelPickerClickListener = new View.OnClickListener() { private View.OnClickListener onPixelPickerClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onPixelPickerClickListener() | 像素拾取"); LogUtils.d(TAG, "onPixelPickerClickListener() | 像素拾取");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onPixelPickerClickListener() | 预览Bean为空"); LogUtils.e(TAG, "onPixelPickerClickListener() | 预览Bean为空");
ToastUtils.show("无有效图片可拾取像素"); ToastUtils.show("无有效图片可拾取像素");
return; return;
} }
@@ -334,23 +335,23 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
File targetFile = new File(targetImagePath); File targetFile = new File(targetImagePath);
if (targetFile == null || !targetFile.exists() || targetFile.length() <= 0) { if (targetFile == null || !targetFile.exists() || targetFile.length() <= 0) {
ToastUtils.show("无有效图片可拾取像素"); ToastUtils.show("无有效图片可拾取像素");
LogUtils.e(TAG, String.format("像素拾取失败 onPixelPickerClickListener() | 文件无效:%s", targetImagePath)); LogUtils.e(TAG, String.format("像素拾取失败 | 文件无效:%s", targetImagePath));
return; return;
} }
Intent intent = new Intent(getApplicationContext(), PixelPickerActivity.class); Intent intent = new Intent(getApplicationContext(), PixelPickerActivity.class);
intent.putExtra("imagePath", targetImagePath); intent.putExtra("imagePath", targetImagePath);
startActivityForResult(intent, REQUEST_PIXELPICKER); startActivityForResult(intent, REQUEST_PIXELPICKER);
LogUtils.d(TAG, String.format("像素拾取启动 onPixelPickerClickListener() | 路径:%s", targetImagePath)); LogUtils.d(TAG, String.format("像素拾取启动 | 路径:%s", targetImagePath));
} }
}; };
private View.OnClickListener onCleanPixelClickListener = new View.OnClickListener() { private View.OnClickListener onCleanPixelClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onCleanPixelClickListener() | 清空像素颜色"); LogUtils.d(TAG, "onCleanPixelClickListener() | 清空像素颜色");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onCleanPixelClickListener() | 预览Bean为空"); LogUtils.e(TAG, "onCleanPixelClickListener() | 预览Bean为空");
return; return;
} }
int oldColor = previewBean.getPixelColor(); int oldColor = previewBean.getPixelColor();
@@ -359,21 +360,21 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
doubleRefreshPreview(); doubleRefreshPreview();
isPreviewBackgroundChanged = true; isPreviewBackgroundChanged = true;
ToastUtils.show("像素颜色已清空"); ToastUtils.show("像素颜色已清空");
LogUtils.d(TAG, String.format("像素清空 onCleanPixelClickListener() | 旧颜色:#%08X", oldColor)); LogUtils.d(TAG, String.format("像素清空 | 旧颜色:#%08X", oldColor));
} }
}; };
private View.OnClickListener onColorPaletteClickListener = new View.OnClickListener() { private View.OnClickListener onColorPaletteClickListener = new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onColorPaletteClickListener() | 调色板按钮"); LogUtils.d(TAG, "onColorPaletteClickListener() | 调色板按钮");
final BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); final BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onColorPaletteClickListener() | 预览Bean为空"); LogUtils.e(TAG, "onColorPaletteClickListener() | 预览Bean为空");
return; return;
} }
int initialColor = previewBean.getPixelColor(); int initialColor = previewBean.getPixelColor();
LogUtils.d(TAG, String.format("调色板 onColorPaletteClickListener() | 初始颜色:#%08X", initialColor)); LogUtils.d(TAG, String.format("调色板 | 初始颜色:#%08X", initialColor));
ColorPaletteDialog dialog = new ColorPaletteDialog(BackgroundSettingsActivity.this, initialColor, new ColorPaletteDialog.OnColorSelectedListener() { ColorPaletteDialog dialog = new ColorPaletteDialog(BackgroundSettingsActivity.this, initialColor, new ColorPaletteDialog.OnColorSelectedListener() {
@Override @Override
public void onColorSelected(int color) { public void onColorSelected(int color) {
@@ -381,11 +382,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
mBgSourceUtils.saveSettings(); mBgSourceUtils.saveSettings();
doubleRefreshPreview(); doubleRefreshPreview();
isPreviewBackgroundChanged = true; isPreviewBackgroundChanged = true;
LogUtils.d(TAG, String.format("颜色选择 onColorSelected() | 选中颜色:#%08X", color)); LogUtils.d(TAG, String.format("颜色选择 | 选中颜色:#%08X", color));
} }
}); });
dialog.show(); dialog.show();
LogUtils.d(TAG, "调色板 onColorPaletteClickListener() | 对话框已显示"); LogUtils.d(TAG, "调色板 | 对话框已显示");
} }
}; };
@@ -396,9 +397,9 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 适配后的Uri失败返回null * @return 适配后的Uri失败返回null
*/ */
public Uri getFileProviderUri(File file) { public Uri getFileProviderUri(File file) {
LogUtils.d(TAG, String.format("工具方法 getFileProviderUri() | 文件路径:%s", (file != null ? file.getAbsolutePath() : "null"))); LogUtils.d(TAG, String.format("getFileProviderUri() | 文件路径:%s", (file != null ? file.getAbsolutePath() : "null")));
if (file == null) { if (file == null) {
LogUtils.e(TAG, "工具异常 getFileProviderUri() | 文件为空"); LogUtils.e(TAG, "getFileProviderUri() | 文件为空");
return null; return null;
} }
try { try {
@@ -409,7 +410,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
return Uri.fromFile(file); return Uri.fromFile(file);
} }
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, String.format("工具异常 getFileProviderUri() | 生成Uri失败%s", e.getMessage())); LogUtils.e(TAG, String.format("getFileProviderUri() | 生成Uri失败%s", e.getMessage()));
return null; return null;
} }
} }
@@ -421,7 +422,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
*/ */
private boolean isBitmapValid(Bitmap bitmap) { private boolean isBitmapValid(Bitmap bitmap) {
boolean isValid = bitmap != null && !bitmap.isRecycled(); boolean isValid = bitmap != null && !bitmap.isRecycled();
LogUtils.d(TAG, String.format("工具方法 isBitmapValid() | Bitmap有效性校验%b", isValid)); LogUtils.d(TAG, String.format("isBitmapValid() | Bitmap有效性校验%b", isValid));
return isValid; return isValid;
} }
@@ -429,7 +430,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 双重刷新预览,确保背景加载最新数据 * 双重刷新预览,确保背景加载最新数据
*/ */
private void doubleRefreshPreview() { private void doubleRefreshPreview() {
LogUtils.d(TAG, "工具方法 doubleRefreshPreview() | 开始双重刷新预览"); LogUtils.d(TAG, "doubleRefreshPreview() 开始双重刷新预览");
if (mBgSourceUtils == null || mBackgroundView == null || isFinishing()) { if (mBgSourceUtils == null || mBackgroundView == null || isFinishing()) {
LogUtils.w(TAG, "双重刷新 跳过对象为空或Activity已结束"); LogUtils.w(TAG, "双重刷新 跳过对象为空或Activity已结束");
return; return;
@@ -440,9 +441,9 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
mBgSourceUtils.loadSettings(); mBgSourceUtils.loadSettings();
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
mBackgroundView.loadByBackgroundBean(previewBean, true); mBackgroundView.loadByBackgroundBean(previewBean, true);
LogUtils.d(TAG, "双重刷新 doubleRefreshPreview() | 第一重完成"); LogUtils.d(TAG, "双重刷新 第一重完成");
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, String.format("双重刷新 doubleRefreshPreview() | 第一重异常:%s", e.getMessage())); LogUtils.e(TAG, String.format("双重刷新 第一重异常:%s", e.getMessage()));
return; return;
} }
@@ -455,9 +456,9 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
mBgSourceUtils.loadSettings(); mBgSourceUtils.loadSettings();
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
mBackgroundView.loadByBackgroundBean(previewBean, true); mBackgroundView.loadByBackgroundBean(previewBean, true);
LogUtils.d(TAG, "双重刷新 doubleRefreshPreview() | 第二重完成"); LogUtils.d(TAG, "双重刷新 第二重完成");
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, String.format("双重刷新 doubleRefreshPreview() | 第二重异常:%s", e.getMessage())); LogUtils.e(TAG, String.format("双重刷新 第二重异常:%s", e.getMessage()));
} }
} }
} }
@@ -469,28 +470,30 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 初始化核心组件(工具类+视图) * 初始化核心组件(工具类+视图)
*/ */
private void initCoreComponents() { private void initCoreComponents() {
LogUtils.d(TAG, "initCoreComponents() 开始初始化");
// 初始化视图 // 初始化视图
mBackgroundView = findViewById(R.id.background_view); mBackgroundView = findViewById(R.id.background_view);
if (mBackgroundView == null) { if (mBackgroundView == null) {
LogUtils.e(TAG, "初始化异常 initCoreComponents() | BackgroundView未找到"); LogUtils.e(TAG, "initCoreComponents() | BackgroundView未找到");
} }
// 初始化工具类 // 初始化工具类
mBgSourceUtils = BackgroundSourceUtils.getInstance(this); mBgSourceUtils = BackgroundSourceUtils.getInstance(this);
mBgSourceUtils.loadSettings(); mBgSourceUtils.loadSettings();
mBitmapCache = BitmapCacheUtils.getInstance(); mBitmapCache = BitmapCacheUtils.getInstance();
LogUtils.d(TAG, "初始化 initCoreComponents() | 视图与工具类加载完成"); LogUtils.d(TAG, "initCoreComponents() 视图与工具类加载完成");
} }
/** /**
* 处理意图或初始化预览 * 处理意图或初始化预览
*/ */
private void handleIntentOrPreview() { private void handleIntentOrPreview() {
LogUtils.d(TAG, "handleIntentOrPreview() 开始处理");
if (handleShareIntent()) { if (handleShareIntent()) {
ToastUtils.show("已接收分享图片"); ToastUtils.show("已接收分享图片");
LogUtils.d(TAG, "意图处理 handleIntentOrPreview() | 处理分享意图成功"); LogUtils.d(TAG, "handleIntentOrPreview() | 处理分享意图成功");
} else { } else {
mBgSourceUtils.setCurrentSourceToPreview(); mBgSourceUtils.setCurrentSourceToPreview();
LogUtils.d(TAG, "意图处理 handleIntentOrPreview() | 加载当前背景配置"); LogUtils.d(TAG, "handleIntentOrPreview() | 加载当前背景配置");
} }
} }
@@ -498,10 +501,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 初始化预览环境 * 初始化预览环境
*/ */
private void initPreviewEnvironment() { private void initPreviewEnvironment() {
LogUtils.d(TAG, "initPreviewEnvironment() 开始初始化");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
mBgSourceUtils.createAndUpdatePreviewEnvironmentForCropping(previewBean); mBgSourceUtils.createAndUpdatePreviewEnvironmentForCropping(previewBean);
doubleRefreshPreview(); doubleRefreshPreview();
LogUtils.d(TAG, "预览环境 initPreviewEnvironment() | 初始化完成"); LogUtils.d(TAG, "initPreviewEnvironment() 初始化完成");
} }
/** /**
@@ -509,11 +513,12 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 处理成功返回true否则false * @return 处理成功返回true否则false
*/ */
private boolean handleShareIntent() { private boolean handleShareIntent() {
LogUtils.d(TAG, "handleShareIntent() 开始处理");
Intent intent = getIntent(); Intent intent = getIntent();
if (intent != null) { if (intent != null) {
String action = intent.getAction(); String action = intent.getAction();
String type = intent.getType(); String type = intent.getType();
LogUtils.d(TAG, String.format("分享处理 handleShareIntent() | action%stype%s", action, type)); LogUtils.d(TAG, String.format("分享处理 | action%stype%s", action, type));
if (Intent.ACTION_SEND.equals(action) && type != null && isImageType(type)) { if (Intent.ACTION_SEND.equals(action) && type != null && isImageType(type)) {
showSharePreviewDialog(); showSharePreviewDialog();
return true; return true;
@@ -526,18 +531,18 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 显示分享图片预览对话框 * 显示分享图片预览对话框
*/ */
private void showSharePreviewDialog() { private void showSharePreviewDialog() {
LogUtils.d(TAG, "工具方法 showSharePreviewDialog()"); LogUtils.d(TAG, "showSharePreviewDialog() 开始显示");
BackgroundPicturePreviewDialog dlg = new BackgroundPicturePreviewDialog(this, new BackgroundPicturePreviewDialog.IOnRecivedPictureListener() { BackgroundPicturePreviewDialog dlg = new BackgroundPicturePreviewDialog(this, new BackgroundPicturePreviewDialog.IOnRecivedPictureListener() {
@Override @Override
public void onAcceptRecivedPicture(Uri uriRecivedPicture) { public void onAcceptRecivedPicture(Uri uriRecivedPicture) {
LogUtils.d(TAG, String.format("分享确认 onAcceptRecivedPicture() | Uri%s", uriRecivedPicture.toString())); LogUtils.d(TAG, String.format("分享确认 | Uri%s", uriRecivedPicture.toString()));
if (putUriFileToPreviewSource(uriRecivedPicture)) { if (putUriFileToPreviewSource(uriRecivedPicture)) {
startImageCrop(false); startImageCrop(false);
} }
} }
}); });
dlg.show(); dlg.show();
LogUtils.d(TAG, "分享处理 showSharePreviewDialog() | 显示图片预览对话框"); LogUtils.d(TAG, "分享处理 | 显示图片预览对话框");
} }
/** /**
@@ -550,7 +555,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
return false; return false;
} }
String lowerMimeType = mimeType.toLowerCase(); String lowerMimeType = mimeType.toLowerCase();
LogUtils.d(TAG, String.format("工具方法 isImageType() | mimeType: %s, lowerMimeType: %s", mimeType, lowerMimeType)); LogUtils.d(TAG, String.format("isImageType() | mimeType: %s, lowerMimeType: %s", mimeType, lowerMimeType));
return lowerMimeType.startsWith("image/"); return lowerMimeType.startsWith("image/");
} }
@@ -558,7 +563,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 启动图片选择器 * 启动图片选择器
*/ */
private void launchImageSelector() { private void launchImageSelector() {
LogUtils.d(TAG, "业务逻辑 launchImageSelector() | 启动图片选择器"); LogUtils.d(TAG, "launchImageSelector() 启动图片选择器");
Intent[] intents = createImageSelectorIntents(); Intent[] intents = createImageSelectorIntents();
Intent validIntent = findValidIntent(intents); Intent validIntent = findValidIntent(intents);
@@ -574,6 +579,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 意图数组 * @return 意图数组
*/ */
private Intent[] createImageSelectorIntents() { private Intent[] createImageSelectorIntents() {
LogUtils.d(TAG, "createImageSelectorIntents() 开始创建");
Intent[] intents = new Intent[3]; Intent[] intents = new Intent[3];
// ACTION_GET_CONTENT // ACTION_GET_CONTENT
Intent getContentIntent = new Intent(Intent.ACTION_GET_CONTENT); Intent getContentIntent = new Intent(Intent.ACTION_GET_CONTENT);
@@ -596,7 +602,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
openDocIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); openDocIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
intents[2] = openDocIntent; intents[2] = openDocIntent;
} }
LogUtils.d(TAG, "业务逻辑 createImageSelectorIntents() | 意图数组创建完成"); LogUtils.d(TAG, "createImageSelectorIntents() 意图数组创建完成");
return intents; return intents;
} }
@@ -606,13 +612,14 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 有效意图无则返回null * @return 有效意图无则返回null
*/ */
private Intent findValidIntent(Intent[] intents) { private Intent findValidIntent(Intent[] intents) {
LogUtils.d(TAG, "findValidIntent() 开始查找");
for (Intent intent : intents) { for (Intent intent : intents) {
if (intent != null && intent.resolveActivity(getPackageManager()) != null) { if (intent != null && intent.resolveActivity(getPackageManager()) != null) {
LogUtils.d(TAG, "业务逻辑 findValidIntent() | 找到有效意图"); LogUtils.d(TAG, "findValidIntent() | 找到有效意图");
return intent; return intent;
} }
} }
LogUtils.d(TAG, "业务逻辑 findValidIntent() | 无有效意图"); LogUtils.d(TAG, "findValidIntent() | 无有效意图");
return null; return null;
} }
@@ -621,17 +628,18 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param validIntent 有效意图 * @param validIntent 有效意图
*/ */
private void launchImageChooser(Intent validIntent) { private void launchImageChooser(Intent validIntent) {
LogUtils.d(TAG, "launchImageChooser() 启动选择器");
Intent chooser = Intent.createChooser(validIntent, "选择图片"); Intent chooser = Intent.createChooser(validIntent, "选择图片");
chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
startActivityForResult(chooser, REQUEST_SELECT_PICTURE); startActivityForResult(chooser, REQUEST_SELECT_PICTURE);
LogUtils.d(TAG, "选图意图 launchImageChooser() | 启动图片选择"); LogUtils.d(TAG, "launchImageChooser() | 启动图片选择");
} }
/** /**
* 显示无相册应用提示对话框 * 显示无相册应用提示对话框
*/ */
private void showNoGalleryDialog() { private void showNoGalleryDialog() {
LogUtils.d(TAG, "选图意图 showNoGalleryDialog() | 无相册应用"); LogUtils.d(TAG, "showNoGalleryDialog() | 无相册应用");
runOnUiThread(new Runnable() { runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
@@ -655,14 +663,15 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 启动应用商店下载相册 * 启动应用商店下载相册
*/ */
private void launchGalleryMarket() { private void launchGalleryMarket() {
LogUtils.d(TAG, "launchGalleryMarket() 启动应用商店");
Intent marketIntent = new Intent(Intent.ACTION_VIEW); Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri.parse("market://details?id=com.android.gallery3d")); marketIntent.setData(Uri.parse("market://details?id=com.android.gallery3d"));
if (marketIntent.resolveActivity(getPackageManager()) != null) { if (marketIntent.resolveActivity(getPackageManager()) != null) {
startActivity(marketIntent); startActivity(marketIntent);
LogUtils.d(TAG, "应用商店 launchGalleryMarket() | 启动成功"); LogUtils.d(TAG, "launchGalleryMarket() | 启动成功");
} else { } else {
ToastUtils.show("无法打开应用商店"); ToastUtils.show("无法打开应用商店");
LogUtils.e(TAG, "应用商店 launchGalleryMarket() | 启动失败"); LogUtils.e(TAG, "launchGalleryMarket() | 启动失败");
} }
} }
@@ -670,8 +679,8 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 处理操作取消或失败 * 处理操作取消或失败
*/ */
private void handleOperationCancelOrFail() { private void handleOperationCancelOrFail() {
LogUtils.d(TAG, "handleOperationCancelOrFail() 操作取消或失败");
mBgSourceUtils.setCurrentSourceToPreview(); mBgSourceUtils.setCurrentSourceToPreview();
LogUtils.d(TAG, "业务逻辑 handleOperationCancelOrFail() | 操作取消或失败,恢复预览");
ToastUtils.show("操作取消或失败"); ToastUtils.show("操作取消或失败");
doubleRefreshPreview(); doubleRefreshPreview();
} }
@@ -680,10 +689,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 处理拍照逻辑(权限通过后执行) * 处理拍照逻辑(权限通过后执行)
*/ */
void handleTakePhoto() { void handleTakePhoto() {
LogUtils.d(TAG, "业务逻辑 handleTakePhoto() | 开始处理拍照"); LogUtils.d(TAG, "handleTakePhoto() 开始处理拍照");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "拍照失败 handleTakePhoto() | 预览Bean为空"); LogUtils.e(TAG, "handleTakePhoto() | 预览Bean为空");
ToastUtils.show("拍照文件创建失败"); ToastUtils.show("拍照文件创建失败");
return; return;
} }
@@ -691,7 +700,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
File takePhotoFile = new File(previewBean.getBackgroundFilePath()); File takePhotoFile = new File(previewBean.getBackgroundFilePath());
if (!takePhotoFile.exists()) { if (!takePhotoFile.exists()) {
ToastUtils.show("拍照文件创建失败"); ToastUtils.show("拍照文件创建失败");
LogUtils.e(TAG, String.format("拍照失败 handleTakePhoto() | 文件不存在:%s", takePhotoFile.getAbsolutePath())); LogUtils.e(TAG, String.format("handleTakePhoto() | 文件不存在:%s", takePhotoFile.getAbsolutePath()));
return; return;
} }
@@ -703,11 +712,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
} }
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
LogUtils.d(TAG, String.format("拍照启动 handleTakePhoto() | Uri%s", photoUri.toString())); LogUtils.d(TAG, String.format("handleTakePhoto() | Uri%s", photoUri.toString()));
} catch (Exception e) { } catch (Exception e) {
String errMsg = "拍照启动异常:" + e.getMessage(); String errMsg = "拍照启动异常:" + e.getMessage();
ToastUtils.show(errMsg.substring(0, 20)); ToastUtils.show(errMsg.substring(0, 20));
LogUtils.e(TAG, String.format("拍照失败 handleTakePhoto() | %s", e.getMessage())); LogUtils.e(TAG, String.format("handleTakePhoto() | %s", e.getMessage()));
} }
} }
@@ -717,7 +726,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param data 回调数据 * @param data 回调数据
*/ */
private void handleActivityResult(int requestCode, Intent data) { private void handleActivityResult(int requestCode, Intent data) {
LogUtils.d(TAG, String.format("业务逻辑 handleActivityResult() | 处理请求码:%d", requestCode)); LogUtils.d(TAG, String.format("handleActivityResult() | 处理请求码:%d", requestCode));
switch (requestCode) { switch (requestCode) {
case REQUEST_SELECT_PICTURE: case REQUEST_SELECT_PICTURE:
handleSelectPictureResult(data); handleSelectPictureResult(data);
@@ -732,7 +741,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
handlePixelPickerResult(); handlePixelPickerResult();
break; break;
default: default:
LogUtils.d(TAG, String.format("回调忽略 handleActivityResult() | 未知requestCode%d", requestCode)); LogUtils.d(TAG, String.format("handleActivityResult() | 未知requestCode%d", requestCode));
break; break;
} }
} }
@@ -742,10 +751,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param data 回调数据 * @param data 回调数据
*/ */
private void handleTakePhotoResult(Intent data) { private void handleTakePhotoResult(Intent data) {
LogUtils.d(TAG, "业务逻辑 handleTakePhotoResult() | 处理拍照结果"); LogUtils.d(TAG, "handleTakePhotoResult() 处理拍照结果");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "拍照结果处理 handleTakePhotoResult() | 预览Bean为空"); LogUtils.e(TAG, "handleTakePhotoResult() | 预览Bean为空");
return; return;
} }
@@ -755,7 +764,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
doubleRefreshPreview(); doubleRefreshPreview();
startImageCrop(false); startImageCrop(false);
LogUtils.d(TAG, "拍照完成 handleTakePhotoResult() | 已启动裁剪"); LogUtils.d(TAG, "handleTakePhotoResult() | 已启动裁剪");
} }
/** /**
@@ -763,30 +772,30 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param data 回调数据 * @param data 回调数据
*/ */
private void handleSelectPictureResult(Intent data) { private void handleSelectPictureResult(Intent data) {
LogUtils.d(TAG, "业务逻辑 handleSelectPictureResult() | 处理选图结果"); LogUtils.d(TAG, "handleSelectPictureResult() 处理选图结果");
Uri selectedImage = data.getData(); Uri selectedImage = data.getData();
if (selectedImage == null) { if (selectedImage == null) {
ToastUtils.show("图片Uri为空"); ToastUtils.show("图片Uri为空");
LogUtils.e(TAG, "选图结果 handleSelectPictureResult() | Uri为空"); LogUtils.e(TAG, "handleSelectPictureResult() | Uri为空");
return; return;
} }
LogUtils.d(TAG, String.format("选图回调 handleSelectPictureResult() | 系统返回Uri : %s", selectedImage.toString())); LogUtils.d(TAG, String.format("handleSelectPictureResult() | 系统返回Uri : %s", selectedImage.toString()));
// 申请持久化权限API33+ // 申请持久化权限API33+
if (Build.VERSION.SDK_INT >= SDK_VERSION_TIRAMISU) { if (Build.VERSION.SDK_INT >= SDK_VERSION_TIRAMISU) {
getContentResolver().takePersistableUriPermission( getContentResolver().takePersistableUriPermission(
selectedImage, selectedImage,
Intent.FLAG_GRANT_READ_URI_PERMISSION); Intent.FLAG_GRANT_READ_URI_PERMISSION);
LogUtils.d(TAG, "选图权限 handleSelectPictureResult() | 已添加持久化权限"); LogUtils.d(TAG, "handleSelectPictureResult() | 已添加持久化权限");
} }
// 同步文件并启动裁剪 // 同步文件并启动裁剪
if (putUriFileToPreviewSource(selectedImage)) { if (putUriFileToPreviewSource(selectedImage)) {
LogUtils.d(TAG, "选图同步 handleSelectPictureResult() | 路径绑定完成"); LogUtils.d(TAG, "handleSelectPictureResult() | 路径绑定完成");
startImageCrop(false); startImageCrop(false);
} else { } else {
ToastUtils.show("图片同步失败"); ToastUtils.show("图片同步失败");
LogUtils.e(TAG, "选图同步 handleSelectPictureResult() | 文件复制失败"); LogUtils.e(TAG, "handleSelectPictureResult() | 文件复制失败");
} }
} }
@@ -796,9 +805,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 同步成功返回true否则false * @return 同步成功返回true否则false
*/ */
private boolean putUriFileToPreviewSource(Uri srcUriFile) { private boolean putUriFileToPreviewSource(Uri srcUriFile) {
LogUtils.d(TAG, String.format("putUriFileToPreviewSource() | 源Uri%s", srcUriFile.toString()));
String filePath = UriUtils.getFilePathFromUri(this, srcUriFile); String filePath = UriUtils.getFilePathFromUri(this, srcUriFile);
if (TextUtils.isEmpty(filePath)) { if (TextUtils.isEmpty(filePath)) {
LogUtils.e(TAG, "选图同步 putUriFileToPreviewSource() | Uri解析路径为空"); LogUtils.e(TAG, "putUriFileToPreviewSource() | Uri解析路径为空");
return false; return false;
} }
File srcFile = new File(filePath); File srcFile = new File(filePath);
@@ -811,16 +821,16 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 同步成功返回true否则false * @return 同步成功返回true否则false
*/ */
private boolean putUriFileToPreviewSource(File srcFile) { private boolean putUriFileToPreviewSource(File srcFile) {
LogUtils.d(TAG, String.format("选图同步 putUriFileToPreviewSource() | 源文件:%s", srcFile.getAbsolutePath())); LogUtils.d(TAG, String.format("putUriFileToPreviewSource() | 源文件:%s", srcFile.getAbsolutePath()));
mBgSourceUtils.loadSettings(); mBgSourceUtils.loadSettings();
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
File dstFile = new File(previewBean.getBackgroundFilePath()); File dstFile = new File(previewBean.getBackgroundFilePath());
LogUtils.d(TAG, String.format("选图同步 putUriFileToPreviewSource() | 目标文件:%s", dstFile.getAbsolutePath())); LogUtils.d(TAG, String.format("putUriFileToPreviewSource() | 目标文件:%s", dstFile.getAbsolutePath()));
if (FileUtils.copyFile(srcFile, dstFile)) { if (FileUtils.copyFile(srcFile, dstFile)) {
LogUtils.d(TAG, "选图同步 putUriFileToPreviewSource() | 文件拷贝成功"); LogUtils.d(TAG, "putUriFileToPreviewSource() | 文件拷贝成功");
return true; return true;
} }
LogUtils.d(TAG, "选图同步 putUriFileToPreviewSource() | 文件无法拷贝"); LogUtils.d(TAG, "putUriFileToPreviewSource() | 文件无法拷贝");
return false; return false;
} }
@@ -829,10 +839,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param data 回调数据 * @param data 回调数据
*/ */
private void handleCropImageResult(Intent data) { private void handleCropImageResult(Intent data) {
LogUtils.d(TAG, "业务逻辑 handleCropImageResult() | 处理裁剪结果"); LogUtils.d(TAG, "handleCropImageResult() 处理裁剪结果");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "裁剪结果处理 handleCropImageResult() | 预览Bean为空"); LogUtils.e(TAG, "handleCropImageResult() | 预览Bean为空");
handleOperationCancelOrFail(); handleOperationCancelOrFail();
return; return;
} }
@@ -856,8 +866,8 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param fileSize 文件大小 * @param fileSize 文件大小
*/ */
private void handleCropSuccess(BackgroundBean previewBean, long fileSize) { private void handleCropSuccess(BackgroundBean previewBean, long fileSize) {
LogUtils.d(TAG, String.format("handleCropSuccess() | 裁剪成功,文件大小:%d", fileSize));
isPreviewBackgroundChanged = true; isPreviewBackgroundChanged = true;
LogUtils.d(TAG, String.format("裁剪结果 handleCropSuccess() | 裁剪成功,文件大小:%d", fileSize));
previewBean.setIsUseBackgroundFile(true); previewBean.setIsUseBackgroundFile(true);
previewBean.setIsUseBackgroundScaledCompressFile(true); previewBean.setIsUseBackgroundScaledCompressFile(true);
mBgSourceUtils.saveSettings(); mBgSourceUtils.saveSettings();
@@ -871,15 +881,15 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param fileSize 文件大小 * @param fileSize 文件大小
*/ */
private void handleCropFailure(boolean isFileExist, boolean isFileReadable, long fileSize) { private void handleCropFailure(boolean isFileExist, boolean isFileReadable, long fileSize) {
LogUtils.e(TAG, String.format("handleCropFailure() | 裁剪失败,文件状态:存在=%b可读=%b大小=%d", isFileExist, isFileReadable, fileSize));
handleOperationCancelOrFail(); handleOperationCancelOrFail();
LogUtils.e(TAG, String.format("裁剪结果 handleCropFailure() | 裁剪失败,文件状态:存在=%b可读=%b大小=%d", isFileExist, isFileReadable, fileSize));
} }
/** /**
* 处理像素拾取结果 * 处理像素拾取结果
*/ */
private void handlePixelPickerResult() { private void handlePixelPickerResult() {
LogUtils.d(TAG, "业务逻辑 handlePixelPickerResult() | 处理像素拾取结果"); LogUtils.d(TAG, "handlePixelPickerResult() 处理像素拾取结果");
doubleRefreshPreview(); doubleRefreshPreview();
isPreviewBackgroundChanged = true; isPreviewBackgroundChanged = true;
} }
@@ -889,11 +899,12 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param grantResults 权限结果数组 * @param grantResults 权限结果数组
*/ */
private void handleCameraPermissionResult(int[] grantResults) { private void handleCameraPermissionResult(int[] grantResults) {
LogUtils.d(TAG, "handleCameraPermissionResult() 处理相机权限结果");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
LogUtils.d(TAG, "权限申请 handleCameraPermissionResult() | 相机权限授予成功"); LogUtils.d(TAG, "handleCameraPermissionResult() | 相机权限授予成功");
handleTakePhoto(); handleTakePhoto();
} else { } else {
LogUtils.d(TAG, "权限申请 handleCameraPermissionResult() | 相机权限授予失败"); LogUtils.d(TAG, "handleCameraPermissionResult() | 相机权限授予失败");
ToastUtils.show("相机权限被拒绝,无法拍照"); ToastUtils.show("相机权限被拒绝,无法拍照");
// 引导用户到设置页面开启权限(用户选择不再询问时) // 引导用户到设置页面开启权限(用户选择不再询问时)
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
@@ -906,18 +917,19 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 启动应用设置页面 * 启动应用设置页面
*/ */
private void launchAppSettings() { private void launchAppSettings() {
LogUtils.d(TAG, "launchAppSettings() 启动应用设置页面");
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null); Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri); intent.setData(uri);
startActivity(intent); startActivity(intent);
ToastUtils.show("请在设置中开启相机权限"); ToastUtils.show("请在设置中开启相机权限");
LogUtils.d(TAG, "权限引导 launchAppSettings() | 启动应用设置页面");
} }
/** /**
* 处理Finish确认对话框 * 处理Finish确认对话框
*/ */
private void handleFinishConfirmation() { private void handleFinishConfirmation() {
LogUtils.d(TAG, "handleFinishConfirmation() 处理Finish确认");
if (isPreviewBackgroundChanged) { if (isPreviewBackgroundChanged) {
YesNoAlertDialog.show(this, "背景更换问题", "是否确定背景图片设置?", new YesNoAlertDialog.OnDialogResultListener() { YesNoAlertDialog.show(this, "背景更换问题", "是否确定背景图片设置?", new YesNoAlertDialog.OnDialogResultListener() {
@Override @Override
@@ -944,9 +956,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param isFreeCrop 是否自由裁剪 * @param isFreeCrop 是否自由裁剪
*/ */
private void startImageCrop(boolean isFreeCrop) { private void startImageCrop(boolean isFreeCrop) {
LogUtils.d(TAG, String.format("startImageCrop() | 是否自由裁剪:%b", isFreeCrop));
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean(); BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) { if (previewBean == null) {
LogUtils.e(TAG, "裁剪启动 startImageCrop() | 预览Bean为空"); LogUtils.e(TAG, "startImageCrop() | 预览Bean为空");
ToastUtils.show("裁剪失败:无有效图片"); ToastUtils.show("裁剪失败:无有效图片");
return; return;
} }
@@ -958,7 +971,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
height, height,
isFreeCrop, isFreeCrop,
REQUEST_CROP_IMAGE); REQUEST_CROP_IMAGE);
LogUtils.d(TAG, String.format("裁剪启动 startImageCrop() | 是否自由裁剪:%b目标尺寸:%dx%d", isFreeCrop, width, height)); LogUtils.d(TAG, String.format("startImageCrop() | 目标尺寸:%dx%d", width, height));
} }
} }

View File

@@ -17,10 +17,10 @@ import java.io.Serializable;
* 包含耗电提醒、充电提醒、电量检测、铃声提醒、相框尺寸等核心配置 * 包含耗电提醒、充电提醒、电量检测、铃声提醒、相框尺寸等核心配置
*/ */
public class AppConfigBean extends BaseBean implements Serializable, Parcelable { public class AppConfigBean extends BaseBean implements Serializable, Parcelable {
// ====================== 静态常量(首屏可见,统一管理) ====================== // ====================== 静态常量(首屏可见,统一管理) ======================
// 序列化版本号Serializable 必备,避免反序列化失败) // 序列化版本号Serializable 必备,避免反序列化失败)
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
// 日志标签(全局统一,替换 Log 为 LogUtils // 日志标签(全局统一)
transient public static final String TAG = "AppConfigBean"; transient public static final String TAG = "AppConfigBean";
// 字段校验常量(统一阈值,避免硬编码) // 字段校验常量(统一阈值,避免硬编码)
private static final int MIN_INTERVAL = 500; // 最小检测间隔ms private static final int MIN_INTERVAL = 500; // 最小检测间隔ms
@@ -31,7 +31,7 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
private static final int DEFAULT_FRAME_WIDTH = 500; // 默认相框宽度px private static final int DEFAULT_FRAME_WIDTH = 500; // 默认相框宽度px
private static final int DEFAULT_FRAME_HEIGHT = 500;// 默认相框高度px private static final int DEFAULT_FRAME_HEIGHT = 500;// 默认相框高度px
// ====================== 成员变量(按功能分类:提醒配置→电量状态→检测配置→相框配置) ====================== // ====================== 成员变量(按功能分类:提醒配置→电量状态→检测配置→相框配置) ======================
// 耗电提醒配置 // 耗电提醒配置
boolean isEnableUsageReminder = false; // 耗电提醒开关 boolean isEnableUsageReminder = false; // 耗电提醒开关
int usageReminderValue = 45; // 耗电提醒阈值0-100 int usageReminderValue = 45; // 耗电提醒阈值0-100
@@ -42,7 +42,6 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
int reminderIntervalTime = 5000; // 铃声提醒间隔ms int reminderIntervalTime = 5000; // 铃声提醒间隔ms
// 电量状态 // 电量状态
boolean isCharging = false; // 是否充电 boolean isCharging = false; // 是否充电
//int currentBatteryValue = INVALID_BATTERY; // 当前电池电量(统一命名,替代原 currentValue
// 电量检测配置 // 电量检测配置
int batteryDetectInterval = 2000; // 电量检测间隔ms适配 RemindThread int batteryDetectInterval = 2000; // 电量检测间隔ms适配 RemindThread
// 相框配置 // 相框配置
@@ -56,54 +55,14 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
setUsageReminderValue(10); setUsageReminderValue(10);
setEnableUsageReminder(false); setEnableUsageReminder(false);
setReminderIntervalTime(5000); setReminderIntervalTime(5000);
setBatteryDetectInterval(1000); // 默认检测间隔1秒 setBatteryDetectInterval(1000);
//setCurrentBatteryValue(INVALID_BATTERY); // 初始化无效电量标识 setDefaultFrameWidth(DEFAULT_FRAME_WIDTH);
setDefaultFrameWidth(DEFAULT_FRAME_WIDTH); // 初始化默认相框宽度 setDefaultFrameHeight(DEFAULT_FRAME_HEIGHT);
setDefaultFrameHeight(DEFAULT_FRAME_HEIGHT); // 初始化默认相框高度 LogUtils.d(TAG, "AppConfigBean() 构造器执行 | 默认配置初始化完成");
LogUtils.d(TAG, "AppConfigBean() 初始化默认配置完成");
} }
// ====================== 核心业务方法Setter/Getter按字段功能分类补充调试日志 ====================== // ====================== 核心业务方法Setter/Getter按字段功能分类补充调试日志 ======================
// --------------- 电量状态相关 ---------------
/**
* 设置当前电池电量Receiver 监听电池变化时调用)
* @param currentBatteryValue 当前电量0-100
*/
// public void setCurrentBatteryValue(int currentBatteryValue) {
// this.currentBatteryValue = (currentBatteryValue >= BATTERY_MIN && currentBatteryValue <= BATTERY_MAX)
// ? currentBatteryValue : INVALID_BATTERY;
// LogUtils.d(TAG, String.format("setCurrentBatteryValue() 执行 | 最终电量=%d | 输入值=%d",
// this.currentBatteryValue, currentBatteryValue));
// }
//
// /**
// * 获取当前电池电量RemindThread 同步配置时调用)
// * @return 当前电量0-100 或 INVALID_BATTERY
// */
// public int getCurrentBatteryValue() {
// return currentBatteryValue;
// }
// --------------- 铃声提醒配置相关 ---------------
/**
* 设置铃声提醒间隔
* @param reminderIntervalTime 提醒间隔ms不小于 MIN_REMIND_INTERVAL
*/
public void setReminderIntervalTime(int reminderIntervalTime) {
this.reminderIntervalTime = Math.max(reminderIntervalTime, MIN_REMIND_INTERVAL);
LogUtils.d(TAG, String.format("setReminderIntervalTime() 执行 | 最终间隔=%dms | 输入值=%dms",
this.reminderIntervalTime, reminderIntervalTime));
}
public int getReminderIntervalTime() {
return reminderIntervalTime;
}
// --------------- 充电状态相关 --------------- // --------------- 充电状态相关 ---------------
/**
* 设置是否充电
* @param isCharging 充电状态
*/
public void setIsCharging(boolean isCharging) { public void setIsCharging(boolean isCharging) {
this.isCharging = isCharging; this.isCharging = isCharging;
LogUtils.d(TAG, String.format("setIsCharging() 执行 | 充电状态=%b", isCharging)); LogUtils.d(TAG, String.format("setIsCharging() 执行 | 充电状态=%b", isCharging));
@@ -123,14 +82,9 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
return isEnableUsageReminder; return isEnableUsageReminder;
} }
/**
* 设置耗电提醒阈值
* @param usageReminderValue 阈值0-100
*/
public void setUsageReminderValue(int usageReminderValue) { public void setUsageReminderValue(int usageReminderValue) {
this.usageReminderValue = Math.min(Math.max(usageReminderValue, BATTERY_MIN), BATTERY_MAX); this.usageReminderValue = Math.min(Math.max(usageReminderValue, BATTERY_MIN), BATTERY_MAX);
LogUtils.d(TAG, String.format("setUsageReminderValue() 执行 | 最终阈值=%d | 输入值=%d", LogUtils.d(TAG, String.format("setUsageReminderValue() 执行 | 最终阈值=%d | 输入值=%d", this.usageReminderValue, usageReminderValue));
this.usageReminderValue, usageReminderValue));
} }
public int getUsageReminderValue() { public int getUsageReminderValue() {
@@ -147,29 +101,29 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
return isEnableChargeReminder; return isEnableChargeReminder;
} }
/**
* 设置充电提醒阈值
* @param chargeReminderValue 阈值0-100
*/
public void setChargeReminderValue(int chargeReminderValue) { public void setChargeReminderValue(int chargeReminderValue) {
this.chargeReminderValue = Math.min(Math.max(chargeReminderValue, BATTERY_MIN), BATTERY_MAX); this.chargeReminderValue = Math.min(Math.max(chargeReminderValue, BATTERY_MIN), BATTERY_MAX);
LogUtils.d(TAG, String.format("setChargeReminderValue() 执行 | 最终阈值=%d | 输入值=%d", LogUtils.d(TAG, String.format("setChargeReminderValue() 执行 | 最终阈值=%d | 输入值=%d", this.chargeReminderValue, chargeReminderValue));
this.chargeReminderValue, chargeReminderValue));
} }
public int getChargeReminderValue() { public int getChargeReminderValue() {
return chargeReminderValue; return chargeReminderValue;
} }
// --------------- 铃声提醒配置相关 ---------------
public void setReminderIntervalTime(int reminderIntervalTime) {
this.reminderIntervalTime = Math.max(reminderIntervalTime, MIN_REMIND_INTERVAL);
LogUtils.d(TAG, String.format("setReminderIntervalTime() 执行 | 最终间隔=%dms | 输入值=%dms", this.reminderIntervalTime, reminderIntervalTime));
}
public int getReminderIntervalTime() {
return reminderIntervalTime;
}
// --------------- 电量检测配置相关 --------------- // --------------- 电量检测配置相关 ---------------
/**
* 设置电量检测间隔
* @param batteryDetectInterval 检测间隔ms不小于 MIN_INTERVAL
*/
public void setBatteryDetectInterval(int batteryDetectInterval) { public void setBatteryDetectInterval(int batteryDetectInterval) {
this.batteryDetectInterval = Math.max(batteryDetectInterval, MIN_INTERVAL); this.batteryDetectInterval = Math.max(batteryDetectInterval, MIN_INTERVAL);
LogUtils.d(TAG, String.format("setBatteryDetectInterval() 执行 | 最终间隔=%dms | 输入值=%dms", LogUtils.d(TAG, String.format("setBatteryDetectInterval() 执行 | 最终间隔=%dms | 输入值=%dms", this.batteryDetectInterval, batteryDetectInterval));
this.batteryDetectInterval, batteryDetectInterval));
} }
public int getBatteryDetectInterval() { public int getBatteryDetectInterval() {
@@ -177,28 +131,18 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
} }
// --------------- 相框配置相关 --------------- // --------------- 相框配置相关 ---------------
/**
* 设置默认相框宽度
* @param defaultFrameWidth 相框宽度px
*/
public void setDefaultFrameWidth(int defaultFrameWidth) { public void setDefaultFrameWidth(int defaultFrameWidth) {
this.defaultFrameWidth = defaultFrameWidth; this.defaultFrameWidth = defaultFrameWidth;
LogUtils.d(TAG, String.format("setDefaultFrameWidth() 执行 | 最终宽度=%dpx | 输入值=%dpx", LogUtils.d(TAG, String.format("setDefaultFrameWidth() 执行 | 最终宽度=%dpx | 输入值=%dpx", this.defaultFrameWidth, defaultFrameWidth));
this.defaultFrameWidth, defaultFrameWidth));
} }
public int getDefaultFrameWidth() { public int getDefaultFrameWidth() {
return defaultFrameWidth; return defaultFrameWidth;
} }
/**
* 设置默认相框高度
* @param defaultFrameHeight 相框高度px
*/
public void setDefaultFrameHeight(int defaultFrameHeight) { public void setDefaultFrameHeight(int defaultFrameHeight) {
this.defaultFrameHeight = defaultFrameHeight; this.defaultFrameHeight = defaultFrameHeight;
LogUtils.d(TAG, String.format("setDefaultFrameHeight() 执行 | 最终高度=%dpx | 输入值=%dpx", LogUtils.d(TAG, String.format("setDefaultFrameHeight() 执行 | 最终高度=%dpx | 输入值=%dpx", this.defaultFrameHeight, defaultFrameHeight));
this.defaultFrameHeight, defaultFrameHeight));
} }
public int getDefaultFrameHeight() { public int getDefaultFrameHeight() {
@@ -214,6 +158,8 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
@Override @Override
public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException { public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException {
super.writeThisToJsonWriter(jsonWriter); super.writeThisToJsonWriter(jsonWriter);
LogUtils.d(TAG, "writeThisToJsonWriter() 执行 | 开始JSON序列化");
// 原有字段序列化 // 原有字段序列化
jsonWriter.name("isEnableUsageReminder").value(isEnableUsageReminder()); jsonWriter.name("isEnableUsageReminder").value(isEnableUsageReminder());
jsonWriter.name("usageReminderValue").value(getUsageReminderValue()); jsonWriter.name("usageReminderValue").value(getUsageReminderValue());
@@ -221,21 +167,21 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
jsonWriter.name("chargeReminderValue").value(getChargeReminderValue()); jsonWriter.name("chargeReminderValue").value(getChargeReminderValue());
jsonWriter.name("reminderIntervalTime").value(getReminderIntervalTime()); jsonWriter.name("reminderIntervalTime").value(getReminderIntervalTime());
jsonWriter.name("isCharging").value(isCharging()); jsonWriter.name("isCharging").value(isCharging());
// 兼容旧字段 currentValue同步新字段 currentBatteryValue
// jsonWriter.name("currentBatteryValue").value(getCurrentBatteryValue());
// jsonWriter.name("currentValue").value(getCurrentBatteryValue());
// 新增字段序列化(检测配置) // 新增字段序列化(检测配置)
jsonWriter.name("batteryDetectInterval").value(getBatteryDetectInterval()); jsonWriter.name("batteryDetectInterval").value(getBatteryDetectInterval());
// 新增字段序列化(相框配置) // 新增字段序列化(相框配置)
jsonWriter.name("defaultFrameWidth").value(getDefaultFrameWidth()); jsonWriter.name("defaultFrameWidth").value(getDefaultFrameWidth());
jsonWriter.name("defaultFrameHeight").value(getDefaultFrameHeight()); jsonWriter.name("defaultFrameHeight").value(getDefaultFrameHeight());
LogUtils.d(TAG, "writeThisToJsonWriter() JSON序列化完成");
LogUtils.d(TAG, "writeThisToJsonWriter() 完成 | JSON序列化成功");
} }
@Override @Override
public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException { public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException {
LogUtils.d(TAG, "readBeanFromJsonReader() 执行 | 开始JSON反序列化");
AppConfigBean bean = new AppConfigBean(); AppConfigBean bean = new AppConfigBean();
jsonReader.beginObject(); jsonReader.beginObject();
while (jsonReader.hasNext()) { while (jsonReader.hasNext()) {
String name = jsonReader.nextName(); String name = jsonReader.nextName();
// 兼容拼写错误字段isEnableUsegeReminder → isEnableUsageReminder // 兼容拼写错误字段isEnableUsegeReminder → isEnableUsageReminder
@@ -257,32 +203,23 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
} else if (name.equals("isCharging")) { } else if (name.equals("isCharging")) {
bean.setIsCharging(jsonReader.nextBoolean()); bean.setIsCharging(jsonReader.nextBoolean());
LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%b", name, bean.isCharging())); LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%b", name, bean.isCharging()));
} } else if (name.equals("batteryDetectInterval")) {
// else if (name.equals("currentValue")) {
// // 优先读取旧字段,兼容历史配置
// bean.setCurrentBatteryValue(jsonReader.nextInt());
// LogUtils.d(TAG, "readBeanFromJsonReader() 读取旧字段 | currentValue=" + bean.getCurrentBatteryValue());
// } else if (name.equals("currentBatteryValue")) {
// // 新字段覆盖旧字段,保证数据最新
// bean.setCurrentBatteryValue(jsonReader.nextInt());
// LogUtils.d(TAG, "readBeanFromJsonReader() 读取新字段 | currentBatteryValue=" + bean.getCurrentBatteryValue());
// }
else if (name.equals("batteryDetectInterval")) {
bean.setBatteryDetectInterval(jsonReader.nextInt()); bean.setBatteryDetectInterval(jsonReader.nextInt());
LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%d", name, bean.getBatteryDetectInterval())); LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%d", name, bean.getBatteryDetectInterval()));
} else if (name.equals("defaultFrameWidth")) { } else if (name.equals("defaultFrameWidth")) {
bean.setDefaultFrameWidth(jsonReader.nextInt()); bean.setDefaultFrameWidth(jsonReader.nextInt());
LogUtils.d(TAG, "readBeanFromJsonReader() 读取字段 | defaultFrameWidth=" + bean.getDefaultFrameWidth()); LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%d", name, bean.getDefaultFrameWidth()));
} else if (name.equals("defaultFrameHeight")) { } else if (name.equals("defaultFrameHeight")) {
bean.setDefaultFrameHeight(jsonReader.nextInt()); bean.setDefaultFrameHeight(jsonReader.nextInt());
LogUtils.d(TAG, "readBeanFromJsonReader() 读取字段 | defaultFrameHeight=" + bean.getDefaultFrameHeight()); LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%d", name, bean.getDefaultFrameHeight()));
} else { } else {
jsonReader.skipValue(); jsonReader.skipValue();
LogUtils.w(TAG, "readBeanFromJsonReader() 跳过未知字段 | " + name); LogUtils.w(TAG, String.format("readBeanFromJsonReader() 跳过未知字段 | %s", name));
} }
} }
jsonReader.endObject(); jsonReader.endObject();
LogUtils.d(TAG, "readBeanFromJsonReader() JSON反序列化"); LogUtils.d(TAG, "readBeanFromJsonReader() 完成 | JSON反序列化成");
return bean; return bean;
} }
@@ -294,6 +231,7 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
@Override @Override
public void writeToParcel(Parcel dest, int flags) { public void writeToParcel(Parcel dest, int flags) {
LogUtils.d(TAG, "writeToParcel() 执行 | 开始Parcel序列化");
// 按成员变量顺序写入boolean 转 byte 存储 // 按成员变量顺序写入boolean 转 byte 存储
dest.writeByte((byte) (isEnableUsageReminder ? 1 : 0)); dest.writeByte((byte) (isEnableUsageReminder ? 1 : 0));
dest.writeInt(usageReminderValue); dest.writeInt(usageReminderValue);
@@ -301,17 +239,17 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
dest.writeInt(chargeReminderValue); dest.writeInt(chargeReminderValue);
dest.writeInt(reminderIntervalTime); dest.writeInt(reminderIntervalTime);
dest.writeByte((byte) (isCharging ? 1 : 0)); dest.writeByte((byte) (isCharging ? 1 : 0));
//dest.writeInt(currentBatteryValue);
dest.writeInt(batteryDetectInterval); dest.writeInt(batteryDetectInterval);
dest.writeInt(defaultFrameWidth); dest.writeInt(defaultFrameWidth);
dest.writeInt(defaultFrameHeight); dest.writeInt(defaultFrameHeight);
LogUtils.d(TAG, "writeToParcel() Parcel序列化"); LogUtils.d(TAG, "writeToParcel() 完成 | Parcel序列化成");
} }
// 反序列化 Creator必须 public static final 修饰Java7 适配) // 反序列化 Creator必须 public static final 修饰Java7 适配)
public static final Parcelable.Creator<AppConfigBean> CREATOR = new Parcelable.Creator<AppConfigBean>() { public static final Parcelable.Creator<AppConfigBean> CREATOR = new Parcelable.Creator<AppConfigBean>() {
@Override @Override
public AppConfigBean createFromParcel(Parcel source) { public AppConfigBean createFromParcel(Parcel source) {
LogUtils.d(TAG, "createFromParcel() 执行 | 开始Parcel反序列化");
AppConfigBean bean = new AppConfigBean(); AppConfigBean bean = new AppConfigBean();
// 按 writeToParcel 顺序读取 // 按 writeToParcel 顺序读取
bean.isEnableUsageReminder = source.readByte() != 0; bean.isEnableUsageReminder = source.readByte() != 0;
@@ -320,11 +258,10 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
bean.chargeReminderValue = source.readInt(); bean.chargeReminderValue = source.readInt();
bean.reminderIntervalTime = source.readInt(); bean.reminderIntervalTime = source.readInt();
bean.isCharging = source.readByte() != 0; bean.isCharging = source.readByte() != 0;
//bean.currentBatteryValue = source.readInt();
bean.batteryDetectInterval = source.readInt(); bean.batteryDetectInterval = source.readInt();
bean.defaultFrameWidth = source.readInt(); bean.defaultFrameWidth = source.readInt();
bean.defaultFrameHeight = source.readInt(); bean.defaultFrameHeight = source.readInt();
LogUtils.d(TAG, "createFromParcel() Parcel反序列化"); LogUtils.d(TAG, "createFromParcel() 完成 | Parcel反序列化成");
return bean; return bean;
} }

View File

@@ -15,11 +15,12 @@ import cc.winboll.studio.powerbell.utils.NotificationManagerUtils;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
/** /**
* @Author ZhanGSKen&豆包大模型<zhangsken@qq.com> * 控制中心广播接收器
* @Date 2025/12/19 20:23
* @Describe 控制中心广播接收器
* 功能:监听电池状态变化、前台通知更新、配置变更指令 * 功能:监听电池状态变化、前台通知更新、配置变更指令
* 适配Java7 | API30 | 内存泄漏防护 | 多线程状态同步 * 适配Java7 | API30 | 内存泄漏防护 | 多线程状态同步
* @Author 豆包&ZhanGSKen<zhangsken@qq.com>
* @Date 2025/12/19 20:23
* @Describe 统一处理系统与应用内广播,同步电池状态与配置,保障多线程数据一致性
*/ */
public class ControlCenterServiceReceiver extends BroadcastReceiver { public class ControlCenterServiceReceiver extends BroadcastReceiver {
// ====================== 静态常量区(置顶归类,消除魔法值) ====================== // ====================== 静态常量区(置顶归类,消除魔法值) ======================
@@ -45,7 +46,8 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
// ====================== 构造方法(初始化弱引用,避免服务强引用泄漏) ====================== // ====================== 构造方法(初始化弱引用,避免服务强引用泄漏) ======================
public ControlCenterServiceReceiver(ControlCenterService service) { public ControlCenterServiceReceiver(ControlCenterService service) {
LogUtils.d(TAG, String.format("构造接收器 | 服务实例:%s", service != null ? service.getClass().getSimpleName() : "null")); LogUtils.d(TAG, String.format("ControlCenterServiceReceiver() 构造 | 服务实例:%s",
service != null ? service.getClass().getSimpleName() : "null"));
this.mwrControlCenterService = new WeakReference<>(service); this.mwrControlCenterService = new WeakReference<>(service);
} }
@@ -53,18 +55,18 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
String action = intent != null ? intent.getAction() : "null"; String action = intent != null ? intent.getAction() : "null";
LogUtils.d(TAG, String.format("onReceive: 接收广播 | Action%s", action)); LogUtils.d(TAG, String.format("onReceive() 执行 | 接收广播 Action%s", action));
// 基础参数校验 // 基础参数校验
if (context == null || intent == null || action == null) { if (context == null || intent == null || action == null) {
LogUtils.e(TAG, "onReceive: 参数无效context=" + context + " | intent=" + intent + ",终止处理"); LogUtils.e(TAG, "onReceive() 终止 | 参数无效context=" + context + " | intent=" + intent + "");
return; return;
} }
// 弱引用获取服务,双重校验服务有效性 // 弱引用获取服务,双重校验服务有效性
ControlCenterService service = mwrControlCenterService != null ? mwrControlCenterService.get() : null; ControlCenterService service = mwrControlCenterService != null ? mwrControlCenterService.get() : null;
if (service == null || service.isDestroyed()) { if (service == null || service.isDestroyed()) {
LogUtils.e(TAG, "onReceive: 服务已销毁或为空,注销广播"); LogUtils.e(TAG, "onReceive() 终止 | 服务已销毁或为空,执行注销");
unregisterAction(context); unregisterAction(context);
return; return;
} }
@@ -78,14 +80,14 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
handleUpdateForegroundNotification(service); handleUpdateForegroundNotification(service);
break; break;
case ACTION_APPCONFIG_CHANGED: case ACTION_APPCONFIG_CHANGED:
LogUtils.d(TAG, "onReceive: 开始处理配置更新广播"); LogUtils.d(TAG, "onReceive() 分发 | 处理配置更新广播");
handleNotifyAppConfigUpdate(service); handleNotifyAppConfigUpdate(service);
break; break;
default: default:
LogUtils.w(TAG, String.format("onReceive: 未知Action=%s", action)); LogUtils.w(TAG, String.format("onReceive() 警告 | 未知Action=%s", action));
} }
LogUtils.d(TAG, "onReceive: 广播处理完成"); LogUtils.d(TAG, "onReceive() 完成 | 广播处理结束");
} }
// ====================== 业务处理方法(按功能拆分,强化容错与日志) ====================== // ====================== 业务处理方法(按功能拆分,强化容错与日志) ======================
@@ -95,17 +97,17 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
* @param intent 电池状态广播意图 * @param intent 电池状态广播意图
*/ */
private void handleBatteryStateChanged(ControlCenterService service, Intent intent) { private void handleBatteryStateChanged(ControlCenterService service, Intent intent) {
LogUtils.d(TAG, "handleBatteryStateChanged: 解析电池状态"); LogUtils.d(TAG, "handleBatteryStateChanged() 执行 | 解析电池状态");
try { try {
// 1. 解析并校验当前电池状态 // 1. 解析并校验当前电池状态
boolean currentCharging = BatteryUtils.isCharging(intent); boolean currentCharging = BatteryUtils.isCharging(intent);
int currentBatteryLevel = BatteryUtils.getCurrentBatteryLevel(intent); int currentBatteryLevel = BatteryUtils.getCurrentBatteryLevel(intent);
currentBatteryLevel = Math.min(Math.max(currentBatteryLevel, BATTERY_LEVEL_MIN), BATTERY_LEVEL_MAX); currentBatteryLevel = Math.min(Math.max(currentBatteryLevel, BATTERY_LEVEL_MIN), BATTERY_LEVEL_MAX);
LogUtils.d(TAG, String.format("handleBatteryStateChanged: 当前状态 | 充电=%b | 电量=%d%%", currentCharging, currentBatteryLevel)); LogUtils.d(TAG, String.format("handleBatteryStateChanged() 解析 | 充电=%b | 电量=%d%%", currentCharging, currentBatteryLevel));
// 2. 状态无变化则跳过,减少无效运算 // 2. 状态无变化则跳过,减少无效运算
if (currentCharging == sIsCharging && currentBatteryLevel == sLastBatteryLevel) { if (currentCharging == sIsCharging && currentBatteryLevel == sLastBatteryLevel) {
LogUtils.d(TAG, "handleBatteryStateChanged: 电池状态无变化,跳过处理"); LogUtils.d(TAG, "handleBatteryStateChanged() 跳过 | 电池状态无变化");
return; return;
} }
@@ -116,9 +118,10 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
// 4. 同步缓存状态到配置 // 4. 同步缓存状态到配置
handleNotifyAppConfigUpdate(service); handleNotifyAppConfigUpdate(service);
LogUtils.d(TAG, String.format("handleBatteryStateChanged: 处理成功 | 缓存电量=%d%% | 缓存充电状态=%b", sLastBatteryLevel, sIsCharging)); LogUtils.d(TAG, String.format("handleBatteryStateChanged() 完成 | 缓存电量=%d%% | 缓存充电状态=%b",
sLastBatteryLevel, sIsCharging));
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "handleBatteryStateChanged: 处理失败", e); LogUtils.e(TAG, "handleBatteryStateChanged() 失败", e);
} }
} }
@@ -127,15 +130,15 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
* @param service 控制中心服务实例 * @param service 控制中心服务实例
*/ */
private void handleNotifyAppConfigUpdate(ControlCenterService service) { private void handleNotifyAppConfigUpdate(ControlCenterService service) {
LogUtils.d(TAG, "handleNotifyAppConfigUpdate: 同步缓存状态到配置"); LogUtils.d(TAG, "handleNotifyAppConfigUpdate() 执行 | 同步缓存状态到配置");
try { try {
// 加载最新配置 // 加载最新配置
AppConfigBean latestConfig = AppConfigUtils.getInstance(service).loadAppConfig(); AppConfigBean latestConfig = AppConfigUtils.getInstance(service).loadAppConfig();
if (latestConfig == null) { if (latestConfig == null) {
LogUtils.e(TAG, "handleNotifyAppConfigUpdate: 最新配置为空,终止处理"); LogUtils.e(TAG, "handleNotifyAppConfigUpdate() 终止 | 最新配置为空");
return; return;
} }
LogUtils.d(TAG, String.format("handleNotifyAppConfigUpdate: 加载最新配置 | 充电阈值=%d | 耗电阈值=%d", LogUtils.d(TAG, String.format("handleNotifyAppConfigUpdate() 加载 | 充电阈值=%d | 耗电阈值=%d",
latestConfig.getChargeReminderValue(), latestConfig.getUsageReminderValue())); latestConfig.getChargeReminderValue(), latestConfig.getUsageReminderValue()));
// 同步缓存的电池状态到配置 // 同步缓存的电池状态到配置
@@ -143,10 +146,10 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
latestConfig.setIsCharging(sIsCharging); latestConfig.setIsCharging(sIsCharging);
service.notifyAppConfigUpdate(latestConfig); service.notifyAppConfigUpdate(latestConfig);
LogUtils.d(TAG, String.format("handleNotifyAppConfigUpdate: 配置同步成功 | 缓存电量=%d%% | 充电状态=%b", sLastBatteryLevel, sIsCharging)); LogUtils.d(TAG, String.format("handleNotifyAppConfigUpdate() 完成 | 缓存电量=%d%% | 充电状态=%b",
LogUtils.d(TAG, "handleNotifyAppConfigUpdate: 配置更新广播处理完成"); sLastBatteryLevel, sIsCharging));
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "handleNotifyAppConfigUpdate: 处理失败", e); LogUtils.e(TAG, "handleNotifyAppConfigUpdate() 失败", e);
} }
} }
@@ -155,21 +158,22 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
* @param service 控制中心服务实例 * @param service 控制中心服务实例
*/ */
private void handleUpdateForegroundNotification(ControlCenterService service) { private void handleUpdateForegroundNotification(ControlCenterService service) {
LogUtils.d(TAG, "handleUpdateForegroundNotification: 更新前台通知"); LogUtils.d(TAG, "handleUpdateForegroundNotification() 执行 | 更新前台通知");
try { try {
NotificationManagerUtils notifyUtils = service.getNotificationManager(); NotificationManagerUtils notifyUtils = service.getNotificationManager();
NotificationMessage notifyMsg = service.getForegroundNotifyMsg(); NotificationMessage notifyMsg = service.getForegroundNotifyMsg();
// 非空校验,避免空指针 // 非空校验,避免空指针
if (notifyUtils == null || notifyMsg == null) { if (notifyUtils == null || notifyMsg == null) {
LogUtils.e(TAG, String.format("handleUpdateForegroundNotification: 通知工具类或消息为空notifyUtils=%s | notifyMsg=%s", notifyUtils, notifyMsg)); LogUtils.e(TAG, String.format("handleUpdateForegroundNotification() 终止 | 通知工具类或消息为空notifyUtils=%s | notifyMsg=%s",
notifyUtils, notifyMsg));
return; return;
} }
notifyUtils.updateForegroundServiceNotify(notifyMsg); notifyUtils.updateForegroundServiceNotify(notifyMsg);
LogUtils.d(TAG, String.format("handleUpdateForegroundNotification: 前台通知更新成功 | 标题=%s", notifyMsg.getTitle())); LogUtils.d(TAG, String.format("handleUpdateForegroundNotification() 完成 | 标题=%s", notifyMsg.getTitle()));
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "handleUpdateForegroundNotification: 处理失败", e); LogUtils.e(TAG, "handleUpdateForegroundNotification() 失败", e);
} }
} }
@@ -179,9 +183,9 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
* @param context 上下文 * @param context 上下文
*/ */
public void registerAction(Context context) { public void registerAction(Context context) {
LogUtils.d(TAG, "registerAction: 注册广播接收器"); LogUtils.d(TAG, "registerAction() 执行 | 注册广播接收器");
if (context == null || isRegistered) { if (context == null || isRegistered) {
LogUtils.e(TAG, "registerAction: 上下文为空或已注册,注册失败"); LogUtils.e(TAG, "registerAction() 失败 | 上下文为空或已注册");
return; return;
} }
@@ -194,9 +198,9 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
context.registerReceiver(this, filter); context.registerReceiver(this, filter);
isRegistered = true; isRegistered = true;
LogUtils.d(TAG, String.format("registerAction: 广播注册成功 | 优先级=%d", BROADCAST_PRIORITY)); LogUtils.d(TAG, String.format("registerAction() 完成 | 优先级=%d", BROADCAST_PRIORITY));
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "registerAction: 注册失败", e); LogUtils.e(TAG, "registerAction() 失败", e);
} }
} }
@@ -205,20 +209,20 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
* @param context 上下文 * @param context 上下文
*/ */
public void unregisterAction(Context context) { public void unregisterAction(Context context) {
LogUtils.d(TAG, "unregisterAction: 注销广播接收器"); LogUtils.d(TAG, "unregisterAction() 执行 | 注销广播接收器");
if (context == null || !isRegistered) { if (context == null || !isRegistered) {
LogUtils.e(TAG, "unregisterAction: 上下文为空或未注册,注销失败"); LogUtils.e(TAG, "unregisterAction() 失败 | 上下文为空或未注册");
return; return;
} }
try { try {
context.unregisterReceiver(this); context.unregisterReceiver(this);
isRegistered = false; isRegistered = false;
LogUtils.d(TAG, "unregisterAction: 广播注销成功"); LogUtils.d(TAG, "unregisterAction() 完成 | 广播注销成功");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
LogUtils.w(TAG, "unregisterAction: 广播未注册,跳过注销"); LogUtils.w(TAG, "unregisterAction() 警告 | 广播未注册,跳过注销");
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "unregisterAction: 注销失败", e); LogUtils.e(TAG, "unregisterAction() 失败", e);
} }
} }
@@ -227,17 +231,17 @@ public class ControlCenterServiceReceiver extends BroadcastReceiver {
* 主动释放资源,避免内存泄漏 * 主动释放资源,避免内存泄漏
*/ */
public void release() { public void release() {
LogUtils.d(TAG, "release: 释放广播接收器资源"); LogUtils.d(TAG, "release() 执行 | 释放广播接收器资源");
// 清空弱引用帮助GC回收 // 清空弱引用帮助GC回收
if (mwrControlCenterService != null) { if (mwrControlCenterService != null) {
mwrControlCenterService.clear(); mwrControlCenterService.clear();
mwrControlCenterService = null; mwrControlCenterService = null;
LogUtils.d(TAG, "release: 弱引用已清空"); LogUtils.d(TAG, "release() 步骤 | 弱引用已清空");
} }
// 重置静态状态缓存 // 重置静态状态缓存
sLastBatteryLevel = -1; sLastBatteryLevel = -1;
sIsCharging = false; sIsCharging = false;
LogUtils.d(TAG, "release: 静态状态缓存已重置"); LogUtils.d(TAG, "release() 完成 | 静态状态缓存已重置");
} }
/** /**

View File

@@ -24,7 +24,7 @@ import java.util.List;
* 电池提醒核心服务 * 电池提醒核心服务
* 功能:管理前台服务生命周期、控制提醒线程启停、处理配置更新 * 功能:管理前台服务生命周期、控制提醒线程启停、处理配置更新
* 适配Java7 | API30 | 前台服务超时防护 | 电池优化忽略引导 * 适配Java7 | API30 | 前台服务超时防护 | 电池优化忽略引导
* @Author ZhanGSKen<zhangsken@qq.com> * @Author 豆包&ZhanGSKen<zhangsken@qq.com>
* @Describe 核心服务:实现电池监测、提醒控制与前台服务保活 * @Describe 核心服务:实现电池监测、提醒控制与前台服务保活
*/ */
public class ControlCenterService extends Service { public class ControlCenterService extends Service {
@@ -62,35 +62,35 @@ public class ControlCenterService extends Service {
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
LogUtils.d(TAG, String.format("onCreate执行 | 线程=%s | 进程ID=%d", Thread.currentThread().getName(), android.os.Process.myPid())); LogUtils.d(TAG, String.format("onCreate() 执行 | 线程=%s | 进程ID=%d", Thread.currentThread().getName(), android.os.Process.myPid()));
runCoreServiceLogic(); runCoreServiceLogic();
boolean serviceEnabled = mServiceControlBean != null && mServiceControlBean.isEnableService(); boolean serviceEnabled = mServiceControlBean != null && mServiceControlBean.isEnableService();
LogUtils.d(TAG, String.format("onCreate完成 | 前台状态=%b | 服务启用=%b", isServiceRunning, serviceEnabled)); LogUtils.d(TAG, String.format("onCreate() 完成 | 前台状态=%b | 服务启用=%b", isServiceRunning, serviceEnabled));
} }
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent != null ? intent.getAction() : "null"; String action = intent != null ? intent.getAction() : "null";
LogUtils.d(TAG, String.format("onStartCommand执行 | startId=%d | action=%s", startId, action)); LogUtils.d(TAG, String.format("onStartCommand() 执行 | startId=%d | action=%s", startId, action));
loadLatestServiceControlConfig(); loadLatestServiceControlConfig();
runCoreServiceLogic(); runCoreServiceLogic();
int returnFlag = (mServiceControlBean != null && mServiceControlBean.isEnableService()) int returnFlag = (mServiceControlBean != null && mServiceControlBean.isEnableService())
? SERVICE_RETURN_STICKY ? SERVICE_RETURN_STICKY
: super.onStartCommand(intent, flags, startId); : super.onStartCommand(intent, flags, startId);
LogUtils.d(TAG, String.format("onStartCommand完成 | 返回策略=%s", returnFlag == SERVICE_RETURN_STICKY ? "START_STICKY" : "DEFAULT")); LogUtils.d(TAG, String.format("onStartCommand() 完成 | 返回策略=%s", returnFlag == SERVICE_RETURN_STICKY ? "START_STICKY" : "DEFAULT"));
return returnFlag; return returnFlag;
} }
@Override @Override
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
LogUtils.d(TAG, String.format("onBind执行 | intent=%s", intent)); LogUtils.d(TAG, String.format("onBind() 执行 | intent=%s", intent));
return null; return null;
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
LogUtils.d(TAG, "onDestroy执行服务销毁流程启动"); LogUtils.d(TAG, "onDestroy() 执行:服务销毁流程启动");
super.onDestroy(); super.onDestroy();
// 资源释放顺序:前台服务 → 线程 → 广播接收器 → Handler → 通知 → 引用(避免内存泄漏) // 资源释放顺序:前台服务 → 线程 → 广播接收器 → Handler → 通知 → 引用(避免内存泄漏)
@@ -108,7 +108,7 @@ public class ControlCenterService extends Service {
isServiceRunning = false; isServiceRunning = false;
mIsDestroyed = true; mIsDestroyed = true;
LogUtils.d(TAG, "onDestroy完成服务销毁完成"); LogUtils.d(TAG, "onDestroy() 完成:服务销毁完成");
} }
// ====================== 核心业务逻辑(独立抽取,统一调用) ====================== // ====================== 核心业务逻辑(独立抽取,统一调用) ======================
@@ -117,11 +117,11 @@ public class ControlCenterService extends Service {
* 避免重复初始化,保证前台服务优先启动 * 避免重复初始化,保证前台服务优先启动
*/ */
private synchronized void runCoreServiceLogic() { private synchronized void runCoreServiceLogic() {
LogUtils.d(TAG, "runCoreServiceLogic执行"); LogUtils.d(TAG, "runCoreServiceLogic() 执行");
loadLatestServiceControlConfig(); loadLatestServiceControlConfig();
boolean serviceEnabled = mServiceControlBean != null && mServiceControlBean.isEnableService(); boolean serviceEnabled = mServiceControlBean != null && mServiceControlBean.isEnableService();
LogUtils.d(TAG, String.format("runCoreServiceLogic服务启用=%b | 已运行=%b | 已销毁=%b", serviceEnabled, isServiceRunning, mIsDestroyed)); LogUtils.d(TAG, String.format("runCoreServiceLogic() | 服务启用=%b | 已运行=%b | 已销毁=%b", serviceEnabled, isServiceRunning, mIsDestroyed));
if (serviceEnabled && !isServiceRunning) { if (serviceEnabled && !isServiceRunning) {
isServiceRunning = true; isServiceRunning = true;
@@ -130,14 +130,14 @@ public class ControlCenterService extends Service {
if (initForegroundNotificationImmediately()) { if (initForegroundNotificationImmediately()) {
loadDefaultConfig(); loadDefaultConfig();
initServiceBusinessLogic(); initServiceBusinessLogic();
LogUtils.d(TAG, "runCoreServiceLogic核心组件初始化成功"); LogUtils.d(TAG, "runCoreServiceLogic() | 核心组件初始化成功");
} else { } else {
LogUtils.e(TAG, "runCoreServiceLogic前台通知初始化失败,终止业务"); LogUtils.e(TAG, "runCoreServiceLogic() | 前台通知初始化失败,终止业务");
stopForegroundService(); stopForegroundService();
isServiceRunning = false; isServiceRunning = false;
} }
} else { } else {
LogUtils.d(TAG, "runCoreServiceLogic无需执行核心逻辑"); LogUtils.d(TAG, "runCoreServiceLogic() | 无需执行核心逻辑");
} }
} }
@@ -147,11 +147,11 @@ public class ControlCenterService extends Service {
* @return true=成功 false=失败 * @return true=成功 false=失败
*/ */
private boolean initForegroundNotificationImmediately() { private boolean initForegroundNotificationImmediately() {
LogUtils.d(TAG, "initForegroundNotificationImmediately执行"); LogUtils.d(TAG, "initForegroundNotificationImmediately() 执行");
try { try {
if (mNotificationManager == null) { if (mNotificationManager == null) {
mNotificationManager = new NotificationManagerUtils(this); mNotificationManager = new NotificationManagerUtils(this);
LogUtils.d(TAG, "initForegroundNotificationImmediately通知工具类初始化完成"); LogUtils.d(TAG, "initForegroundNotificationImmediately() | 通知工具类初始化完成");
} }
if (mForegroundNotifyMsg == null) { if (mForegroundNotifyMsg == null) {
@@ -159,15 +159,15 @@ public class ControlCenterService extends Service {
mForegroundNotifyMsg.setTitle("电池监测服务"); mForegroundNotifyMsg.setTitle("电池监测服务");
mForegroundNotifyMsg.setContent("后台运行中"); mForegroundNotifyMsg.setContent("后台运行中");
mForegroundNotifyMsg.setRemindMSG("service_running"); mForegroundNotifyMsg.setRemindMSG("service_running");
LogUtils.d(TAG, "initForegroundNotificationImmediately通知消息构建完成"); LogUtils.d(TAG, "initForegroundNotificationImmediately() | 通知消息构建完成");
} }
mNotificationManager.startForegroundServiceNotify(this, mForegroundNotifyMsg); mNotificationManager.startForegroundServiceNotify(this, mForegroundNotifyMsg);
ToastUtils.show("电池监测服务已启动"); ToastUtils.show("电池监测服务已启动");
LogUtils.d(TAG, String.format("initForegroundNotificationImmediately前台通知发送成功 | ID=%d", NotificationManagerUtils.NOTIFY_ID_FOREGROUND_SERVICE)); LogUtils.d(TAG, String.format("initForegroundNotificationImmediately() | 前台通知发送成功 | ID=%d", NotificationManagerUtils.NOTIFY_ID_FOREGROUND_SERVICE));
return true; return true;
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "initForegroundNotificationImmediately通知初始化异常", e); LogUtils.e(TAG, "initForegroundNotificationImmediately() | 通知初始化异常", e);
return false; return false;
} }
} }
@@ -176,12 +176,12 @@ public class ControlCenterService extends Service {
* 停止前台服务并取消通知 * 停止前台服务并取消通知
*/ */
private void stopForegroundService() { private void stopForegroundService() {
LogUtils.d(TAG, "stopForegroundService执行"); LogUtils.d(TAG, "stopForegroundService() 执行");
try { try {
stopForeground(true); stopForeground(true);
LogUtils.d(TAG, "stopForegroundService前台服务已停止,通知已取消"); LogUtils.d(TAG, "stopForegroundService() | 前台服务已停止,通知已取消");
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "stopForegroundService停止异常", e); LogUtils.e(TAG, "stopForegroundService() | 停止异常", e);
} }
} }
@@ -190,13 +190,13 @@ public class ControlCenterService extends Service {
* 加载本地最新服务控制配置 * 加载本地最新服务控制配置
*/ */
private void loadLatestServiceControlConfig() { private void loadLatestServiceControlConfig() {
LogUtils.d(TAG, "loadLatestServiceControlConfig执行"); LogUtils.d(TAG, "loadLatestServiceControlConfig() 执行");
ControlCenterServiceBean latestBean = ControlCenterServiceBean.loadBean(this, ControlCenterServiceBean.class); ControlCenterServiceBean latestBean = ControlCenterServiceBean.loadBean(this, ControlCenterServiceBean.class);
if (latestBean != null) { if (latestBean != null) {
mServiceControlBean = latestBean; mServiceControlBean = latestBean;
LogUtils.d(TAG, String.format("loadLatestServiceControlConfig配置读取成功 | 启用=%b", mServiceControlBean.isEnableService())); LogUtils.d(TAG, String.format("loadLatestServiceControlConfig() | 配置读取成功 | 启用=%b", mServiceControlBean.isEnableService()));
} else { } else {
LogUtils.w(TAG, "loadLatestServiceControlConfig本地无配置,沿用内存配置"); LogUtils.w(TAG, "loadLatestServiceControlConfig() | 本地无配置,沿用内存配置");
} }
} }
@@ -204,7 +204,7 @@ public class ControlCenterService extends Service {
* 加载默认业务配置(首次启动兜底) * 加载默认业务配置(首次启动兜底)
*/ */
private void loadDefaultConfig() { private void loadDefaultConfig() {
LogUtils.d(TAG, "loadDefaultConfig执行"); LogUtils.d(TAG, "loadDefaultConfig() 执行");
if (mCurrentConfigBean == null) { if (mCurrentConfigBean == null) {
mCurrentConfigBean = new AppConfigBean(); mCurrentConfigBean = new AppConfigBean();
mCurrentConfigBean.setEnableChargeReminder(true); mCurrentConfigBean.setEnableChargeReminder(true);
@@ -212,10 +212,10 @@ public class ControlCenterService extends Service {
mCurrentConfigBean.setEnableUsageReminder(true); mCurrentConfigBean.setEnableUsageReminder(true);
mCurrentConfigBean.setUsageReminderValue(DEFAULT_USAGE_REMINDER_VALUE); mCurrentConfigBean.setUsageReminderValue(DEFAULT_USAGE_REMINDER_VALUE);
mCurrentConfigBean.setBatteryDetectInterval(DEFAULT_BATTERY_DETECT_INTERVAL); mCurrentConfigBean.setBatteryDetectInterval(DEFAULT_BATTERY_DETECT_INTERVAL);
LogUtils.d(TAG, String.format("loadDefaultConfig默认配置加载完成 | 充电阈值=%d | 耗电阈值=%d | 检测间隔=%dms", LogUtils.d(TAG, String.format("loadDefaultConfig() | 默认配置加载完成 | 充电阈值=%d | 耗电阈值=%d | 检测间隔=%dms",
DEFAULT_CHARGE_REMINDER_VALUE, DEFAULT_USAGE_REMINDER_VALUE, DEFAULT_BATTERY_DETECT_INTERVAL)); DEFAULT_CHARGE_REMINDER_VALUE, DEFAULT_USAGE_REMINDER_VALUE, DEFAULT_BATTERY_DETECT_INTERVAL));
} else { } else {
LogUtils.d(TAG, "loadDefaultConfig内存已有配置,无需加载"); LogUtils.d(TAG, "loadDefaultConfig() | 内存已有配置,无需加载");
} }
} }
@@ -224,21 +224,21 @@ public class ControlCenterService extends Service {
* 初始化Handler等核心业务组件 * 初始化Handler等核心业务组件
*/ */
private void initServiceBusinessLogic() { private void initServiceBusinessLogic() {
LogUtils.d(TAG, "initServiceBusinessLogic执行"); LogUtils.d(TAG, "initServiceBusinessLogic() 执行");
// 初始化Handler // 初始化Handler
if (mServiceHandler == null) { if (mServiceHandler == null) {
mServiceHandler = new ControlCenterServiceHandler(this); mServiceHandler = new ControlCenterServiceHandler(this);
LogUtils.d(TAG, "initServiceBusinessLogicHandler初始化完成"); LogUtils.d(TAG, "initServiceBusinessLogic() | Handler初始化完成");
} else { } else {
LogUtils.d(TAG, "initServiceBusinessLogicHandler已存在"); LogUtils.d(TAG, "initServiceBusinessLogic() | Handler已存在");
} }
// 初始化广播接收器 // 初始化广播接收器
if (mControlCenterServiceReceiver == null) { if (mControlCenterServiceReceiver == null) {
mControlCenterServiceReceiver = new ControlCenterServiceReceiver(this); mControlCenterServiceReceiver = new ControlCenterServiceReceiver(this);
mControlCenterServiceReceiver.registerAction(this); mControlCenterServiceReceiver.registerAction(this);
LogUtils.d(TAG, "initServiceBusinessLogic广播接收器初始化并注册完成"); LogUtils.d(TAG, "initServiceBusinessLogic() | 广播接收器初始化并注册完成");
} else { } else {
LogUtils.d(TAG, "initServiceBusinessLogic广播接收器已存在"); LogUtils.d(TAG, "initServiceBusinessLogic() | 广播接收器已存在");
} }
} }
@@ -246,13 +246,13 @@ public class ControlCenterService extends Service {
* 释放广播接收器资源 * 释放广播接收器资源
*/ */
private void releaseBroadcastReceiver() { private void releaseBroadcastReceiver() {
LogUtils.d(TAG, "releaseBroadcastReceiver执行"); LogUtils.d(TAG, "releaseBroadcastReceiver() 执行");
if (mControlCenterServiceReceiver != null) { if (mControlCenterServiceReceiver != null) {
mControlCenterServiceReceiver.release(); mControlCenterServiceReceiver.release();
mControlCenterServiceReceiver = null; mControlCenterServiceReceiver = null;
LogUtils.d(TAG, "releaseBroadcastReceiver广播接收器已释放"); LogUtils.d(TAG, "releaseBroadcastReceiver() | 广播接收器已释放");
} else { } else {
LogUtils.w(TAG, "releaseBroadcastReceiver广播接收器实例为空"); LogUtils.w(TAG, "releaseBroadcastReceiver() | 广播接收器实例为空");
} }
} }
@@ -260,13 +260,13 @@ public class ControlCenterService extends Service {
* 销毁Handler移除所有消息和回调防止内存泄漏 * 销毁Handler移除所有消息和回调防止内存泄漏
*/ */
private void destroyHandler() { private void destroyHandler() {
LogUtils.d(TAG, "destroyHandler执行"); LogUtils.d(TAG, "destroyHandler() 执行");
if (mServiceHandler != null) { if (mServiceHandler != null) {
mServiceHandler.removeCallbacksAndMessages(null); mServiceHandler.removeCallbacksAndMessages(null);
mServiceHandler = null; mServiceHandler = null;
LogUtils.d(TAG, "destroyHandlerHandler已销毁"); LogUtils.d(TAG, "destroyHandler() | Handler已销毁");
} else { } else {
LogUtils.w(TAG, "destroyHandlerHandler实例为空"); LogUtils.w(TAG, "destroyHandler() | Handler实例为空");
} }
} }
@@ -274,13 +274,13 @@ public class ControlCenterService extends Service {
* 释放通知工具类资源 * 释放通知工具类资源
*/ */
private void releaseNotificationResource() { private void releaseNotificationResource() {
LogUtils.d(TAG, "releaseNotificationResource执行"); LogUtils.d(TAG, "releaseNotificationResource() 执行");
if (mNotificationManager != null) { if (mNotificationManager != null) {
mNotificationManager.release(); mNotificationManager.release();
mNotificationManager = null; mNotificationManager = null;
LogUtils.d(TAG, "releaseNotificationResource通知资源已释放"); LogUtils.d(TAG, "releaseNotificationResource() | 通知资源已释放");
} else { } else {
LogUtils.w(TAG, "releaseNotificationResource通知工具类实例为空"); LogUtils.w(TAG, "releaseNotificationResource() | 通知工具类实例为空");
} }
} }
@@ -288,10 +288,10 @@ public class ControlCenterService extends Service {
* 置空所有引用,防止内存泄漏 * 置空所有引用,防止内存泄漏
*/ */
private void clearAllReferences() { private void clearAllReferences() {
LogUtils.d(TAG, "clearAllReferences执行"); LogUtils.d(TAG, "clearAllReferences() 执行");
mForegroundNotifyMsg = null; mForegroundNotifyMsg = null;
mServiceControlBean = null; mServiceControlBean = null;
LogUtils.d(TAG, "clearAllReferences引用清理完成"); LogUtils.d(TAG, "clearAllReferences() | 引用清理完成");
} }
// ====================== 外部调用接口(静态方法,提供服务启停/配置更新入口) ====================== // ====================== 外部调用接口(静态方法,提供服务启停/配置更新入口) ======================
@@ -300,25 +300,25 @@ public class ControlCenterService extends Service {
* @param context 上下文 * @param context 上下文
*/ */
public static void startControlCenterService(Context context) { public static void startControlCenterService(Context context) {
LogUtils.d(TAG, String.format("startControlCenterService执行 | context=%s", context)); LogUtils.d(TAG, String.format("startControlCenterService() 执行 | context=%s", context));
if (context == null) { if (context == null) {
LogUtils.e(TAG, "startControlCenterServiceContext为空启动失败"); LogUtils.e(TAG, "startControlCenterService() | Context为空启动失败");
return; return;
} }
// 保存启用配置 // 保存启用配置
ControlCenterServiceBean controlBean = new ControlCenterServiceBean(true); ControlCenterServiceBean controlBean = new ControlCenterServiceBean(true);
ControlCenterServiceBean.saveBean(context, controlBean); ControlCenterServiceBean.saveBean(context, controlBean);
LogUtils.d(TAG, "startControlCenterService服务启用配置已保存"); LogUtils.d(TAG, "startControlCenterService() | 服务启用配置已保存");
// 启动服务区分API版本 // 启动服务区分API版本
Intent intent = new Intent(context, ControlCenterService.class); Intent intent = new Intent(context, ControlCenterService.class);
if (Build.VERSION.SDK_INT >= API_LEVEL_26) { if (Build.VERSION.SDK_INT >= API_LEVEL_26) {
context.startForegroundService(intent); context.startForegroundService(intent);
LogUtils.d(TAG, "startControlCenterService以前台服务方式启动API26+"); LogUtils.d(TAG, "startControlCenterService() | 以前台服务方式启动API26+");
} else { } else {
context.startService(intent); context.startService(intent);
LogUtils.d(TAG, "startControlCenterService以普通服务方式启动API26-"); LogUtils.d(TAG, "startControlCenterService() | 以普通服务方式启动API26-");
} }
} }
@@ -327,21 +327,21 @@ public class ControlCenterService extends Service {
* @param context 上下文 * @param context 上下文
*/ */
public static void stopControlCenterService(Context context) { public static void stopControlCenterService(Context context) {
LogUtils.d(TAG, String.format("stopControlCenterService执行 | context=%s", context)); LogUtils.d(TAG, String.format("stopControlCenterService() 执行 | context=%s", context));
if (context == null) { if (context == null) {
LogUtils.e(TAG, "stopControlCenterServiceContext为空停止失败"); LogUtils.e(TAG, "stopControlCenterService() | Context为空停止失败");
return; return;
} }
// 保存停用配置 // 保存停用配置
ControlCenterServiceBean controlBean = new ControlCenterServiceBean(false); ControlCenterServiceBean controlBean = new ControlCenterServiceBean(false);
ControlCenterServiceBean.saveBean(context, controlBean); ControlCenterServiceBean.saveBean(context, controlBean);
LogUtils.d(TAG, "stopControlCenterService服务停用配置已保存"); LogUtils.d(TAG, "stopControlCenterService() | 服务停用配置已保存");
// 停止服务 // 停止服务
Intent intent = new Intent(context, ControlCenterService.class); Intent intent = new Intent(context, ControlCenterService.class);
context.stopService(intent); context.stopService(intent);
LogUtils.d(TAG, "stopControlCenterService停止指令已发送"); LogUtils.d(TAG, "stopControlCenterService() | 停止指令已发送");
} }
/** /**
@@ -349,16 +349,16 @@ public class ControlCenterService extends Service {
* @param context 上下文 * @param context 上下文
*/ */
public static void sendAppConfigStatusUpdateMessage(Context context) { public static void sendAppConfigStatusUpdateMessage(Context context) {
LogUtils.d(TAG, String.format("sendAppConfigStatusUpdateMessage执行 | context=%s", context)); LogUtils.d(TAG, String.format("sendAppConfigStatusUpdateMessage() 执行 | context=%s", context));
if (context == null) { if (context == null) {
LogUtils.e(TAG, "sendAppConfigStatusUpdateMessage参数为空,更新失败"); LogUtils.e(TAG, "sendAppConfigStatusUpdateMessage() | 参数为空,更新失败");
return; return;
} }
Intent intent = new Intent(ControlCenterServiceReceiver.ACTION_APPCONFIG_CHANGED); Intent intent = new Intent(ControlCenterServiceReceiver.ACTION_APPCONFIG_CHANGED);
intent.setPackage(context.getPackageName()); intent.setPackage(context.getPackageName());
context.sendBroadcast(intent); context.sendBroadcast(intent);
LogUtils.d(TAG, String.format("sendAppConfigStatusUpdateMessage配置更新广播发送 | action=%s", ControlCenterServiceReceiver.ACTION_APPCONFIG_CHANGED)); LogUtils.d(TAG, String.format("sendAppConfigStatusUpdateMessage() | 配置更新广播发送 | action=%s", ControlCenterServiceReceiver.ACTION_APPCONFIG_CHANGED));
} }
/** /**
@@ -366,28 +366,28 @@ public class ControlCenterService extends Service {
* @param context 上下文 * @param context 上下文
*/ */
public static void checkIgnoreBatteryOptimization(Context context) { public static void checkIgnoreBatteryOptimization(Context context) {
LogUtils.d(TAG, String.format("checkIgnoreBatteryOptimization执行 | context=%s", context)); LogUtils.d(TAG, String.format("checkIgnoreBatteryOptimization() 执行 | context=%s", context));
if (context == null || Build.VERSION.SDK_INT < API_LEVEL_23) { if (context == null || Build.VERSION.SDK_INT < API_LEVEL_23) {
LogUtils.w(TAG, "checkIgnoreBatteryOptimization无需检查Context为空或API<23"); LogUtils.w(TAG, "checkIgnoreBatteryOptimization() | 无需检查Context为空或API<23");
return; return;
} }
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (powerManager == null) { if (powerManager == null) {
LogUtils.e(TAG, "checkIgnoreBatteryOptimizationPowerManager获取失败"); LogUtils.e(TAG, "checkIgnoreBatteryOptimization() | PowerManager获取失败");
return; return;
} }
String packageName = context.getPackageName(); String packageName = context.getPackageName();
boolean isIgnored = powerManager.isIgnoringBatteryOptimizations(packageName); boolean isIgnored = powerManager.isIgnoringBatteryOptimizations(packageName);
LogUtils.d(TAG, String.format("checkIgnoreBatteryOptimization已忽略电池优化=%b", isIgnored)); LogUtils.d(TAG, String.format("checkIgnoreBatteryOptimization() | 已忽略电池优化=%b", isIgnored));
if (!isIgnored) { if (!isIgnored) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName)); intent.setData(Uri.parse("package:" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent); context.startActivity(intent);
LogUtils.d(TAG, String.format("checkIgnoreBatteryOptimization已跳转至系统设置页 | package=%s", packageName)); LogUtils.d(TAG, String.format("checkIgnoreBatteryOptimization() | 已跳转至系统设置页 | package=%s", packageName));
} }
} }
@@ -398,15 +398,15 @@ public class ControlCenterService extends Service {
* @return true=运行中 false=未运行 * @return true=运行中 false=未运行
*/ */
private static boolean isServiceRunning(Context context, Class<?> serviceClass) { private static boolean isServiceRunning(Context context, Class<?> serviceClass) {
LogUtils.d(TAG, String.format("isServiceRunning执行 | context=%s | service=%s", context, serviceClass != null ? serviceClass.getName() : "null")); LogUtils.d(TAG, String.format("isServiceRunning() 执行 | context=%s | service=%s", context, serviceClass != null ? serviceClass.getName() : "null"));
if (context == null || serviceClass == null) { if (context == null || serviceClass == null) {
LogUtils.e(TAG, "isServiceRunning参数为空"); LogUtils.e(TAG, "isServiceRunning() | 参数为空");
return false; return false;
} }
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) { if (am == null) {
LogUtils.e(TAG, "isServiceRunningActivityManager获取失败"); LogUtils.e(TAG, "isServiceRunning() | ActivityManager获取失败");
return false; return false;
} }
@@ -427,7 +427,7 @@ public class ControlCenterService extends Service {
} }
} }
} }
LogUtils.d(TAG, String.format("isServiceRunningAPI30+ 判断结果=%b", isRunning)); LogUtils.d(TAG, String.format("isServiceRunning() | API30+ 判断结果=%b", isRunning));
} else { } else {
// API30- 通过服务列表判断 // API30- 通过服务列表判断
List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(RUNNING_SERVICE_LIST_LIMIT); List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(RUNNING_SERVICE_LIST_LIMIT);
@@ -439,13 +439,13 @@ public class ControlCenterService extends Service {
} }
} }
} }
LogUtils.d(TAG, String.format("isServiceRunningAPI30- 判断结果=%b", isRunning)); LogUtils.d(TAG, String.format("isServiceRunning() | API30- 判断结果=%b", isRunning));
} }
// 兜底判断:配置启用状态 // 兜底判断:配置启用状态
if (!isRunning) { if (!isRunning) {
isRunning = isServiceStarted(context, serviceClass); isRunning = isServiceStarted(context, serviceClass);
LogUtils.d(TAG, String.format("isServiceRunning兜底判断结果=%b", isRunning)); LogUtils.d(TAG, String.format("isServiceRunning() | 兜底判断结果=%b", isRunning));
} }
return isRunning; return isRunning;
} }
@@ -454,12 +454,12 @@ public class ControlCenterService extends Service {
* 兜底判断服务是否已启动(通过配置文件) * 兜底判断服务是否已启动(通过配置文件)
*/ */
private static boolean isServiceStarted(Context context, Class<?> serviceClass) { private static boolean isServiceStarted(Context context, Class<?> serviceClass) {
LogUtils.d(TAG, "isServiceStarted执行"); LogUtils.d(TAG, "isServiceStarted() 执行");
try { try {
ControlCenterServiceBean controlBean = ControlCenterServiceBean.loadBean(context, ControlCenterServiceBean.class); ControlCenterServiceBean controlBean = ControlCenterServiceBean.loadBean(context, ControlCenterServiceBean.class);
return controlBean != null && controlBean.isEnableService(); return controlBean != null && controlBean.isEnableService();
} catch (Exception e) { } catch (Exception e) {
LogUtils.e(TAG, "isServiceStarted兜底判断异常", e); LogUtils.e(TAG, "isServiceStarted() | 兜底判断异常", e);
return false; return false;
} }
} }
@@ -472,13 +472,13 @@ public class ControlCenterService extends Service {
public void notifyAppConfigUpdate(AppConfigBean latestConfig) { public void notifyAppConfigUpdate(AppConfigBean latestConfig) {
int chargeThreshold = latestConfig != null ? latestConfig.getChargeReminderValue() : -1; int chargeThreshold = latestConfig != null ? latestConfig.getChargeReminderValue() : -1;
int usageThreshold = latestConfig != null ? latestConfig.getUsageReminderValue() : -1; int usageThreshold = latestConfig != null ? latestConfig.getUsageReminderValue() : -1;
LogUtils.d(TAG, String.format("notifyAppConfigUpdate执行 | 充电阈值=%d | 耗电阈值=%d", chargeThreshold, usageThreshold)); LogUtils.d(TAG, String.format("notifyAppConfigUpdate() 执行 | 充电阈值=%d | 耗电阈值=%d", chargeThreshold, usageThreshold));
if (latestConfig != null && mServiceHandler != null) { if (latestConfig != null && mServiceHandler != null) {
mCurrentConfigBean = latestConfig; mCurrentConfigBean = latestConfig;
RemindThread.startRemindThreadWithAppConfig(this, mServiceHandler, latestConfig); RemindThread.startRemindThreadWithAppConfig(this, mServiceHandler, latestConfig);
LogUtils.d(TAG, "notifyAppConfigUpdate配置已同步到提醒线程"); LogUtils.d(TAG, "notifyAppConfigUpdate() | 配置已同步到提醒线程");
} else { } else {
LogUtils.e(TAG, String.format("notifyAppConfigUpdate参数为空,同步失败 | latestConfig=%s | mServiceHandler=%s", latestConfig, mServiceHandler)); LogUtils.e(TAG, String.format("notifyAppConfigUpdate() | 参数为空,同步失败 | latestConfig=%s | mServiceHandler=%s", latestConfig, mServiceHandler));
} }
} }

View File

@@ -55,16 +55,16 @@ public class RemindThread extends Thread {
private volatile long sleepTime; private volatile long sleepTime;
private volatile int chargeReminderValue; private volatile int chargeReminderValue;
private volatile int usageReminderValue; private volatile int usageReminderValue;
public static volatile int sQuantityOfElectricity = INVALID_BATTERY_VALUE;; public static volatile int sQuantityOfElectricity = INVALID_BATTERY_VALUE;
private volatile boolean isCharging; private volatile boolean isCharging;
// ====================== 私有构造器(禁止外部实例化) ====================== // ====================== 私有构造器(禁止外部实例化) ======================
private RemindThread(Context context, ControlCenterServiceHandler handler) { private RemindThread(Context context, ControlCenterServiceHandler handler) {
LogUtils.d(TAG, String.format("构造器调用 | context=%s | handler=%s", context, handler)); LogUtils.d(TAG, String.format("RemindThread() 构造器调用 | context=%s | handler=%s", context, handler));
this.mContext = context.getApplicationContext(); this.mContext = context.getApplicationContext();
this.mwrControlCenterServiceHandler = new WeakReference<>(handler); this.mwrControlCenterServiceHandler = new WeakReference<>(handler);
resetThreadStateInternal(); resetThreadStateInternal();
LogUtils.d(TAG, String.format("构造完成 | threadId=%d | 初始状态重置成功", getId())); LogUtils.d(TAG, String.format("RemindThread() 构造完成 | threadId=%d | 初始状态重置成功", getId()));
} }
// ====================== 对外公开静态接口(多实例列表管理) ====================== // ====================== 对外公开静态接口(多实例列表管理) ======================
@@ -77,7 +77,7 @@ public class RemindThread extends Thread {
* @return true: 启动成功false: 入参非法 * @return true: 启动成功false: 入参非法
*/ */
public static boolean startRemindThreadWithAppConfig(Context context, ControlCenterServiceHandler handler, AppConfigBean config) { public static boolean startRemindThreadWithAppConfig(Context context, ControlCenterServiceHandler handler, AppConfigBean config) {
LogUtils.d(TAG, String.format("startRemindThreadWithAppConfig调用 | context=%s | handler=%s | config=%s", context, handler, config)); LogUtils.d(TAG, String.format("startRemindThreadWithAppConfig() 调用 | context=%s | handler=%s | config=%s", context, handler, config));
// 入参严格校验 // 入参严格校验
if (context == null || handler == null || config == null) { if (context == null || handler == null || config == null) {
@@ -108,55 +108,12 @@ public class RemindThread extends Thread {
return true; return true;
} }
/**
* 启动提醒线程,同步电池状态信息
* 逻辑:停止所有旧线程 → 创建新线程 → 同步电池状态 → 加入列表管理
* @param context 上下文(非空)
* @param handler 服务处理器(非空)
* @param isCharging 充电状态
* @param batteryLevel 当前电量
* @return true: 启动成功false: 入参非法
*/
/*public static boolean startRemindThreadWithBatteryInfo(Context context, ControlCenterServiceHandler handler, boolean isCharging, int batteryLevel) {
LogUtils.d(TAG, String.format("startRemindThreadWithBatteryInfo调用 | context=%s | handler=%s | isCharging=%b | batteryLevel=%d", context, handler, isCharging, batteryLevel));
// 入参严格校验
if (context == null || handler == null) {
LogUtils.e(TAG, String.format("启动失败:入参为空 | context=%s | handler=%s", context, handler));
return false;
}
// 初始化线程列表(双重校验锁)
if (sRemindThreadList == null) {
synchronized (RemindThread.class) {
if (sRemindThreadList == null) {
sRemindThreadList = new ArrayList<RemindThread>();
LogUtils.d(TAG, "线程列表初始化完成");
}
}
}
// 停止所有旧线程
stopAllOldThreadsInternal();
// 创建并启动新线程
RemindThread newRemindThread = new RemindThread(context, handler);
// 同步电池状态(范围校验)
newRemindThread.isCharging = isCharging;
newRemindThread.sQuantityOfElectricity = Math.min(Math.max(batteryLevel, BATTERY_LEVEL_MIN), BATTERY_LEVEL_MAX);
newRemindThread.isExist = false;
newRemindThread.start();
sRemindThreadList.add(newRemindThread);
LogUtils.d(TAG, String.format("新线程启动成功 | threadId=%d | 电池状态同步完成(电量=%d充电=%b", newRemindThread.getId(), newRemindThread.sQuantityOfElectricity, newRemindThread.isCharging));
return true;
}*/
/** /**
* 安全停止所有线程,清空列表 * 安全停止所有线程,清空列表
*/ */
public static void stopRemindThread() { public static void stopRemindThread() {
int listSize = sRemindThreadList != null ? sRemindThreadList.size() : 0; int listSize = sRemindThreadList != null ? sRemindThreadList.size() : 0;
LogUtils.d(TAG, String.format("stopRemindThread调用 | 列表存在=%b | 列表大小=%d", sRemindThreadList != null, listSize)); LogUtils.d(TAG, String.format("stopRemindThread() 调用 | 列表存在=%b | 列表大小=%d", sRemindThreadList != null, listSize));
if (sRemindThreadList == null || sRemindThreadList.isEmpty()) { if (sRemindThreadList == null || sRemindThreadList.isEmpty()) {
LogUtils.w(TAG, "停止失败:线程列表为空"); LogUtils.w(TAG, "停止失败:线程列表为空");
return; return;
@@ -194,7 +151,7 @@ public class RemindThread extends Thread {
// ====================== 线程核心运行逻辑 ====================== // ====================== 线程核心运行逻辑 ======================
@Override @Override
public void run() { public void run() {
LogUtils.d(TAG, String.format("run执行 | threadId=%d | 状态=%s", getId(), getState())); LogUtils.d(TAG, String.format("run() 执行 | threadId=%d | 状态=%s", getId(), getState()));
// 初始化提醒状态(加锁保护,避免多线程竞争) // 初始化提醒状态(加锁保护,避免多线程竞争)
synchronized (mRemindLock) { synchronized (mRemindLock) {
@@ -244,7 +201,7 @@ public class RemindThread extends Thread {
// 循环退出,清理状态 // 循环退出,清理状态
cleanThreadStateInternal(); cleanThreadStateInternal();
LogUtils.d(TAG, String.format("run结束 | threadId=%d", getId())); LogUtils.d(TAG, String.format("run() 结束 | threadId=%d", getId()));
} }
// ====================== 内部业务辅助方法 ====================== // ====================== 内部业务辅助方法 ======================
@@ -255,7 +212,7 @@ public class RemindThread extends Thread {
* @param isCharging 充电状态 * @param isCharging 充电状态
*/ */
private void sendNotificationMessageInternal(String type, int battery, boolean isCharging) { private void sendNotificationMessageInternal(String type, int battery, boolean isCharging) {
LogUtils.d(TAG, String.format("sendNotificationMessageInternal调用 | 类型=%s | 电量=%d | isCharging=%b | threadId=%d", type, battery, isCharging, getId())); LogUtils.d(TAG, String.format("sendNotificationMessageInternal() 调用 | 类型=%s | 电量=%d | isCharging=%b | threadId=%d", type, battery, isCharging, getId()));
// 前置状态校验 // 前置状态校验
if (isExist || !isReminding) { if (isExist || !isReminding) {
LogUtils.d(TAG, String.format("消息发送跳过:线程已退出或提醒关闭 | threadId=%d", getId())); LogUtils.d(TAG, String.format("消息发送跳过:线程已退出或提醒关闭 | threadId=%d", getId()));
@@ -292,7 +249,7 @@ public class RemindThread extends Thread {
* @param millis 休眠时长(ms) * @param millis 休眠时长(ms)
*/ */
private void safeSleepInternal(long millis) { private void safeSleepInternal(long millis) {
LogUtils.d(TAG, String.format("safeSleepInternal调用 | 休眠时长=%dms | threadId=%d", millis, getId())); LogUtils.d(TAG, String.format("safeSleepInternal() 调用 | 休眠时长=%dms | threadId=%d", millis, getId()));
try { try {
Thread.sleep(millis); Thread.sleep(millis);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@@ -305,7 +262,7 @@ public class RemindThread extends Thread {
* 重置线程初始状态(构造器专用) * 重置线程初始状态(构造器专用)
*/ */
private void resetThreadStateInternal() { private void resetThreadStateInternal() {
LogUtils.d(TAG, String.format("resetThreadStateInternal调用 | threadId=%d", getId())); LogUtils.d(TAG, String.format("resetThreadStateInternal() 调用 | threadId=%d", getId()));
// 状态标记初始化 // 状态标记初始化
isExist = false; isExist = false;
isReminding = false; isReminding = false;
@@ -323,7 +280,7 @@ public class RemindThread extends Thread {
* 清理线程运行状态(循环退出时调用) * 清理线程运行状态(循环退出时调用)
*/ */
private void cleanThreadStateInternal() { private void cleanThreadStateInternal() {
LogUtils.d(TAG, String.format("cleanThreadStateInternal调用 | threadId=%d", getId())); LogUtils.d(TAG, String.format("cleanThreadStateInternal() 调用 | threadId=%d", getId()));
isReminding = false; isReminding = false;
isExist = true; isExist = true;
sQuantityOfElectricity = INVALID_BATTERY_VALUE; sQuantityOfElectricity = INVALID_BATTERY_VALUE;
@@ -340,7 +297,7 @@ public class RemindThread extends Thread {
* @param config 应用配置Bean * @param config 应用配置Bean
*/ */
public void setAppConfigBean(AppConfigBean config) { public void setAppConfigBean(AppConfigBean config) {
LogUtils.d(TAG, String.format("setAppConfigBean调用 | config=%s | threadId=%d", config, getId())); LogUtils.d(TAG, String.format("setAppConfigBean() 调用 | config=%s | threadId=%d", config, getId()));
if (config == null) { if (config == null) {
LogUtils.e(TAG, String.format("配置同步失败配置Bean为空 | threadId=%d", getId())); LogUtils.e(TAG, String.format("配置同步失败配置Bean为空 | threadId=%d", getId()));
sQuantityOfElectricity = INVALID_BATTERY_VALUE; sQuantityOfElectricity = INVALID_BATTERY_VALUE;
@@ -354,7 +311,7 @@ public class RemindThread extends Thread {
usageReminderValue = Math.min(Math.max(config.getUsageReminderValue(), BATTERY_LEVEL_MIN), BATTERY_LEVEL_MAX); usageReminderValue = Math.min(Math.max(config.getUsageReminderValue(), BATTERY_LEVEL_MIN), BATTERY_LEVEL_MAX);
sleepTime = Math.max(config.getBatteryDetectInterval(), MIN_SLEEP_TIME); sleepTime = Math.max(config.getBatteryDetectInterval(), MIN_SLEEP_TIME);
// sQuantityOfElectricity = (config.getCurrentBatteryValue() >= BATTERY_LEVEL_MIN && config.getCurrentBatteryValue() <= BATTERY_LEVEL_MAX) // sQuantityOfElectricity = (config.getCurrentBatteryValue() >= BATTERY_LEVEL_MIN && config.getCurrentBatteryValue() <= BATTERY_LEVEL_MAX)
// ? config.getCurrentBatteryValue() : INVALID_BATTERY_VALUE; // ? config.getCurrentBatteryValue() : INVALID_BATTERY_VALUE;
isCharging = config.isCharging(); isCharging = config.isCharging();
LogUtils.d(TAG, String.format("配置同步完成 | 休眠时间=%dms | 充电提醒=%b | 耗电提醒=%b | 当前电量=%d | 充电阈值=%d | 耗电阈值=%d | threadId=%d", LogUtils.d(TAG, String.format("配置同步完成 | 休眠时间=%dms | 充电提醒=%b | 耗电提醒=%b | 当前电量=%d | 充电阈值=%d | 耗电阈值=%d | threadId=%d",
@@ -367,13 +324,13 @@ public class RemindThread extends Thread {
*/ */
private boolean isRunning() { private boolean isRunning() {
boolean running = !isExist && isAlive(); boolean running = !isExist && isAlive();
LogUtils.d(TAG, String.format("isRunning调用 | 运行中=%b | 退出标记=%b | 存活=%b | threadId=%d", running, isExist, isAlive(), getId())); LogUtils.d(TAG, String.format("isRunning() 调用 | 运行中=%b | 退出标记=%b | 存活=%b | threadId=%d", running, isExist, isAlive(), getId()));
return running; return running;
} }
// ====================== Getter/Setter按需开放 ====================== // ====================== Getter/Setter按需开放 ======================
public void setIsExist(boolean isExist) { public void setIsExist(boolean isExist) {
LogUtils.d(TAG, String.format("setIsExist调用 | isExist=%b | threadId=%d", isExist, getId())); LogUtils.d(TAG, String.format("setIsExist() 调用 | isExist=%b | threadId=%d", isExist, getId()));
this.isExist = isExist; this.isExist = isExist;
} }
@@ -385,16 +342,16 @@ public class RemindThread extends Thread {
@Override @Override
public String toString() { public String toString() {
return "RemindThread{" + return "RemindThread{" +
"threadId=" + getId() + "threadId=" + getId() +
", threadName='" + getName() + '\'' + ", threadName='" + getName() + '\'' +
", isRunning=" + isRunning() + ", isRunning=" + isRunning() +
", isReminding=" + isReminding + ", isReminding=" + isReminding +
", chargeThreshold=" + chargeReminderValue + ", chargeThreshold=" + chargeReminderValue +
", usageThreshold=" + usageReminderValue + ", usageThreshold=" + usageReminderValue +
", currentBattery=" + sQuantityOfElectricity + ", currentBattery=" + sQuantityOfElectricity +
", isCharging=" + isCharging + ", isCharging=" + isCharging +
", sleepTime=" + sleepTime + "ms" + ", sleepTime=" + sleepTime + "ms" +
'}'; '}';
} }
} }

View File

@@ -39,10 +39,10 @@ public class AppConfigUtils {
*/ */
public static AppConfigUtils getInstance(Context context) { public static AppConfigUtils getInstance(Context context) {
String contextType = context != null ? context.getClass().getSimpleName() : "null"; String contextType = context != null ? context.getClass().getSimpleName() : "null";
LogUtils.d(TAG, String.format("getInstance调用 | 传入Context类型=%s", contextType)); LogUtils.d(TAG, String.format("getInstance() 调用 | 传入Context类型=%s", contextType));
if (context == null) { if (context == null) {
LogUtils.e(TAG, "getInstance失败Context不能为空"); LogUtils.e(TAG, "getInstance() 失败Context不能为空");
throw new IllegalArgumentException("Context cannot be null"); throw new IllegalArgumentException("Context cannot be null");
} }
@@ -50,12 +50,12 @@ public class AppConfigUtils {
synchronized (AppConfigUtils.class) { synchronized (AppConfigUtils.class) {
if (sInstance == null) { if (sInstance == null) {
sInstance = new AppConfigUtils(context); sInstance = new AppConfigUtils(context);
LogUtils.d(TAG, "getInstance单例实例创建成功"); LogUtils.d(TAG, "getInstance():单例实例创建成功");
} }
} }
} }
LogUtils.d(TAG, "getInstance单例实例获取成功"); LogUtils.d(TAG, "getInstance():单例实例获取成功");
return sInstance; return sInstance;
} }
@@ -64,12 +64,12 @@ public class AppConfigUtils {
* @param context 上下文内部转换为ApplicationContext * @param context 上下文内部转换为ApplicationContext
*/ */
private AppConfigUtils(Context context) { private AppConfigUtils(Context context) {
LogUtils.d(TAG, "AppConfigUtils构造方法调用"); LogUtils.d(TAG, "AppConfigUtils() 构造方法调用");
this.mContext = context.getApplicationContext(); this.mContext = context.getApplicationContext();
this.mApplication = (App) context.getApplicationContext(); this.mApplication = (App) context.getApplicationContext();
mAppConfigBean = new AppConfigBean(); mAppConfigBean = new AppConfigBean();
loadAppConfig(); // 加载持久化配置 loadAppConfig(); // 加载持久化配置
LogUtils.d(TAG, "AppConfigUtils构造完成配置初始化成功"); LogUtils.d(TAG, "AppConfigUtils() 构造完成,配置初始化成功");
} }
// ======================== 核心配置持久化方法区(加载+保存)======================== // ======================== 核心配置持久化方法区(加载+保存)========================
@@ -78,17 +78,17 @@ public class AppConfigUtils {
* @return 加载后的应用配置Bean * @return 加载后的应用配置Bean
*/ */
public AppConfigBean loadAppConfig() { public AppConfigBean loadAppConfig() {
LogUtils.d(TAG, "loadAppConfig调用:开始加载应用配置"); LogUtils.d(TAG, "loadAppConfig() 调用 | 开始加载应用配置");
AppConfigBean savedAppBean = (AppConfigBean) AppConfigBean.loadBean(mContext, AppConfigBean.class); AppConfigBean savedAppBean = (AppConfigBean) AppConfigBean.loadBean(mContext, AppConfigBean.class);
if (savedAppBean != null) { if (savedAppBean != null) {
mAppConfigBean = savedAppBean; mAppConfigBean = savedAppBean;
LogUtils.d(TAG, String.format("loadAppConfig成功 | 充电阈值=%d%% | 耗电阈值=%d%%", LogUtils.d(TAG, String.format("loadAppConfig() 成功 | 充电阈值=%d%% | 耗电阈值=%d%%",
mAppConfigBean.getChargeReminderValue(), mAppConfigBean.getUsageReminderValue())); mAppConfigBean.getChargeReminderValue(), mAppConfigBean.getUsageReminderValue()));
} else { } else {
mAppConfigBean = new AppConfigBean(); mAppConfigBean = new AppConfigBean();
AppConfigBean.saveBean(mContext, mAppConfigBean); AppConfigBean.saveBean(mContext, mAppConfigBean);
LogUtils.d(TAG, "loadAppConfig无已保存配置使用默认值并持久化"); LogUtils.d(TAG, "loadAppConfig():无已保存配置,使用默认值并持久化");
} }
return mAppConfigBean; return mAppConfigBean;
@@ -99,7 +99,7 @@ public class AppConfigUtils {
*/ */
public void saveAppConfig() { public void saveAppConfig() {
AppConfigBean.saveBean(mContext, mAppConfigBean); AppConfigBean.saveBean(mContext, mAppConfigBean);
LogUtils.d(TAG, "saveAppConfig应用配置保存成功"); LogUtils.d(TAG, "saveAppConfig():应用配置保存成功");
} }
// ======================== 充电提醒配置方法区(开关+阈值)======================== // ======================== 充电提醒配置方法区(开关+阈值)========================
@@ -108,16 +108,16 @@ public class AppConfigUtils {
* @param isEnabled 目标状态true=开启false=关闭) * @param isEnabled 目标状态true=开启false=关闭)
*/ */
public void setChargeReminderEnabled(final boolean isEnabled) { public void setChargeReminderEnabled(final boolean isEnabled) {
LogUtils.d(TAG, String.format("setChargeReminderEnabled调用 | 传入状态=%b", isEnabled)); LogUtils.d(TAG, String.format("setChargeReminderEnabled() 调用 | 传入状态=%b", isEnabled));
if (isEnabled == mAppConfigBean.isEnableChargeReminder()) { if (isEnabled == mAppConfigBean.isEnableChargeReminder()) {
LogUtils.d(TAG, "setChargeReminderEnabled充电提醒状态无变化无需操作"); LogUtils.d(TAG, "setChargeReminderEnabled():充电提醒状态无变化,无需操作");
return; return;
} }
mAppConfigBean.setEnableChargeReminder(isEnabled); mAppConfigBean.setEnableChargeReminder(isEnabled);
saveAppConfig(); saveAppConfig();
LogUtils.d(TAG, String.format("setChargeReminderEnabled成功 | 充电提醒状态=%s", isEnabled ? "开启" : "关闭")); LogUtils.d(TAG, String.format("setChargeReminderEnabled() 成功 | 充电提醒状态=%s", isEnabled ? "开启" : "关闭"));
} }
/** /**
@@ -126,7 +126,7 @@ public class AppConfigUtils {
*/ */
public boolean isChargeReminderEnabled() { public boolean isChargeReminderEnabled() {
boolean isEnabled = mAppConfigBean.isEnableChargeReminder(); boolean isEnabled = mAppConfigBean.isEnableChargeReminder();
LogUtils.d(TAG, String.format("isChargeReminderEnabled获取充电提醒状态=%s", isEnabled ? "开启" : "关闭")); LogUtils.d(TAG, String.format("isChargeReminderEnabled():获取充电提醒状态=%s", isEnabled ? "开启" : "关闭"));
return isEnabled; return isEnabled;
} }
@@ -135,17 +135,17 @@ public class AppConfigUtils {
* @param value 目标阈值 * @param value 目标阈值
*/ */
public void setChargeReminderValue(final int value) { public void setChargeReminderValue(final int value) {
LogUtils.d(TAG, String.format("setChargeReminderValue调用 | 传入阈值=%d", value)); LogUtils.d(TAG, String.format("setChargeReminderValue() 调用 | 传入阈值=%d", value));
final int calibratedValue = Math.min(Math.max(value, MIN_REMINDER_VALUE), MAX_REMINDER_VALUE); final int calibratedValue = Math.min(Math.max(value, MIN_REMINDER_VALUE), MAX_REMINDER_VALUE);
if (calibratedValue == mAppConfigBean.getChargeReminderValue()) { if (calibratedValue == mAppConfigBean.getChargeReminderValue()) {
LogUtils.d(TAG, "setChargeReminderValue充电提醒阈值无变化无需操作"); LogUtils.d(TAG, "setChargeReminderValue():充电提醒阈值无变化,无需操作");
return; return;
} }
mAppConfigBean.setChargeReminderValue(calibratedValue); mAppConfigBean.setChargeReminderValue(calibratedValue);
saveAppConfig(); saveAppConfig();
LogUtils.d(TAG, String.format("setChargeReminderValue成功 | 充电提醒阈值=%d%%", calibratedValue)); LogUtils.d(TAG, String.format("setChargeReminderValue() 成功 | 充电提醒阈值=%d%%", calibratedValue));
} }
/** /**
@@ -154,7 +154,7 @@ public class AppConfigUtils {
*/ */
public int getChargeReminderValue() { public int getChargeReminderValue() {
int value = mAppConfigBean.getChargeReminderValue(); int value = mAppConfigBean.getChargeReminderValue();
LogUtils.d(TAG, String.format("getChargeReminderValue获取充电提醒阈值=%d%%", value)); LogUtils.d(TAG, String.format("getChargeReminderValue():获取充电提醒阈值=%d%%", value));
return value; return value;
} }
@@ -164,16 +164,16 @@ public class AppConfigUtils {
* @param isEnabled 目标状态true=开启false=关闭) * @param isEnabled 目标状态true=开启false=关闭)
*/ */
public void setUsageReminderEnabled(final boolean isEnabled) { public void setUsageReminderEnabled(final boolean isEnabled) {
LogUtils.d(TAG, String.format("setUsageReminderEnabled调用 | 传入状态=%b", isEnabled)); LogUtils.d(TAG, String.format("setUsageReminderEnabled() 调用 | 传入状态=%b", isEnabled));
if (isEnabled == mAppConfigBean.isEnableUsageReminder()) { if (isEnabled == mAppConfigBean.isEnableUsageReminder()) {
LogUtils.d(TAG, "setUsageReminderEnabled耗电提醒状态无变化无需操作"); LogUtils.d(TAG, "setUsageReminderEnabled():耗电提醒状态无变化,无需操作");
return; return;
} }
mAppConfigBean.setEnableUsageReminder(isEnabled); mAppConfigBean.setEnableUsageReminder(isEnabled);
saveAppConfig(); saveAppConfig();
LogUtils.d(TAG, String.format("setUsageReminderEnabled成功 | 耗电提醒状态=%s", isEnabled ? "开启" : "关闭")); LogUtils.d(TAG, String.format("setUsageReminderEnabled() 成功 | 耗电提醒状态=%s", isEnabled ? "开启" : "关闭"));
} }
/** /**
@@ -182,7 +182,7 @@ public class AppConfigUtils {
*/ */
public boolean isUsageReminderEnabled() { public boolean isUsageReminderEnabled() {
boolean isEnabled = mAppConfigBean.isEnableUsageReminder(); boolean isEnabled = mAppConfigBean.isEnableUsageReminder();
LogUtils.d(TAG, String.format("isUsageReminderEnabled获取耗电提醒状态=%s", isEnabled ? "开启" : "关闭")); LogUtils.d(TAG, String.format("isUsageReminderEnabled():获取耗电提醒状态=%s", isEnabled ? "开启" : "关闭"));
return isEnabled; return isEnabled;
} }
@@ -191,17 +191,17 @@ public class AppConfigUtils {
* @param value 目标阈值 * @param value 目标阈值
*/ */
public void setUsageReminderValue(final int value) { public void setUsageReminderValue(final int value) {
LogUtils.d(TAG, String.format("setUsageReminderValue调用 | 传入阈值=%d", value)); LogUtils.d(TAG, String.format("setUsageReminderValue() 调用 | 传入阈值=%d", value));
final int calibratedValue = Math.min(Math.max(value, MIN_REMINDER_VALUE), MAX_REMINDER_VALUE); final int calibratedValue = Math.min(Math.max(value, MIN_REMINDER_VALUE), MAX_REMINDER_VALUE);
if (calibratedValue == mAppConfigBean.getUsageReminderValue()) { if (calibratedValue == mAppConfigBean.getUsageReminderValue()) {
LogUtils.d(TAG, "setUsageReminderValue耗电提醒阈值无变化无需操作"); LogUtils.d(TAG, "setUsageReminderValue():耗电提醒阈值无变化,无需操作");
return; return;
} }
mAppConfigBean.setUsageReminderValue(calibratedValue); mAppConfigBean.setUsageReminderValue(calibratedValue);
saveAppConfig(); saveAppConfig();
LogUtils.d(TAG, String.format("setUsageReminderValue成功 | 耗电提醒阈值=%d%%", calibratedValue)); LogUtils.d(TAG, String.format("setUsageReminderValue() 成功 | 耗电提醒阈值=%d%%", calibratedValue));
} }
/** /**
@@ -210,7 +210,7 @@ public class AppConfigUtils {
*/ */
public int getUsageReminderValue() { public int getUsageReminderValue() {
int value = mAppConfigBean.getUsageReminderValue(); int value = mAppConfigBean.getUsageReminderValue();
LogUtils.d(TAG, String.format("getUsageReminderValue获取耗电提醒阈值=%d%%", value)); LogUtils.d(TAG, String.format("getUsageReminderValue():获取耗电提醒阈值=%d%%", value));
return value; return value;
} }
@@ -220,15 +220,15 @@ public class AppConfigUtils {
* @param isCharging 充电状态true=充电中false=未充电) * @param isCharging 充电状态true=充电中false=未充电)
*/ */
public void setCharging(boolean isCharging) { public void setCharging(boolean isCharging) {
LogUtils.d(TAG, String.format("setCharging调用 | 传入状态=%b", isCharging)); LogUtils.d(TAG, String.format("setCharging() 调用 | 传入状态=%b", isCharging));
if (isCharging == mAppConfigBean.isCharging()) { if (isCharging == mAppConfigBean.isCharging()) {
LogUtils.d(TAG, "setCharging充电状态无变化无需操作"); LogUtils.d(TAG, "setCharging():充电状态无变化,无需操作");
return; return;
} }
mAppConfigBean.setIsCharging(isCharging); mAppConfigBean.setIsCharging(isCharging);
LogUtils.d(TAG, String.format("setCharging成功 | 充电状态=%s", isCharging ? "充电中" : "未充电")); LogUtils.d(TAG, String.format("setCharging() 成功 | 充电状态=%s", isCharging ? "充电中" : "未充电"));
} }
/** /**
@@ -237,7 +237,7 @@ public class AppConfigUtils {
*/ */
public boolean isCharging() { public boolean isCharging() {
boolean isCharging = mAppConfigBean.isCharging(); boolean isCharging = mAppConfigBean.isCharging();
LogUtils.d(TAG, String.format("isCharging获取充电状态=%s", isCharging ? "充电中" : "未充电")); LogUtils.d(TAG, String.format("isCharging():获取充电状态=%s", isCharging ? "充电中" : "未充电"));
return isCharging; return isCharging;
} }
@@ -246,16 +246,16 @@ public class AppConfigUtils {
* @param value 当前电量 * @param value 当前电量
*/ */
public void setCurrentBatteryValue(int value) { public void setCurrentBatteryValue(int value) {
LogUtils.d(TAG, String.format("setCurrentBatteryValue调用 | 传入电量=%d", value)); LogUtils.d(TAG, String.format("setCurrentBatteryValue() 调用 | 传入电量=%d", value));
int calibratedValue = Math.min(Math.max(value, MIN_REMINDER_VALUE), MAX_REMINDER_VALUE); int calibratedValue = Math.min(Math.max(value, MIN_REMINDER_VALUE), MAX_REMINDER_VALUE);
if (calibratedValue == RemindThread.sQuantityOfElectricity) { if (calibratedValue == RemindThread.sQuantityOfElectricity) {
LogUtils.d(TAG, "setCurrentBatteryValue电池电量无变化无需操作"); LogUtils.d(TAG, "setCurrentBatteryValue():电池电量无变化,无需操作");
return; return;
} }
RemindThread.sQuantityOfElectricity = calibratedValue; RemindThread.sQuantityOfElectricity = calibratedValue;
LogUtils.d(TAG, String.format("setCurrentBatteryValue成功 | 电池电量=%d%%", calibratedValue)); LogUtils.d(TAG, String.format("setCurrentBatteryValue() 成功 | 电池电量=%d%%", calibratedValue));
} }
/** /**
@@ -264,7 +264,7 @@ public class AppConfigUtils {
*/ */
public int getCurrentBatteryValue() { public int getCurrentBatteryValue() {
int value = RemindThread.sQuantityOfElectricity; int value = RemindThread.sQuantityOfElectricity;
LogUtils.d(TAG, String.format("getCurrentBatteryValue获取电池电量=%d%%", value)); LogUtils.d(TAG, String.format("getCurrentBatteryValue():获取电池电量=%d%%", value));
return value; return value;
} }
@@ -274,17 +274,17 @@ public class AppConfigUtils {
* @param interval 目标间隔单位ms * @param interval 目标间隔单位ms
*/ */
public void setReminderIntervalTime(final int interval) { public void setReminderIntervalTime(final int interval) {
LogUtils.d(TAG, String.format("setReminderIntervalTime调用 | 传入间隔=%dms", interval)); LogUtils.d(TAG, String.format("setReminderIntervalTime() 调用 | 传入间隔=%dms", interval));
final int calibratedInterval = Math.max(interval, MIN_INTERVAL_TIME); final int calibratedInterval = Math.max(interval, MIN_INTERVAL_TIME);
if (calibratedInterval == mAppConfigBean.getReminderIntervalTime()) { if (calibratedInterval == mAppConfigBean.getReminderIntervalTime()) {
LogUtils.d(TAG, "setReminderIntervalTime提醒间隔无变化无需操作"); LogUtils.d(TAG, "setReminderIntervalTime():提醒间隔无变化,无需操作");
return; return;
} }
mAppConfigBean.setReminderIntervalTime(calibratedInterval); mAppConfigBean.setReminderIntervalTime(calibratedInterval);
saveAppConfig(); saveAppConfig();
LogUtils.d(TAG, String.format("setReminderIntervalTime成功 | 提醒间隔=%dms", calibratedInterval)); LogUtils.d(TAG, String.format("setReminderIntervalTime() 成功 | 提醒间隔=%dms", calibratedInterval));
} }
/** /**
@@ -293,7 +293,7 @@ public class AppConfigUtils {
*/ */
public int getReminderIntervalTime() { public int getReminderIntervalTime() {
int interval = mAppConfigBean.getReminderIntervalTime(); int interval = mAppConfigBean.getReminderIntervalTime();
LogUtils.d(TAG, String.format("getReminderIntervalTime获取提醒间隔=%dms", interval)); LogUtils.d(TAG, String.format("getReminderIntervalTime():获取提醒间隔=%dms", interval));
return interval; return interval;
} }
@@ -302,17 +302,17 @@ public class AppConfigUtils {
* @param interval 目标间隔单位ms * @param interval 目标间隔单位ms
*/ */
public void setBatteryDetectInterval(final int interval) { public void setBatteryDetectInterval(final int interval) {
LogUtils.d(TAG, String.format("setBatteryDetectInterval调用 | 传入间隔=%dms", interval)); LogUtils.d(TAG, String.format("setBatteryDetectInterval() 调用 | 传入间隔=%dms", interval));
final int calibratedInterval = Math.max(interval, MIN_DETECT_INTERVAL); final int calibratedInterval = Math.max(interval, MIN_DETECT_INTERVAL);
if (calibratedInterval == mAppConfigBean.getBatteryDetectInterval()) { if (calibratedInterval == mAppConfigBean.getBatteryDetectInterval()) {
LogUtils.d(TAG, "setBatteryDetectInterval检测间隔无变化无需操作"); LogUtils.d(TAG, "setBatteryDetectInterval():检测间隔无变化,无需操作");
return; return;
} }
mAppConfigBean.setBatteryDetectInterval(calibratedInterval); mAppConfigBean.setBatteryDetectInterval(calibratedInterval);
saveAppConfig(); saveAppConfig();
LogUtils.d(TAG, String.format("setBatteryDetectInterval成功 | 电量检测间隔=%dms", calibratedInterval)); LogUtils.d(TAG, String.format("setBatteryDetectInterval() 成功 | 电量检测间隔=%dms", calibratedInterval));
} }
/** /**
@@ -321,7 +321,7 @@ public class AppConfigUtils {
*/ */
public int getBatteryDetectInterval() { public int getBatteryDetectInterval() {
int interval = mAppConfigBean.getBatteryDetectInterval(); int interval = mAppConfigBean.getBatteryDetectInterval();
LogUtils.d(TAG, String.format("getBatteryDetectInterval获取电量检测间隔=%dms", interval)); LogUtils.d(TAG, String.format("getBatteryDetectInterval():获取电量检测间隔=%dms", interval));
return interval; return interval;
} }
@@ -331,16 +331,16 @@ public class AppConfigUtils {
* @return 服务开关状态true=开启false=关闭) * @return 服务开关状态true=开启false=关闭)
*/ */
public boolean isServiceEnabled() { public boolean isServiceEnabled() {
LogUtils.d(TAG, "isServiceEnabled调用:开始获取服务开关状态"); LogUtils.d(TAG, "isServiceEnabled() 调用 | 开始获取服务开关状态");
ControlCenterServiceBean savedServiceBean = (ControlCenterServiceBean) ControlCenterServiceBean.loadBean(mContext, ControlCenterServiceBean.class); ControlCenterServiceBean savedServiceBean = (ControlCenterServiceBean) ControlCenterServiceBean.loadBean(mContext, ControlCenterServiceBean.class);
if (savedServiceBean != null) { if (savedServiceBean != null) {
boolean isEnabled = savedServiceBean.isEnableService(); boolean isEnabled = savedServiceBean.isEnableService();
LogUtils.d(TAG, String.format("isServiceEnabled服务开关状态=%b", isEnabled)); LogUtils.d(TAG, String.format("isServiceEnabled():服务开关状态=%b", isEnabled));
return isEnabled; return isEnabled;
} else { } else {
ControlCenterServiceBean.saveBean(mContext, new ControlCenterServiceBean(false)); ControlCenterServiceBean.saveBean(mContext, new ControlCenterServiceBean(false));
LogUtils.d(TAG, "isServiceEnabled无已保存服务配置默认关闭并持久化"); LogUtils.d(TAG, "isServiceEnabled():无已保存服务配置,默认关闭并持久化");
return false; return false;
} }
} }
@@ -350,9 +350,9 @@ public class AppConfigUtils {
* @param isServiceEnabled 目标状态true=开启false=关闭) * @param isServiceEnabled 目标状态true=开启false=关闭)
*/ */
public void setIsServiceEnabled(boolean isServiceEnabled) { public void setIsServiceEnabled(boolean isServiceEnabled) {
LogUtils.d(TAG, String.format("setIsServiceEnabled调用 | 传入状态=%b", isServiceEnabled)); LogUtils.d(TAG, String.format("setIsServiceEnabled() 调用 | 传入状态=%b", isServiceEnabled));
ControlCenterServiceBean.saveBean(mContext, new ControlCenterServiceBean(isServiceEnabled)); ControlCenterServiceBean.saveBean(mContext, new ControlCenterServiceBean(isServiceEnabled));
LogUtils.d(TAG, String.format("setIsServiceEnabled成功 | 服务开关状态=%b", isServiceEnabled)); LogUtils.d(TAG, String.format("setIsServiceEnabled() 成功 | 服务开关状态=%b", isServiceEnabled));
} }
} }