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

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
#Wed Dec 24 13:05:44 GMT 2025
#Wed Dec 24 13:18:30 GMT 2025
stageCount=29
libraryProject=
baseVersion=15.14
publishVersion=15.14.28
buildCount=103
buildCount=104
baseBetaVersion=15.14.29

View File

@@ -46,8 +46,7 @@ import java.io.File;
* @Author 豆包&ZhanGSKen<zhangsken@qq.com>
*/
public class BackgroundSettingsActivity extends WinBoLLActivity {
// ====================== 常量定义(按功能分类置顶)======================
// ====================== 常量定义(按功能分类)======================
public static final String TAG = "BackgroundSettingsActivity";
// 系统版本常量
private static final int SDK_VERSION_TIRAMISU = 33;
@@ -86,7 +85,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtils.d(TAG, "生命周期 onCreate() 开始初始化");
LogUtils.d(TAG, "onCreate() 开始初始化");
setContentView(R.layout.activity_background_settings);
// 初始化核心组件
@@ -94,20 +93,20 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
// 初始化界面与事件
initToolbar();
initClickListeners();
LogUtils.d(TAG, "初始化 界面与事件绑定完成");
LogUtils.d(TAG, "界面与事件绑定完成");
// 处理分享意图或初始化预览
handleIntentOrPreview();
// 初始化预览环境并刷新
initPreviewEnvironment();
LogUtils.d(TAG, "生命周期 onCreate() 初始化完成");
LogUtils.d(TAG, "onCreate() 初始化完成");
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
LogUtils.d(TAG, "生命周期 onPostCreate() 执行双重刷新预览");
LogUtils.d(TAG, "onPostCreate() 执行双重刷新预览");
// 监听视图布局完成事件
mBackgroundView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@@ -139,24 +138,24 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent 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 {
if (resultCode != RESULT_OK) {
LogUtils.d(TAG, "回调处理 结果非RESULT_OK执行取消逻辑");
LogUtils.d(TAG, "结果非RESULT_OK执行取消逻辑");
handleOperationCancelOrFail();
return;
}
handleActivityResult(requestCode, data);
} 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("操作失败");
}
}
@Override
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) {
super.finish();
} else {
@@ -168,7 +167,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] 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) {
handleCameraPermissionResult(grantResults);
}
@@ -176,9 +175,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
// ====================== 界面初始化方法Toolbar + 点击事件)======================
private void initToolbar() {
LogUtils.d(TAG, "initToolbar() 开始初始化");
mToolbar = findViewById(R.id.toolbar);
if (mToolbar == null) {
LogUtils.e(TAG, "初始化异常 initToolbar() | Toolbar未找到");
LogUtils.e(TAG, "initToolbar() | Toolbar未找到");
return;
}
setSupportActionBar(mToolbar);
@@ -192,11 +192,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
finish();
}
});
LogUtils.d(TAG, "界面初始化 initToolbar() | 配置完成");
LogUtils.d(TAG, "initToolbar() 配置完成");
}
private void initClickListeners() {
LogUtils.d(TAG, "界面初始化 initClickListeners() | 开始绑定按钮点击事件");
LogUtils.d(TAG, "initClickListeners() 开始绑定按钮点击事件");
// 绑定所有按钮点击事件
bindClickListener(R.id.activitybackgroundsettingsAButton1, onOriginNullClickListener);
bindClickListener(R.id.activitybackgroundsettingsAButton2, onReceivedPictureClickListener);
@@ -208,17 +208,18 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
bindClickListener(R.id.activitybackgroundsettingsAButton8, onPixelPickerClickListener);
bindClickListener(R.id.activitybackgroundsettingsAButton9, onColorPaletteClickListener);
bindClickListener(R.id.activitybackgroundsettingsAButton10, onCleanPixelClickListener);
LogUtils.d(TAG, "界面初始化 initClickListeners() | 按钮点击事件绑定完成");
LogUtils.d(TAG, "initClickListeners() 按钮点击事件绑定完成");
}
// 通用按钮绑定工具方法
private void bindClickListener(int resId, View.OnClickListener listener) {
LogUtils.d(TAG, String.format("bindClickListener() | resId=%d", resId));
View view = findViewById(resId);
if (view != null) {
view.setOnClickListener(listener);
LogUtils.d(TAG, String.format("绑定成功 bindClickListener() | resId=%d", resId));
LogUtils.d(TAG, String.format("bindClickListener() | resId=%d 绑定成功", resId));
} 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() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onOriginNullClickListener() | 取消背景图片");
LogUtils.d(TAG, "onOriginNullClickListener() | 取消背景图片");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onOriginNullClickListener() | 预览Bean为空");
LogUtils.e(TAG, "onOriginNullClickListener() | 预览Bean为空");
return;
}
previewBean.setIsUseBackgroundFile(false);
@@ -242,7 +243,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onSelectPictureClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onSelectPictureClickListener() | 选择图片");
LogUtils.d(TAG, "onSelectPictureClickListener() | 选择图片");
launchImageSelector();
}
};
@@ -250,7 +251,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onNetworkBackgroundDialog = new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onNetworkBackgroundDialog() | 打开网络背景对话框");
LogUtils.d(TAG, "onNetworkBackgroundDialog() | 打开网络背景对话框");
NetworkBackgroundDialog networkBackgroundDialog = new NetworkBackgroundDialog(BackgroundSettingsActivity.this, new NetworkBackgroundDialog.OnDialogClickListener() {
@Override
public void onConfirm(String szConfirmFilePath) {
@@ -273,7 +274,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onCropPictureClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onCropPictureClickListener() | 固定比例裁剪");
LogUtils.d(TAG, "onCropPictureClickListener() | 固定比例裁剪");
startImageCrop(false);
}
};
@@ -281,7 +282,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onCropFreePictureClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onCropFreePictureClickListener() | 自由裁剪");
LogUtils.d(TAG, "onCropFreePictureClickListener() | 自由裁剪");
startImageCrop(true);
}
};
@@ -289,11 +290,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onTakePhotoClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onTakePhotoClickListener() | 拍照");
LogUtils.d(TAG, "onTakePhotoClickListener() | 拍照");
// 动态申请相机权限
if (ContextCompat.checkSelfPermission(BackgroundSettingsActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
LogUtils.d(TAG, "拍照准备 onTakePhotoClickListener() | 相机权限未授予,发起申请");
LogUtils.d(TAG, "拍照准备 | 相机权限未授予,发起申请");
ActivityCompat.requestPermissions(
BackgroundSettingsActivity.this,
new String[]{Manifest.permission.CAMERA},
@@ -307,10 +308,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onReceivedPictureClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onReceivedPictureClickListener() | 恢复收到的图片");
LogUtils.d(TAG, "onReceivedPictureClickListener() | 恢复收到的图片");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onReceivedPictureClickListener() | 预览Bean为空");
LogUtils.e(TAG, "onReceivedPictureClickListener() | 预览Bean为空");
return;
}
previewBean.setIsUseBackgroundFile(true);
@@ -323,10 +324,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
private View.OnClickListener onPixelPickerClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onPixelPickerClickListener() | 像素拾取");
LogUtils.d(TAG, "onPixelPickerClickListener() | 像素拾取");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onPixelPickerClickListener() | 预览Bean为空");
LogUtils.e(TAG, "onPixelPickerClickListener() | 预览Bean为空");
ToastUtils.show("无有效图片可拾取像素");
return;
}
@@ -334,23 +335,23 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
File targetFile = new File(targetImagePath);
if (targetFile == null || !targetFile.exists() || targetFile.length() <= 0) {
ToastUtils.show("无有效图片可拾取像素");
LogUtils.e(TAG, String.format("像素拾取失败 onPixelPickerClickListener() | 文件无效:%s", targetImagePath));
LogUtils.e(TAG, String.format("像素拾取失败 | 文件无效:%s", targetImagePath));
return;
}
Intent intent = new Intent(getApplicationContext(), PixelPickerActivity.class);
intent.putExtra("imagePath", targetImagePath);
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() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onCleanPixelClickListener() | 清空像素颜色");
LogUtils.d(TAG, "onCleanPixelClickListener() | 清空像素颜色");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onCleanPixelClickListener() | 预览Bean为空");
LogUtils.e(TAG, "onCleanPixelClickListener() | 预览Bean为空");
return;
}
int oldColor = previewBean.getPixelColor();
@@ -359,21 +360,21 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
doubleRefreshPreview();
isPreviewBackgroundChanged = true;
ToastUtils.show("像素颜色已清空");
LogUtils.d(TAG, String.format("像素清空 onCleanPixelClickListener() | 旧颜色:#%08X", oldColor));
LogUtils.d(TAG, String.format("像素清空 | 旧颜色:#%08X", oldColor));
}
};
private View.OnClickListener onColorPaletteClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtils.d(TAG, "按钮点击 onColorPaletteClickListener() | 调色板按钮");
LogUtils.d(TAG, "onColorPaletteClickListener() | 调色板按钮");
final BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "操作异常 onColorPaletteClickListener() | 预览Bean为空");
LogUtils.e(TAG, "onColorPaletteClickListener() | 预览Bean为空");
return;
}
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() {
@Override
public void onColorSelected(int color) {
@@ -381,11 +382,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
mBgSourceUtils.saveSettings();
doubleRefreshPreview();
isPreviewBackgroundChanged = true;
LogUtils.d(TAG, String.format("颜色选择 onColorSelected() | 选中颜色:#%08X", color));
LogUtils.d(TAG, String.format("颜色选择 | 选中颜色:#%08X", color));
}
});
dialog.show();
LogUtils.d(TAG, "调色板 onColorPaletteClickListener() | 对话框已显示");
LogUtils.d(TAG, "调色板 | 对话框已显示");
}
};
@@ -396,9 +397,9 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 适配后的Uri失败返回null
*/
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) {
LogUtils.e(TAG, "工具异常 getFileProviderUri() | 文件为空");
LogUtils.e(TAG, "getFileProviderUri() | 文件为空");
return null;
}
try {
@@ -409,7 +410,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
return Uri.fromFile(file);
}
} 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;
}
}
@@ -421,7 +422,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
*/
private boolean isBitmapValid(Bitmap bitmap) {
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;
}
@@ -429,7 +430,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 双重刷新预览,确保背景加载最新数据
*/
private void doubleRefreshPreview() {
LogUtils.d(TAG, "工具方法 doubleRefreshPreview() | 开始双重刷新预览");
LogUtils.d(TAG, "doubleRefreshPreview() 开始双重刷新预览");
if (mBgSourceUtils == null || mBackgroundView == null || isFinishing()) {
LogUtils.w(TAG, "双重刷新 跳过对象为空或Activity已结束");
return;
@@ -440,9 +441,9 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
mBgSourceUtils.loadSettings();
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
mBackgroundView.loadByBackgroundBean(previewBean, true);
LogUtils.d(TAG, "双重刷新 doubleRefreshPreview() | 第一重完成");
LogUtils.d(TAG, "双重刷新 第一重完成");
} catch (Exception e) {
LogUtils.e(TAG, String.format("双重刷新 doubleRefreshPreview() | 第一重异常:%s", e.getMessage()));
LogUtils.e(TAG, String.format("双重刷新 第一重异常:%s", e.getMessage()));
return;
}
@@ -455,9 +456,9 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
mBgSourceUtils.loadSettings();
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
mBackgroundView.loadByBackgroundBean(previewBean, true);
LogUtils.d(TAG, "双重刷新 doubleRefreshPreview() | 第二重完成");
LogUtils.d(TAG, "双重刷新 第二重完成");
} 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() {
LogUtils.d(TAG, "initCoreComponents() 开始初始化");
// 初始化视图
mBackgroundView = findViewById(R.id.background_view);
if (mBackgroundView == null) {
LogUtils.e(TAG, "初始化异常 initCoreComponents() | BackgroundView未找到");
LogUtils.e(TAG, "initCoreComponents() | BackgroundView未找到");
}
// 初始化工具类
mBgSourceUtils = BackgroundSourceUtils.getInstance(this);
mBgSourceUtils.loadSettings();
mBitmapCache = BitmapCacheUtils.getInstance();
LogUtils.d(TAG, "初始化 initCoreComponents() | 视图与工具类加载完成");
LogUtils.d(TAG, "initCoreComponents() 视图与工具类加载完成");
}
/**
* 处理意图或初始化预览
*/
private void handleIntentOrPreview() {
LogUtils.d(TAG, "handleIntentOrPreview() 开始处理");
if (handleShareIntent()) {
ToastUtils.show("已接收分享图片");
LogUtils.d(TAG, "意图处理 handleIntentOrPreview() | 处理分享意图成功");
LogUtils.d(TAG, "handleIntentOrPreview() | 处理分享意图成功");
} else {
mBgSourceUtils.setCurrentSourceToPreview();
LogUtils.d(TAG, "意图处理 handleIntentOrPreview() | 加载当前背景配置");
LogUtils.d(TAG, "handleIntentOrPreview() | 加载当前背景配置");
}
}
@@ -498,10 +501,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 初始化预览环境
*/
private void initPreviewEnvironment() {
LogUtils.d(TAG, "initPreviewEnvironment() 开始初始化");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
mBgSourceUtils.createAndUpdatePreviewEnvironmentForCropping(previewBean);
doubleRefreshPreview();
LogUtils.d(TAG, "预览环境 initPreviewEnvironment() | 初始化完成");
LogUtils.d(TAG, "initPreviewEnvironment() 初始化完成");
}
/**
@@ -509,11 +513,12 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 处理成功返回true否则false
*/
private boolean handleShareIntent() {
LogUtils.d(TAG, "handleShareIntent() 开始处理");
Intent intent = getIntent();
if (intent != null) {
String action = intent.getAction();
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)) {
showSharePreviewDialog();
return true;
@@ -526,18 +531,18 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 显示分享图片预览对话框
*/
private void showSharePreviewDialog() {
LogUtils.d(TAG, "工具方法 showSharePreviewDialog()");
LogUtils.d(TAG, "showSharePreviewDialog() 开始显示");
BackgroundPicturePreviewDialog dlg = new BackgroundPicturePreviewDialog(this, new BackgroundPicturePreviewDialog.IOnRecivedPictureListener() {
@Override
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)) {
startImageCrop(false);
}
}
});
dlg.show();
LogUtils.d(TAG, "分享处理 showSharePreviewDialog() | 显示图片预览对话框");
LogUtils.d(TAG, "分享处理 | 显示图片预览对话框");
}
/**
@@ -550,7 +555,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
return false;
}
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/");
}
@@ -558,7 +563,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 启动图片选择器
*/
private void launchImageSelector() {
LogUtils.d(TAG, "业务逻辑 launchImageSelector() | 启动图片选择器");
LogUtils.d(TAG, "launchImageSelector() 启动图片选择器");
Intent[] intents = createImageSelectorIntents();
Intent validIntent = findValidIntent(intents);
@@ -574,6 +579,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 意图数组
*/
private Intent[] createImageSelectorIntents() {
LogUtils.d(TAG, "createImageSelectorIntents() 开始创建");
Intent[] intents = new Intent[3];
// 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);
intents[2] = openDocIntent;
}
LogUtils.d(TAG, "业务逻辑 createImageSelectorIntents() | 意图数组创建完成");
LogUtils.d(TAG, "createImageSelectorIntents() 意图数组创建完成");
return intents;
}
@@ -606,13 +612,14 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 有效意图无则返回null
*/
private Intent findValidIntent(Intent[] intents) {
LogUtils.d(TAG, "findValidIntent() 开始查找");
for (Intent intent : intents) {
if (intent != null && intent.resolveActivity(getPackageManager()) != null) {
LogUtils.d(TAG, "业务逻辑 findValidIntent() | 找到有效意图");
LogUtils.d(TAG, "findValidIntent() | 找到有效意图");
return intent;
}
}
LogUtils.d(TAG, "业务逻辑 findValidIntent() | 无有效意图");
LogUtils.d(TAG, "findValidIntent() | 无有效意图");
return null;
}
@@ -621,17 +628,18 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param validIntent 有效意图
*/
private void launchImageChooser(Intent validIntent) {
LogUtils.d(TAG, "launchImageChooser() 启动选择器");
Intent chooser = Intent.createChooser(validIntent, "选择图片");
chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
startActivityForResult(chooser, REQUEST_SELECT_PICTURE);
LogUtils.d(TAG, "选图意图 launchImageChooser() | 启动图片选择");
LogUtils.d(TAG, "launchImageChooser() | 启动图片选择");
}
/**
* 显示无相册应用提示对话框
*/
private void showNoGalleryDialog() {
LogUtils.d(TAG, "选图意图 showNoGalleryDialog() | 无相册应用");
LogUtils.d(TAG, "showNoGalleryDialog() | 无相册应用");
runOnUiThread(new Runnable() {
@Override
public void run() {
@@ -655,14 +663,15 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 启动应用商店下载相册
*/
private void launchGalleryMarket() {
LogUtils.d(TAG, "launchGalleryMarket() 启动应用商店");
Intent marketIntent = new Intent(Intent.ACTION_VIEW);
marketIntent.setData(Uri.parse("market://details?id=com.android.gallery3d"));
if (marketIntent.resolveActivity(getPackageManager()) != null) {
startActivity(marketIntent);
LogUtils.d(TAG, "应用商店 launchGalleryMarket() | 启动成功");
LogUtils.d(TAG, "launchGalleryMarket() | 启动成功");
} else {
ToastUtils.show("无法打开应用商店");
LogUtils.e(TAG, "应用商店 launchGalleryMarket() | 启动失败");
LogUtils.e(TAG, "launchGalleryMarket() | 启动失败");
}
}
@@ -670,8 +679,8 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 处理操作取消或失败
*/
private void handleOperationCancelOrFail() {
LogUtils.d(TAG, "handleOperationCancelOrFail() 操作取消或失败");
mBgSourceUtils.setCurrentSourceToPreview();
LogUtils.d(TAG, "业务逻辑 handleOperationCancelOrFail() | 操作取消或失败,恢复预览");
ToastUtils.show("操作取消或失败");
doubleRefreshPreview();
}
@@ -680,10 +689,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 处理拍照逻辑(权限通过后执行)
*/
void handleTakePhoto() {
LogUtils.d(TAG, "业务逻辑 handleTakePhoto() | 开始处理拍照");
LogUtils.d(TAG, "handleTakePhoto() 开始处理拍照");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "拍照失败 handleTakePhoto() | 预览Bean为空");
LogUtils.e(TAG, "handleTakePhoto() | 预览Bean为空");
ToastUtils.show("拍照文件创建失败");
return;
}
@@ -691,7 +700,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
File takePhotoFile = new File(previewBean.getBackgroundFilePath());
if (!takePhotoFile.exists()) {
ToastUtils.show("拍照文件创建失败");
LogUtils.e(TAG, String.format("拍照失败 handleTakePhoto() | 文件不存在:%s", takePhotoFile.getAbsolutePath()));
LogUtils.e(TAG, String.format("handleTakePhoto() | 文件不存在:%s", takePhotoFile.getAbsolutePath()));
return;
}
@@ -703,11 +712,11 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
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) {
String errMsg = "拍照启动异常:" + e.getMessage();
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 回调数据
*/
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) {
case REQUEST_SELECT_PICTURE:
handleSelectPictureResult(data);
@@ -732,7 +741,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
handlePixelPickerResult();
break;
default:
LogUtils.d(TAG, String.format("回调忽略 handleActivityResult() | 未知requestCode%d", requestCode));
LogUtils.d(TAG, String.format("handleActivityResult() | 未知requestCode%d", requestCode));
break;
}
}
@@ -742,10 +751,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param data 回调数据
*/
private void handleTakePhotoResult(Intent data) {
LogUtils.d(TAG, "业务逻辑 handleTakePhotoResult() | 处理拍照结果");
LogUtils.d(TAG, "handleTakePhotoResult() 处理拍照结果");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "拍照结果处理 handleTakePhotoResult() | 预览Bean为空");
LogUtils.e(TAG, "handleTakePhotoResult() | 预览Bean为空");
return;
}
@@ -755,7 +764,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
doubleRefreshPreview();
startImageCrop(false);
LogUtils.d(TAG, "拍照完成 handleTakePhotoResult() | 已启动裁剪");
LogUtils.d(TAG, "handleTakePhotoResult() | 已启动裁剪");
}
/**
@@ -763,30 +772,30 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param data 回调数据
*/
private void handleSelectPictureResult(Intent data) {
LogUtils.d(TAG, "业务逻辑 handleSelectPictureResult() | 处理选图结果");
LogUtils.d(TAG, "handleSelectPictureResult() 处理选图结果");
Uri selectedImage = data.getData();
if (selectedImage == null) {
ToastUtils.show("图片Uri为空");
LogUtils.e(TAG, "选图结果 handleSelectPictureResult() | Uri为空");
LogUtils.e(TAG, "handleSelectPictureResult() | Uri为空");
return;
}
LogUtils.d(TAG, String.format("选图回调 handleSelectPictureResult() | 系统返回Uri : %s", selectedImage.toString()));
LogUtils.d(TAG, String.format("handleSelectPictureResult() | 系统返回Uri : %s", selectedImage.toString()));
// 申请持久化权限API33+
if (Build.VERSION.SDK_INT >= SDK_VERSION_TIRAMISU) {
getContentResolver().takePersistableUriPermission(
selectedImage,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
LogUtils.d(TAG, "选图权限 handleSelectPictureResult() | 已添加持久化权限");
LogUtils.d(TAG, "handleSelectPictureResult() | 已添加持久化权限");
}
// 同步文件并启动裁剪
if (putUriFileToPreviewSource(selectedImage)) {
LogUtils.d(TAG, "选图同步 handleSelectPictureResult() | 路径绑定完成");
LogUtils.d(TAG, "handleSelectPictureResult() | 路径绑定完成");
startImageCrop(false);
} else {
ToastUtils.show("图片同步失败");
LogUtils.e(TAG, "选图同步 handleSelectPictureResult() | 文件复制失败");
LogUtils.e(TAG, "handleSelectPictureResult() | 文件复制失败");
}
}
@@ -796,9 +805,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 同步成功返回true否则false
*/
private boolean putUriFileToPreviewSource(Uri srcUriFile) {
LogUtils.d(TAG, String.format("putUriFileToPreviewSource() | 源Uri%s", srcUriFile.toString()));
String filePath = UriUtils.getFilePathFromUri(this, srcUriFile);
if (TextUtils.isEmpty(filePath)) {
LogUtils.e(TAG, "选图同步 putUriFileToPreviewSource() | Uri解析路径为空");
LogUtils.e(TAG, "putUriFileToPreviewSource() | Uri解析路径为空");
return false;
}
File srcFile = new File(filePath);
@@ -811,16 +821,16 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @return 同步成功返回true否则false
*/
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();
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
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)) {
LogUtils.d(TAG, "选图同步 putUriFileToPreviewSource() | 文件拷贝成功");
LogUtils.d(TAG, "putUriFileToPreviewSource() | 文件拷贝成功");
return true;
}
LogUtils.d(TAG, "选图同步 putUriFileToPreviewSource() | 文件无法拷贝");
LogUtils.d(TAG, "putUriFileToPreviewSource() | 文件无法拷贝");
return false;
}
@@ -829,10 +839,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param data 回调数据
*/
private void handleCropImageResult(Intent data) {
LogUtils.d(TAG, "业务逻辑 handleCropImageResult() | 处理裁剪结果");
LogUtils.d(TAG, "handleCropImageResult() 处理裁剪结果");
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "裁剪结果处理 handleCropImageResult() | 预览Bean为空");
LogUtils.e(TAG, "handleCropImageResult() | 预览Bean为空");
handleOperationCancelOrFail();
return;
}
@@ -856,8 +866,8 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param fileSize 文件大小
*/
private void handleCropSuccess(BackgroundBean previewBean, long fileSize) {
LogUtils.d(TAG, String.format("handleCropSuccess() | 裁剪成功,文件大小:%d", fileSize));
isPreviewBackgroundChanged = true;
LogUtils.d(TAG, String.format("裁剪结果 handleCropSuccess() | 裁剪成功,文件大小:%d", fileSize));
previewBean.setIsUseBackgroundFile(true);
previewBean.setIsUseBackgroundScaledCompressFile(true);
mBgSourceUtils.saveSettings();
@@ -871,15 +881,15 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param fileSize 文件大小
*/
private void handleCropFailure(boolean isFileExist, boolean isFileReadable, long fileSize) {
LogUtils.e(TAG, String.format("handleCropFailure() | 裁剪失败,文件状态:存在=%b可读=%b大小=%d", isFileExist, isFileReadable, fileSize));
handleOperationCancelOrFail();
LogUtils.e(TAG, String.format("裁剪结果 handleCropFailure() | 裁剪失败,文件状态:存在=%b可读=%b大小=%d", isFileExist, isFileReadable, fileSize));
}
/**
* 处理像素拾取结果
*/
private void handlePixelPickerResult() {
LogUtils.d(TAG, "业务逻辑 handlePixelPickerResult() | 处理像素拾取结果");
LogUtils.d(TAG, "handlePixelPickerResult() 处理像素拾取结果");
doubleRefreshPreview();
isPreviewBackgroundChanged = true;
}
@@ -889,11 +899,12 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param grantResults 权限结果数组
*/
private void handleCameraPermissionResult(int[] grantResults) {
LogUtils.d(TAG, "handleCameraPermissionResult() 处理相机权限结果");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
LogUtils.d(TAG, "权限申请 handleCameraPermissionResult() | 相机权限授予成功");
LogUtils.d(TAG, "handleCameraPermissionResult() | 相机权限授予成功");
handleTakePhoto();
} else {
LogUtils.d(TAG, "权限申请 handleCameraPermissionResult() | 相机权限授予失败");
LogUtils.d(TAG, "handleCameraPermissionResult() | 相机权限授予失败");
ToastUtils.show("相机权限被拒绝,无法拍照");
// 引导用户到设置页面开启权限(用户选择不再询问时)
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
@@ -906,18 +917,19 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* 启动应用设置页面
*/
private void launchAppSettings() {
LogUtils.d(TAG, "launchAppSettings() 启动应用设置页面");
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
ToastUtils.show("请在设置中开启相机权限");
LogUtils.d(TAG, "权限引导 launchAppSettings() | 启动应用设置页面");
}
/**
* 处理Finish确认对话框
*/
private void handleFinishConfirmation() {
LogUtils.d(TAG, "handleFinishConfirmation() 处理Finish确认");
if (isPreviewBackgroundChanged) {
YesNoAlertDialog.show(this, "背景更换问题", "是否确定背景图片设置?", new YesNoAlertDialog.OnDialogResultListener() {
@Override
@@ -944,9 +956,10 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
* @param isFreeCrop 是否自由裁剪
*/
private void startImageCrop(boolean isFreeCrop) {
LogUtils.d(TAG, String.format("startImageCrop() | 是否自由裁剪:%b", isFreeCrop));
BackgroundBean previewBean = mBgSourceUtils.getPreviewBackgroundBean();
if (previewBean == null) {
LogUtils.e(TAG, "裁剪启动 startImageCrop() | 预览Bean为空");
LogUtils.e(TAG, "startImageCrop() | 预览Bean为空");
ToastUtils.show("裁剪失败:无有效图片");
return;
}
@@ -958,7 +971,7 @@ public class BackgroundSettingsActivity extends WinBoLLActivity {
height,
isFreeCrop,
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 {
// ====================== 静态常量(首屏可见,统一管理) ======================
// ====================== 静态常量(首屏可见,统一管理) ======================
// 序列化版本号Serializable 必备,避免反序列化失败)
private static final long serialVersionUID = 1L;
// 日志标签(全局统一,替换 Log 为 LogUtils
// 日志标签(全局统一)
transient public static final String TAG = "AppConfigBean";
// 字段校验常量(统一阈值,避免硬编码)
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_HEIGHT = 500;// 默认相框高度px
// ====================== 成员变量(按功能分类:提醒配置→电量状态→检测配置→相框配置) ======================
// ====================== 成员变量(按功能分类:提醒配置→电量状态→检测配置→相框配置) ======================
// 耗电提醒配置
boolean isEnableUsageReminder = false; // 耗电提醒开关
int usageReminderValue = 45; // 耗电提醒阈值0-100
@@ -42,7 +42,6 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
int reminderIntervalTime = 5000; // 铃声提醒间隔ms
// 电量状态
boolean isCharging = false; // 是否充电
//int currentBatteryValue = INVALID_BATTERY; // 当前电池电量(统一命名,替代原 currentValue
// 电量检测配置
int batteryDetectInterval = 2000; // 电量检测间隔ms适配 RemindThread
// 相框配置
@@ -56,54 +55,14 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
setUsageReminderValue(10);
setEnableUsageReminder(false);
setReminderIntervalTime(5000);
setBatteryDetectInterval(1000); // 默认检测间隔1秒
//setCurrentBatteryValue(INVALID_BATTERY); // 初始化无效电量标识
setDefaultFrameWidth(DEFAULT_FRAME_WIDTH); // 初始化默认相框宽度
setDefaultFrameHeight(DEFAULT_FRAME_HEIGHT); // 初始化默认相框高度
LogUtils.d(TAG, "AppConfigBean() 初始化默认配置完成");
setBatteryDetectInterval(1000);
setDefaultFrameWidth(DEFAULT_FRAME_WIDTH);
setDefaultFrameHeight(DEFAULT_FRAME_HEIGHT);
LogUtils.d(TAG, "AppConfigBean() 构造器执行 | 默认配置初始化完成");
}
// ====================== 核心业务方法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) {
this.isCharging = isCharging;
LogUtils.d(TAG, String.format("setIsCharging() 执行 | 充电状态=%b", isCharging));
@@ -123,14 +82,9 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
return isEnableUsageReminder;
}
/**
* 设置耗电提醒阈值
* @param usageReminderValue 阈值0-100
*/
public void setUsageReminderValue(int usageReminderValue) {
this.usageReminderValue = Math.min(Math.max(usageReminderValue, BATTERY_MIN), BATTERY_MAX);
LogUtils.d(TAG, String.format("setUsageReminderValue() 执行 | 最终阈值=%d | 输入值=%d",
this.usageReminderValue, usageReminderValue));
LogUtils.d(TAG, String.format("setUsageReminderValue() 执行 | 最终阈值=%d | 输入值=%d", this.usageReminderValue, usageReminderValue));
}
public int getUsageReminderValue() {
@@ -147,29 +101,29 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
return isEnableChargeReminder;
}
/**
* 设置充电提醒阈值
* @param chargeReminderValue 阈值0-100
*/
public void setChargeReminderValue(int chargeReminderValue) {
this.chargeReminderValue = Math.min(Math.max(chargeReminderValue, BATTERY_MIN), BATTERY_MAX);
LogUtils.d(TAG, String.format("setChargeReminderValue() 执行 | 最终阈值=%d | 输入值=%d",
this.chargeReminderValue, chargeReminderValue));
LogUtils.d(TAG, String.format("setChargeReminderValue() 执行 | 最终阈值=%d | 输入值=%d", this.chargeReminderValue, chargeReminderValue));
}
public int getChargeReminderValue() {
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) {
this.batteryDetectInterval = Math.max(batteryDetectInterval, MIN_INTERVAL);
LogUtils.d(TAG, String.format("setBatteryDetectInterval() 执行 | 最终间隔=%dms | 输入值=%dms",
this.batteryDetectInterval, batteryDetectInterval));
LogUtils.d(TAG, String.format("setBatteryDetectInterval() 执行 | 最终间隔=%dms | 输入值=%dms", this.batteryDetectInterval, batteryDetectInterval));
}
public int getBatteryDetectInterval() {
@@ -177,28 +131,18 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
}
// --------------- 相框配置相关 ---------------
/**
* 设置默认相框宽度
* @param defaultFrameWidth 相框宽度px
*/
public void setDefaultFrameWidth(int defaultFrameWidth) {
this.defaultFrameWidth = defaultFrameWidth;
LogUtils.d(TAG, String.format("setDefaultFrameWidth() 执行 | 最终宽度=%dpx | 输入值=%dpx",
this.defaultFrameWidth, defaultFrameWidth));
LogUtils.d(TAG, String.format("setDefaultFrameWidth() 执行 | 最终宽度=%dpx | 输入值=%dpx", this.defaultFrameWidth, defaultFrameWidth));
}
public int getDefaultFrameWidth() {
return defaultFrameWidth;
}
/**
* 设置默认相框高度
* @param defaultFrameHeight 相框高度px
*/
public void setDefaultFrameHeight(int defaultFrameHeight) {
this.defaultFrameHeight = defaultFrameHeight;
LogUtils.d(TAG, String.format("setDefaultFrameHeight() 执行 | 最终高度=%dpx | 输入值=%dpx",
this.defaultFrameHeight, defaultFrameHeight));
LogUtils.d(TAG, String.format("setDefaultFrameHeight() 执行 | 最终高度=%dpx | 输入值=%dpx", this.defaultFrameHeight, defaultFrameHeight));
}
public int getDefaultFrameHeight() {
@@ -214,6 +158,8 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
@Override
public void writeThisToJsonWriter(JsonWriter jsonWriter) throws IOException {
super.writeThisToJsonWriter(jsonWriter);
LogUtils.d(TAG, "writeThisToJsonWriter() 执行 | 开始JSON序列化");
// 原有字段序列化
jsonWriter.name("isEnableUsageReminder").value(isEnableUsageReminder());
jsonWriter.name("usageReminderValue").value(getUsageReminderValue());
@@ -221,21 +167,21 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
jsonWriter.name("chargeReminderValue").value(getChargeReminderValue());
jsonWriter.name("reminderIntervalTime").value(getReminderIntervalTime());
jsonWriter.name("isCharging").value(isCharging());
// 兼容旧字段 currentValue同步新字段 currentBatteryValue
// jsonWriter.name("currentBatteryValue").value(getCurrentBatteryValue());
// jsonWriter.name("currentValue").value(getCurrentBatteryValue());
// 新增字段序列化(检测配置)
jsonWriter.name("batteryDetectInterval").value(getBatteryDetectInterval());
// 新增字段序列化(相框配置)
jsonWriter.name("defaultFrameWidth").value(getDefaultFrameWidth());
jsonWriter.name("defaultFrameHeight").value(getDefaultFrameHeight());
LogUtils.d(TAG, "writeThisToJsonWriter() JSON序列化完成");
LogUtils.d(TAG, "writeThisToJsonWriter() 完成 | JSON序列化成功");
}
@Override
public BaseBean readBeanFromJsonReader(JsonReader jsonReader) throws IOException {
LogUtils.d(TAG, "readBeanFromJsonReader() 执行 | 开始JSON反序列化");
AppConfigBean bean = new AppConfigBean();
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
// 兼容拼写错误字段isEnableUsegeReminder → isEnableUsageReminder
@@ -257,32 +203,23 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
} else if (name.equals("isCharging")) {
bean.setIsCharging(jsonReader.nextBoolean());
LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%b", name, bean.isCharging()));
}
// 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")) {
} else if (name.equals("batteryDetectInterval")) {
bean.setBatteryDetectInterval(jsonReader.nextInt());
LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%d", name, bean.getBatteryDetectInterval()));
} else if (name.equals("defaultFrameWidth")) {
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")) {
bean.setDefaultFrameHeight(jsonReader.nextInt());
LogUtils.d(TAG, "readBeanFromJsonReader() 读取字段 | defaultFrameHeight=" + bean.getDefaultFrameHeight());
LogUtils.d(TAG, String.format("readBeanFromJsonReader() 读取字段 | %s=%d", name, bean.getDefaultFrameHeight()));
} else {
jsonReader.skipValue();
LogUtils.w(TAG, "readBeanFromJsonReader() 跳过未知字段 | " + name);
LogUtils.w(TAG, String.format("readBeanFromJsonReader() 跳过未知字段 | %s", name));
}
}
jsonReader.endObject();
LogUtils.d(TAG, "readBeanFromJsonReader() JSON反序列化");
LogUtils.d(TAG, "readBeanFromJsonReader() 完成 | JSON反序列化成");
return bean;
}
@@ -294,6 +231,7 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
@Override
public void writeToParcel(Parcel dest, int flags) {
LogUtils.d(TAG, "writeToParcel() 执行 | 开始Parcel序列化");
// 按成员变量顺序写入boolean 转 byte 存储
dest.writeByte((byte) (isEnableUsageReminder ? 1 : 0));
dest.writeInt(usageReminderValue);
@@ -301,17 +239,17 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
dest.writeInt(chargeReminderValue);
dest.writeInt(reminderIntervalTime);
dest.writeByte((byte) (isCharging ? 1 : 0));
//dest.writeInt(currentBatteryValue);
dest.writeInt(batteryDetectInterval);
dest.writeInt(defaultFrameWidth);
dest.writeInt(defaultFrameHeight);
LogUtils.d(TAG, "writeToParcel() Parcel序列化");
LogUtils.d(TAG, "writeToParcel() 完成 | Parcel序列化成");
}
// 反序列化 Creator必须 public static final 修饰Java7 适配)
public static final Parcelable.Creator<AppConfigBean> CREATOR = new Parcelable.Creator<AppConfigBean>() {
@Override
public AppConfigBean createFromParcel(Parcel source) {
LogUtils.d(TAG, "createFromParcel() 执行 | 开始Parcel反序列化");
AppConfigBean bean = new AppConfigBean();
// 按 writeToParcel 顺序读取
bean.isEnableUsageReminder = source.readByte() != 0;
@@ -320,11 +258,10 @@ public class AppConfigBean extends BaseBean implements Serializable, Parcelable
bean.chargeReminderValue = source.readInt();
bean.reminderIntervalTime = source.readInt();
bean.isCharging = source.readByte() != 0;
//bean.currentBatteryValue = source.readInt();
bean.batteryDetectInterval = source.readInt();
bean.defaultFrameWidth = source.readInt();
bean.defaultFrameHeight = source.readInt();
LogUtils.d(TAG, "createFromParcel() Parcel反序列化");
LogUtils.d(TAG, "createFromParcel() 完成 | Parcel反序列化成");
return bean;
}

View File

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

View File

@@ -24,7 +24,7 @@ import java.util.List;
* 电池提醒核心服务
* 功能:管理前台服务生命周期、控制提醒线程启停、处理配置更新
* 适配Java7 | API30 | 前台服务超时防护 | 电池优化忽略引导
* @Author ZhanGSKen<zhangsken@qq.com>
* @Author 豆包&ZhanGSKen<zhangsken@qq.com>
* @Describe 核心服务:实现电池监测、提醒控制与前台服务保活
*/
public class ControlCenterService extends Service {
@@ -62,35 +62,35 @@ public class ControlCenterService extends Service {
@Override
public void 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();
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
public int onStartCommand(Intent intent, int flags, int startId) {
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();
runCoreServiceLogic();
int returnFlag = (mServiceControlBean != null && mServiceControlBean.isEnableService())
? SERVICE_RETURN_STICKY
: 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;
}
@Override
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;
}
@Override
public void onDestroy() {
LogUtils.d(TAG, "onDestroy执行服务销毁流程启动");
LogUtils.d(TAG, "onDestroy() 执行:服务销毁流程启动");
super.onDestroy();
// 资源释放顺序:前台服务 → 线程 → 广播接收器 → Handler → 通知 → 引用(避免内存泄漏)
@@ -108,7 +108,7 @@ public class ControlCenterService extends Service {
isServiceRunning = false;
mIsDestroyed = true;
LogUtils.d(TAG, "onDestroy完成服务销毁完成");
LogUtils.d(TAG, "onDestroy() 完成:服务销毁完成");
}
// ====================== 核心业务逻辑(独立抽取,统一调用) ======================
@@ -117,11 +117,11 @@ public class ControlCenterService extends Service {
* 避免重复初始化,保证前台服务优先启动
*/
private synchronized void runCoreServiceLogic() {
LogUtils.d(TAG, "runCoreServiceLogic执行");
LogUtils.d(TAG, "runCoreServiceLogic() 执行");
loadLatestServiceControlConfig();
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) {
isServiceRunning = true;
@@ -130,14 +130,14 @@ public class ControlCenterService extends Service {
if (initForegroundNotificationImmediately()) {
loadDefaultConfig();
initServiceBusinessLogic();
LogUtils.d(TAG, "runCoreServiceLogic核心组件初始化成功");
LogUtils.d(TAG, "runCoreServiceLogic() | 核心组件初始化成功");
} else {
LogUtils.e(TAG, "runCoreServiceLogic前台通知初始化失败,终止业务");
LogUtils.e(TAG, "runCoreServiceLogic() | 前台通知初始化失败,终止业务");
stopForegroundService();
isServiceRunning = false;
}
} else {
LogUtils.d(TAG, "runCoreServiceLogic无需执行核心逻辑");
LogUtils.d(TAG, "runCoreServiceLogic() | 无需执行核心逻辑");
}
}
@@ -147,11 +147,11 @@ public class ControlCenterService extends Service {
* @return true=成功 false=失败
*/
private boolean initForegroundNotificationImmediately() {
LogUtils.d(TAG, "initForegroundNotificationImmediately执行");
LogUtils.d(TAG, "initForegroundNotificationImmediately() 执行");
try {
if (mNotificationManager == null) {
mNotificationManager = new NotificationManagerUtils(this);
LogUtils.d(TAG, "initForegroundNotificationImmediately通知工具类初始化完成");
LogUtils.d(TAG, "initForegroundNotificationImmediately() | 通知工具类初始化完成");
}
if (mForegroundNotifyMsg == null) {
@@ -159,15 +159,15 @@ public class ControlCenterService extends Service {
mForegroundNotifyMsg.setTitle("电池监测服务");
mForegroundNotifyMsg.setContent("后台运行中");
mForegroundNotifyMsg.setRemindMSG("service_running");
LogUtils.d(TAG, "initForegroundNotificationImmediately通知消息构建完成");
LogUtils.d(TAG, "initForegroundNotificationImmediately() | 通知消息构建完成");
}
mNotificationManager.startForegroundServiceNotify(this, mForegroundNotifyMsg);
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;
} catch (Exception e) {
LogUtils.e(TAG, "initForegroundNotificationImmediately通知初始化异常", e);
LogUtils.e(TAG, "initForegroundNotificationImmediately() | 通知初始化异常", e);
return false;
}
}
@@ -176,12 +176,12 @@ public class ControlCenterService extends Service {
* 停止前台服务并取消通知
*/
private void stopForegroundService() {
LogUtils.d(TAG, "stopForegroundService执行");
LogUtils.d(TAG, "stopForegroundService() 执行");
try {
stopForeground(true);
LogUtils.d(TAG, "stopForegroundService前台服务已停止,通知已取消");
LogUtils.d(TAG, "stopForegroundService() | 前台服务已停止,通知已取消");
} 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() {
LogUtils.d(TAG, "loadLatestServiceControlConfig执行");
LogUtils.d(TAG, "loadLatestServiceControlConfig() 执行");
ControlCenterServiceBean latestBean = ControlCenterServiceBean.loadBean(this, ControlCenterServiceBean.class);
if (latestBean != null) {
mServiceControlBean = latestBean;
LogUtils.d(TAG, String.format("loadLatestServiceControlConfig配置读取成功 | 启用=%b", mServiceControlBean.isEnableService()));
LogUtils.d(TAG, String.format("loadLatestServiceControlConfig() | 配置读取成功 | 启用=%b", mServiceControlBean.isEnableService()));
} else {
LogUtils.w(TAG, "loadLatestServiceControlConfig本地无配置,沿用内存配置");
LogUtils.w(TAG, "loadLatestServiceControlConfig() | 本地无配置,沿用内存配置");
}
}
@@ -204,7 +204,7 @@ public class ControlCenterService extends Service {
* 加载默认业务配置(首次启动兜底)
*/
private void loadDefaultConfig() {
LogUtils.d(TAG, "loadDefaultConfig执行");
LogUtils.d(TAG, "loadDefaultConfig() 执行");
if (mCurrentConfigBean == null) {
mCurrentConfigBean = new AppConfigBean();
mCurrentConfigBean.setEnableChargeReminder(true);
@@ -212,10 +212,10 @@ public class ControlCenterService extends Service {
mCurrentConfigBean.setEnableUsageReminder(true);
mCurrentConfigBean.setUsageReminderValue(DEFAULT_USAGE_REMINDER_VALUE);
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));
} else {
LogUtils.d(TAG, "loadDefaultConfig内存已有配置,无需加载");
LogUtils.d(TAG, "loadDefaultConfig() | 内存已有配置,无需加载");
}
}
@@ -224,21 +224,21 @@ public class ControlCenterService extends Service {
* 初始化Handler等核心业务组件
*/
private void initServiceBusinessLogic() {
LogUtils.d(TAG, "initServiceBusinessLogic执行");
LogUtils.d(TAG, "initServiceBusinessLogic() 执行");
// 初始化Handler
if (mServiceHandler == null) {
mServiceHandler = new ControlCenterServiceHandler(this);
LogUtils.d(TAG, "initServiceBusinessLogicHandler初始化完成");
LogUtils.d(TAG, "initServiceBusinessLogic() | Handler初始化完成");
} else {
LogUtils.d(TAG, "initServiceBusinessLogicHandler已存在");
LogUtils.d(TAG, "initServiceBusinessLogic() | Handler已存在");
}
// 初始化广播接收器
if (mControlCenterServiceReceiver == null) {
mControlCenterServiceReceiver = new ControlCenterServiceReceiver(this);
mControlCenterServiceReceiver.registerAction(this);
LogUtils.d(TAG, "initServiceBusinessLogic广播接收器初始化并注册完成");
LogUtils.d(TAG, "initServiceBusinessLogic() | 广播接收器初始化并注册完成");
} else {
LogUtils.d(TAG, "initServiceBusinessLogic广播接收器已存在");
LogUtils.d(TAG, "initServiceBusinessLogic() | 广播接收器已存在");
}
}
@@ -246,13 +246,13 @@ public class ControlCenterService extends Service {
* 释放广播接收器资源
*/
private void releaseBroadcastReceiver() {
LogUtils.d(TAG, "releaseBroadcastReceiver执行");
LogUtils.d(TAG, "releaseBroadcastReceiver() 执行");
if (mControlCenterServiceReceiver != null) {
mControlCenterServiceReceiver.release();
mControlCenterServiceReceiver = null;
LogUtils.d(TAG, "releaseBroadcastReceiver广播接收器已释放");
LogUtils.d(TAG, "releaseBroadcastReceiver() | 广播接收器已释放");
} else {
LogUtils.w(TAG, "releaseBroadcastReceiver广播接收器实例为空");
LogUtils.w(TAG, "releaseBroadcastReceiver() | 广播接收器实例为空");
}
}
@@ -260,13 +260,13 @@ public class ControlCenterService extends Service {
* 销毁Handler移除所有消息和回调防止内存泄漏
*/
private void destroyHandler() {
LogUtils.d(TAG, "destroyHandler执行");
LogUtils.d(TAG, "destroyHandler() 执行");
if (mServiceHandler != null) {
mServiceHandler.removeCallbacksAndMessages(null);
mServiceHandler = null;
LogUtils.d(TAG, "destroyHandlerHandler已销毁");
LogUtils.d(TAG, "destroyHandler() | Handler已销毁");
} else {
LogUtils.w(TAG, "destroyHandlerHandler实例为空");
LogUtils.w(TAG, "destroyHandler() | Handler实例为空");
}
}
@@ -274,13 +274,13 @@ public class ControlCenterService extends Service {
* 释放通知工具类资源
*/
private void releaseNotificationResource() {
LogUtils.d(TAG, "releaseNotificationResource执行");
LogUtils.d(TAG, "releaseNotificationResource() 执行");
if (mNotificationManager != null) {
mNotificationManager.release();
mNotificationManager = null;
LogUtils.d(TAG, "releaseNotificationResource通知资源已释放");
LogUtils.d(TAG, "releaseNotificationResource() | 通知资源已释放");
} else {
LogUtils.w(TAG, "releaseNotificationResource通知工具类实例为空");
LogUtils.w(TAG, "releaseNotificationResource() | 通知工具类实例为空");
}
}
@@ -288,10 +288,10 @@ public class ControlCenterService extends Service {
* 置空所有引用,防止内存泄漏
*/
private void clearAllReferences() {
LogUtils.d(TAG, "clearAllReferences执行");
LogUtils.d(TAG, "clearAllReferences() 执行");
mForegroundNotifyMsg = null;
mServiceControlBean = null;
LogUtils.d(TAG, "clearAllReferences引用清理完成");
LogUtils.d(TAG, "clearAllReferences() | 引用清理完成");
}
// ====================== 外部调用接口(静态方法,提供服务启停/配置更新入口) ======================
@@ -300,25 +300,25 @@ public class ControlCenterService extends Service {
* @param 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) {
LogUtils.e(TAG, "startControlCenterServiceContext为空启动失败");
LogUtils.e(TAG, "startControlCenterService() | Context为空启动失败");
return;
}
// 保存启用配置
ControlCenterServiceBean controlBean = new ControlCenterServiceBean(true);
ControlCenterServiceBean.saveBean(context, controlBean);
LogUtils.d(TAG, "startControlCenterService服务启用配置已保存");
LogUtils.d(TAG, "startControlCenterService() | 服务启用配置已保存");
// 启动服务区分API版本
Intent intent = new Intent(context, ControlCenterService.class);
if (Build.VERSION.SDK_INT >= API_LEVEL_26) {
context.startForegroundService(intent);
LogUtils.d(TAG, "startControlCenterService以前台服务方式启动API26+");
LogUtils.d(TAG, "startControlCenterService() | 以前台服务方式启动API26+");
} else {
context.startService(intent);
LogUtils.d(TAG, "startControlCenterService以普通服务方式启动API26-");
LogUtils.d(TAG, "startControlCenterService() | 以普通服务方式启动API26-");
}
}
@@ -327,21 +327,21 @@ public class ControlCenterService extends Service {
* @param 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) {
LogUtils.e(TAG, "stopControlCenterServiceContext为空停止失败");
LogUtils.e(TAG, "stopControlCenterService() | Context为空停止失败");
return;
}
// 保存停用配置
ControlCenterServiceBean controlBean = new ControlCenterServiceBean(false);
ControlCenterServiceBean.saveBean(context, controlBean);
LogUtils.d(TAG, "stopControlCenterService服务停用配置已保存");
LogUtils.d(TAG, "stopControlCenterService() | 服务停用配置已保存");
// 停止服务
Intent intent = new Intent(context, ControlCenterService.class);
context.stopService(intent);
LogUtils.d(TAG, "stopControlCenterService停止指令已发送");
LogUtils.d(TAG, "stopControlCenterService() | 停止指令已发送");
}
/**
@@ -349,16 +349,16 @@ public class ControlCenterService extends Service {
* @param 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) {
LogUtils.e(TAG, "sendAppConfigStatusUpdateMessage参数为空,更新失败");
LogUtils.e(TAG, "sendAppConfigStatusUpdateMessage() | 参数为空,更新失败");
return;
}
Intent intent = new Intent(ControlCenterServiceReceiver.ACTION_APPCONFIG_CHANGED);
intent.setPackage(context.getPackageName());
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 上下文
*/
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) {
LogUtils.w(TAG, "checkIgnoreBatteryOptimization无需检查Context为空或API<23");
LogUtils.w(TAG, "checkIgnoreBatteryOptimization() | 无需检查Context为空或API<23");
return;
}
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (powerManager == null) {
LogUtils.e(TAG, "checkIgnoreBatteryOptimizationPowerManager获取失败");
LogUtils.e(TAG, "checkIgnoreBatteryOptimization() | PowerManager获取失败");
return;
}
String packageName = context.getPackageName();
boolean isIgnored = powerManager.isIgnoringBatteryOptimizations(packageName);
LogUtils.d(TAG, String.format("checkIgnoreBatteryOptimization已忽略电池优化=%b", isIgnored));
LogUtils.d(TAG, String.format("checkIgnoreBatteryOptimization() | 已忽略电池优化=%b", isIgnored));
if (!isIgnored) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
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=未运行
*/
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) {
LogUtils.e(TAG, "isServiceRunning参数为空");
LogUtils.e(TAG, "isServiceRunning() | 参数为空");
return false;
}
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) {
LogUtils.e(TAG, "isServiceRunningActivityManager获取失败");
LogUtils.e(TAG, "isServiceRunning() | ActivityManager获取失败");
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 {
// API30- 通过服务列表判断
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) {
isRunning = isServiceStarted(context, serviceClass);
LogUtils.d(TAG, String.format("isServiceRunning兜底判断结果=%b", isRunning));
LogUtils.d(TAG, String.format("isServiceRunning() | 兜底判断结果=%b", isRunning));
}
return isRunning;
}
@@ -454,12 +454,12 @@ public class ControlCenterService extends Service {
* 兜底判断服务是否已启动(通过配置文件)
*/
private static boolean isServiceStarted(Context context, Class<?> serviceClass) {
LogUtils.d(TAG, "isServiceStarted执行");
LogUtils.d(TAG, "isServiceStarted() 执行");
try {
ControlCenterServiceBean controlBean = ControlCenterServiceBean.loadBean(context, ControlCenterServiceBean.class);
return controlBean != null && controlBean.isEnableService();
} catch (Exception e) {
LogUtils.e(TAG, "isServiceStarted兜底判断异常", e);
LogUtils.e(TAG, "isServiceStarted() | 兜底判断异常", e);
return false;
}
}
@@ -472,13 +472,13 @@ public class ControlCenterService extends Service {
public void notifyAppConfigUpdate(AppConfigBean latestConfig) {
int chargeThreshold = latestConfig != null ? latestConfig.getChargeReminderValue() : -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) {
mCurrentConfigBean = latestConfig;
RemindThread.startRemindThreadWithAppConfig(this, mServiceHandler, latestConfig);
LogUtils.d(TAG, "notifyAppConfigUpdate配置已同步到提醒线程");
LogUtils.d(TAG, "notifyAppConfigUpdate() | 配置已同步到提醒线程");
} 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 int chargeReminderValue;
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 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.mwrControlCenterServiceHandler = new WeakReference<>(handler);
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: 入参非法
*/
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) {
@@ -108,55 +108,12 @@ public class RemindThread extends Thread {
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() {
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()) {
LogUtils.w(TAG, "停止失败:线程列表为空");
return;
@@ -194,7 +151,7 @@ public class RemindThread extends Thread {
// ====================== 线程核心运行逻辑 ======================
@Override
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) {
@@ -244,7 +201,7 @@ public class RemindThread extends Thread {
// 循环退出,清理状态
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 充电状态
*/
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) {
LogUtils.d(TAG, String.format("消息发送跳过:线程已退出或提醒关闭 | threadId=%d", getId()));
@@ -292,7 +249,7 @@ public class RemindThread extends Thread {
* @param millis 休眠时长(ms)
*/
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 {
Thread.sleep(millis);
} catch (InterruptedException e) {
@@ -305,7 +262,7 @@ public class RemindThread extends Thread {
* 重置线程初始状态(构造器专用)
*/
private void resetThreadStateInternal() {
LogUtils.d(TAG, String.format("resetThreadStateInternal调用 | threadId=%d", getId()));
LogUtils.d(TAG, String.format("resetThreadStateInternal() 调用 | threadId=%d", getId()));
// 状态标记初始化
isExist = false;
isReminding = false;
@@ -323,7 +280,7 @@ public class RemindThread extends Thread {
* 清理线程运行状态(循环退出时调用)
*/
private void cleanThreadStateInternal() {
LogUtils.d(TAG, String.format("cleanThreadStateInternal调用 | threadId=%d", getId()));
LogUtils.d(TAG, String.format("cleanThreadStateInternal() 调用 | threadId=%d", getId()));
isReminding = false;
isExist = true;
sQuantityOfElectricity = INVALID_BATTERY_VALUE;
@@ -340,7 +297,7 @@ public class RemindThread extends Thread {
* @param config 应用配置Bean
*/
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) {
LogUtils.e(TAG, String.format("配置同步失败配置Bean为空 | threadId=%d", getId()));
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);
sleepTime = Math.max(config.getBatteryDetectInterval(), MIN_SLEEP_TIME);
// sQuantityOfElectricity = (config.getCurrentBatteryValue() >= BATTERY_LEVEL_MIN && config.getCurrentBatteryValue() <= BATTERY_LEVEL_MAX)
// ? config.getCurrentBatteryValue() : INVALID_BATTERY_VALUE;
// ? config.getCurrentBatteryValue() : INVALID_BATTERY_VALUE;
isCharging = config.isCharging();
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() {
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;
}
// ====================== Getter/Setter按需开放 ======================
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;
}
@@ -385,16 +342,16 @@ public class RemindThread extends Thread {
@Override
public String toString() {
return "RemindThread{" +
"threadId=" + getId() +
", threadName='" + getName() + '\'' +
", isRunning=" + isRunning() +
", isReminding=" + isReminding +
", chargeThreshold=" + chargeReminderValue +
", usageThreshold=" + usageReminderValue +
", currentBattery=" + sQuantityOfElectricity +
", isCharging=" + isCharging +
", sleepTime=" + sleepTime + "ms" +
'}';
"threadId=" + getId() +
", threadName='" + getName() + '\'' +
", isRunning=" + isRunning() +
", isReminding=" + isReminding +
", chargeThreshold=" + chargeReminderValue +
", usageThreshold=" + usageReminderValue +
", currentBattery=" + sQuantityOfElectricity +
", isCharging=" + isCharging +
", sleepTime=" + sleepTime + "ms" +
'}';
}
}

View File

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