30 Commits

Author SHA1 Message Date
lxh2875931338 b390311827 版本号调整 2026-07-19 20:14:32 +08:00
lxh2875931338 f3a414b097 readme更新 2026-07-19 20:05:47 +08:00
lxh2875931338 cf7cec6be3 readme更新 2026-07-19 19:55:32 +08:00
lxh2875931338 6808f099f4 去除魅族22的机型匹配信息(机型没有响应的log文件) 2026-07-19 19:50:20 +08:00
lxh2875931338 38624a8d50 修改机型名称(匹配其他机型的非全大写) 2026-07-19 19:48:55 +08:00
lxh2875931338 b34af6af66 20inf识别字更新 2026-07-19 19:48:07 +08:00
lxh2875931338 ae9bb2dfa1 1.5.2版本发布及部分readme更新 2026-07-14 23:03:35 +08:00
lxh2875931338 bb9a3dc3f5 浪漫雅圆(FlymeFont.ttf)脱色处理并添加代码适配 2026-07-14 22:58:37 +08:00
lxh2875931338 adc49fa1a5 更新一个字体 2026-07-14 21:51:44 +08:00
lxh2875931338 804b992ee4 readme修改,涉及机型匹配相关信息调整 2026-07-11 21:41:59 +08:00
lxh2875931338 4857aa5d1b 1.5.0版本readme更新 2026-07-08 23:47:51 +08:00
lxh2875931338 9066b0f703 优化部分页面下UI显示问题 2026-07-08 23:43:23 +08:00
lxh2875931338 23d5c3b341 针对1.4.7的擦屁股操作:优化status=full的判定逻辑 2026-07-08 23:32:50 +08:00
lxh2875931338 6af7ad6cd2 单位对应数值优化 2026-07-08 23:19:27 +08:00
lxh2875931338 afc83c16c3 充电逻辑修改初步定档 2026-07-08 23:10:16 +08:00
lxh2875931338 c5e5280de7 log信息来源补充 2026-07-07 23:47:54 +08:00
lxh2875931338 28824501dc 相应的版本更新 2026-07-06 18:57:42 +08:00
lxh2875931338 76bff59afc 部分自动优化 2026-07-06 18:29:49 +08:00
lxh2875931338 26aa931e06 更新一下readme 2026-07-05 23:55:56 +08:00
lxh2875931338 0fa47dcb61 新计算逻辑继续补充中 2026-07-05 23:36:58 +08:00
lxh2875931338 20e29f3043 尝试针对魅族20系设计新的计算逻辑 2026-07-05 23:23:30 +08:00
lxh2875931338 14416be48e 更新readme进度 2026-07-05 01:30:14 +08:00
lxh2875931338 0450bc9540 背景色优化 2026-07-05 01:25:49 +08:00
lxh2875931338 f8ffb32bb0 Merge branch 'main' of http://192.168.3.16:3800/lxh2875931338/MEIZU-Battery-Healthy 2026-07-05 01:05:02 +08:00
lxh2875931338 8e93cbeed2 尝试解决二次启动时文件读取问题 2026-07-05 01:01:47 +08:00
lxh2875931338 7ba2e612f1 尝试解决二次启动时文件读取问题 2026-07-05 00:59:41 +08:00
lxh2875931338 c7ee563e84 末端测试中 2026-07-05 00:43:16 +08:00
lxh2875931338 45c69c8ec4 SAF测试阶段,验证中 2026-07-05 00:32:28 +08:00
lxh2875931338 dff0f6fb6b SAF实现修改 2026-07-05 00:02:23 +08:00
lxh2875931338 745fdaf7e7 部分bug修复 2026-07-04 22:49:48 +08:00
30 changed files with 2309 additions and 1481 deletions
+2 -1
View File
@@ -1,3 +1,4 @@
{
"cmake.ignoreCMakeListsMissing": true
"cmake.ignoreCMakeListsMissing": true,
"gitlens.codeLens.enabled": false
}
+16 -7
View File
@@ -24,18 +24,26 @@
| 版本 | 主题 | 状态 |
| :--- | :--- | :--- |
| 1.3.0 | 时间窗口 + real_type 优先级 | ✅ 已发布 |
| 1.4.0 | SAF 权限改造 | 📋 规划中 |
| 1.5.0 | 功率计算优化 | 📋 规划中 |
| 2.0.0 | 数据看板扩展(月/季/年趋势) | 📋 远景 |
| 1.5.0 | 功率计算优化 | ✅ 已发布 |
| 1.5.2 | 部分场景字体替换 | ✅ 已发布 |
| 1.6.0 | 更新日志独立页面 | 📋近期开发 |
| 1.7.0 | 适配夜间模式 | 📋近期开发 |
| 2.0.0 | 数据看板扩展等系列更新 | 📋 远景 |
| 3.0.0 | 搭配PC上位机记录充电信息等 | 📋 远景 |
---
## 环境要求
- Flutter SDK: ^3.9.2
- Android: 8.0+ (API 26+)
- 仅支持魅族手机(15 系列 ~ 25 系列)
---
## 机型匹配情况
目前据群友反馈已知:
- 魅族22无mbattery_charger目录生成,无法实时计算相应百分比,因此已在最近版本去除相关匹配信息
- 魅族18在后续的版本中关闭了mbattery_log生成,疑似无效,老版本可能支持
- 最完美的支持版本至少可覆盖魅族20/21系机型(20inf已确认,机型匹配ID已更新)
---
@@ -49,4 +57,5 @@ flutter pub get
flutter run
# Release APK
flutter build apk --release
flutter build apk --release --target-platform android-arm64
```
+21 -24
View File
@@ -6,7 +6,7 @@ plugins {
android {
namespace = "com.lxh.battery_health"
compileSdk = flutter.compileSdkVersion
compileSdk = 34
ndkVersion = flutter.ndkVersion
compileOptions {
@@ -21,38 +21,39 @@ android {
defaultConfig {
applicationId = "com.lxh.battery_health"
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
targetSdk = 34
versionCode = flutter.versionCode
versionName = flutter.versionName
multiDexEnabled = true
}
signingConfigs {
create("release") {
// 这里配置你正式发布的签名
// 如果还没有正式签名,debug 可以用 debug 签名替代
keyAlias = "your_key_alias"
keyPassword = "your_key_password"
storeFile = file("your_keystore.jks")
storePassword = "your_store_password"
// 如果没有正式签名,可以用 debug 签名代替(测试用)
// 正式发布时请替换为自己的密钥
getByName("debug") {
// debug 签名已经存在,无需额外配置
}
create("release") {
// 如果有正式签名,在这里配置
// keyAlias = "..."
// keyPassword = "..."
// storeFile = file("...")
// storePassword = "..."
}
}
signingConfigs {
// 如果没有正式签名,可以暂时用 debug 签名
// 正式发布时再替换
}
buildTypes {
debug {
// 🟢 关键:debug 版本包名加 .dev 后缀
applicationIdSuffix = ".dev"
signingConfig = signingConfigs.getByName("debug")
isDebuggable = true
isMinifyEnabled = false
isShrinkResources = false
}
release {
applicationIdSuffix = "" // 保持原包名
// 🟢 如果还没有正式签名,先用 debug 签名替代
signingConfig = signingConfigs.getByName("debug")
// release 版本不加后缀,保持原包名
signingConfig = signingConfigs.getByName("debug") // 若没有正式签名,先用 debug 签名
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(
@@ -61,16 +62,12 @@ android {
)
}
}
// 如果有 productFlavors,可以在这里配置
// 如果没有,忽略即可
}
}
flutter {
source = "../.."
}
dependencies {
// 如果项目中有其他依赖,添加在这里
// 注意:sqflite、permission_handler 等 Flutter 插件会自动包含
// 无需额外添加 Activity KTX,因为已改用 startActivityForResult
}
+73
View File
@@ -0,0 +1,73 @@
plugins {
id("com.android.application")
id("kotlin-android")
id("dev.flutter.flutter-gradle-plugin")
}
android {
namespace = "com.lxh.battery_health"
compileSdk = 34
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
defaultConfig {
applicationId = "com.lxh.battery_health"
minSdk = flutter.minSdkVersion
targetSdk = 34
versionCode = flutter.versionCode
versionName = flutter.versionName
multiDexEnabled = true
}
signingConfigs {
// 如果没有正式签名,可以用 debug 签名代替(测试用)
// 正式发布时请替换为自己的密钥
getByName("debug") {
// debug 签名已经存在,无需额外配置
}
create("release") {
// 如果有正式签名,在这里配置
// keyAlias = "..."
// keyPassword = "..."
// storeFile = file("...")
// storePassword = "..."
}
}
buildTypes {
debug {
// 🟢 关键:debug 版本包名加 .dev 后缀
applicationIdSuffix = ".dev"
signingConfig = signingConfigs.getByName("debug")
isDebuggable = true
isMinifyEnabled = false
isShrinkResources = false
}
release {
// release 版本不加后缀,保持原包名
signingConfig = signingConfigs.getByName("debug") // 若没有正式签名,先用 debug 签名
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
}
flutter {
source = "../.."
}
dependencies {
// 无需额外添加 Activity KTX,因为已改用 startActivityForResult
}
+16 -14
View File
@@ -1,20 +1,22 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />-->
<application
android:label="@string/app_name"
android:name="${applicationName}"
android:icon="@drawable/logo"
android:requestLegacyExternalStorage="true">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<application
android:label="@string/app_name"
android:name="${applicationName}"
android:icon="@drawable/logo"
android:requestLegacyExternalStorage="true"
android:theme="@style/LaunchTheme"> <!-- 全局先用 LaunchTheme -->
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/AppTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
@@ -0,0 +1,50 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />-->
<application
android:label="@string/app_name"
android:name="${applicationName}"
android:icon="@drawable/logo"
android:requestLegacyExternalStorage="true"
android:theme="@style/LaunchTheme"> <!-- 全局先用 LaunchTheme -->
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/AppTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>
@@ -1,96 +0,0 @@
package com.lxh.battery_health
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Bundle
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val CHANNEL = "com.lxh.battery_health/charge"
private val EVENT_CHANNEL = "com.lxh.battery_health/charge_events"
private var eventSink: EventChannel.EventSink? = null
private val chargeReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent ?: return
when (intent.action) {
Intent.ACTION_POWER_CONNECTED -> sendChargeState(true)
Intent.ACTION_POWER_DISCONNECTED -> sendChargeState(false)
}
}
}
private fun sendChargeState(isCharging: Boolean) {
val chargeType = if (isCharging) {
val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val plug = batteryIntent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1
android.util.Log.d("BatteryHealth", "plug value: $plug, isCharging: $isCharging")
when (plug) {
BatteryManager.BATTERY_PLUGGED_AC -> "AC"
BatteryManager.BATTERY_PLUGGED_USB -> "USB"
BatteryManager.BATTERY_PLUGGED_WIRELESS -> "WIRELESS" // 🟢 关键修复
else -> "UNKNOWN"
}
} else {
"NONE"
}
eventSink?.success(mapOf("isCharging" to isCharging, "chargeType" to chargeType))
}
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "getChargeState") {
val isCharging = getBatteryStatus()
val chargeType = if (isCharging) {
val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val plug = batteryIntent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1
when (plug) {
BatteryManager.BATTERY_PLUGGED_AC -> "AC"
BatteryManager.BATTERY_PLUGGED_USB -> "USB"
BatteryManager.BATTERY_PLUGGED_WIRELESS -> "WIRELESS" // 🟢 关键修复
else -> "UNKNOWN"
}
} else {
"NONE"
}
result.success(mapOf("isCharging" to isCharging, "chargeType" to chargeType))
} else {
result.notImplemented()
}
}
EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL).setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events
val filter = IntentFilter().apply {
addAction(Intent.ACTION_POWER_CONNECTED)
addAction(Intent.ACTION_POWER_DISCONNECTED)
}
registerReceiver(chargeReceiver, filter)
}
override fun onCancel(arguments: Any?) {
eventSink = null
unregisterReceiver(chargeReceiver)
}
}
)
}
private fun getBatteryStatus(): Boolean {
val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
return status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL
}
}
@@ -0,0 +1,305 @@
package com.lxh.battery_health
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.net.Uri
import android.os.BatteryManager
import android.os.Build
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import androidx.activity.ComponentActivity
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import java.io.BufferedReader
import java.io.InputStreamReader
class MainActivity : FlutterActivity() {
private val CHARGE_CHANNEL = "com.lxh.battery_health/charge"
private val EVENT_CHANNEL = "com.lxh.battery_health/charge_events"
private var eventSink: EventChannel.EventSink? = null
private val SAF_CHANNEL = "com.lxh.battery_health/saf"
private var safResult: MethodChannel.Result? = null
private var safUri: Uri? = null
private val FOLDER_PICKER_REQUEST = 1001
private val PREF_NAME = "battery_health_prefs"
private val KEY_SAF_URI = "saf_uri"
private val chargeReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent ?: return
when (intent.action) {
Intent.ACTION_POWER_CONNECTED -> sendChargeState(true)
Intent.ACTION_POWER_DISCONNECTED -> sendChargeState(false)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
android.util.Log.d("BatteryHealth", "onCreate 开始")
try {
val prefs: SharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val uriString = prefs.getString(KEY_SAF_URI, null)
android.util.Log.d("BatteryHealth", "SharedPreferences URI: $uriString")
if (uriString != null) {
safUri = Uri.parse(uriString)
android.util.Log.d("BatteryHealth", "恢复 SAF URI 成功: $safUri")
}
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "恢复 URI 异常: ${e.message}")
}
android.util.Log.d("BatteryHealth", "onCreate 结束,safUri = $safUri")
}
private fun saveUri(uri: Uri) {
try {
val prefs: SharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
prefs.edit().putString(KEY_SAF_URI, uri.toString()).apply()
android.util.Log.d("BatteryHealth", "保存 SAF URI: $uri")
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "保存 URI 失败: ${e.message}")
}
}
private fun restoreUri(uriString: String) {
try {
safUri = Uri.parse(uriString)
android.util.Log.d("BatteryHealth", "通过 MethodChannel 恢复 URI: $safUri")
// 同时保存到 SharedPreferences
val prefs: SharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
prefs.edit().putString(KEY_SAF_URI, uriString).apply()
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "restoreUri 失败: ${e.message}")
}
}
private fun sendChargeState(isCharging: Boolean) {
val chargeType = if (isCharging) {
val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val plug = batteryIntent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1
android.util.Log.d("BatteryHealth", "plug value: $plug, isCharging: $isCharging")
when (plug) {
BatteryManager.BATTERY_PLUGGED_AC -> "AC"
BatteryManager.BATTERY_PLUGGED_USB -> "USB"
BatteryManager.BATTERY_PLUGGED_WIRELESS -> "WIRELESS"
else -> "UNKNOWN"
}
} else {
"NONE"
}
eventSink?.success(mapOf("isCharging" to isCharging, "chargeType" to chargeType))
}
private fun getBatteryStatus(): Boolean {
val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
return status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL
}
private fun openFolderPicker() {
try {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
val downloadsUri = DocumentsContract.buildDocumentUri(
"com.android.externalstorage.documents",
"primary:Downloads"
)
putExtra(DocumentsContract.EXTRA_INITIAL_URI, downloadsUri)
} catch (e: Exception) {
// 忽略
}
}
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
startActivityForResult(intent, FOLDER_PICKER_REQUEST)
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "打开文件夹选择器失败: ${e.message}")
safResult?.error("SELECT_FOLDER_FAILED", e.message, null)
safResult = null
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == FOLDER_PICKER_REQUEST && resultCode == ComponentActivity.RESULT_OK) {
val uri = data?.data
if (uri != null) {
try {
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
contentResolver.takePersistableUriPermission(uri, takeFlags)
safUri = uri
saveUri(uri)
android.util.Log.d("BatteryHealth", "SAF 授权成功 URI: $uri")
safResult?.success(uri.toString())
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "SAF 授权失败: ${e.message}")
safResult?.error("SAF_FAILED", e.message, null)
}
} else {
safResult?.success(null)
}
safResult = null
}
}
private fun getTreeDocId(): String? {
return safUri?.let { DocumentsContract.getTreeDocumentId(it) }
}
private fun listFiles(): List<String> {
android.util.Log.d("BatteryHealth", "listFiles 被调用,safUri = $safUri")
val result = mutableListOf<String>()
val docId = getTreeDocId()
if (docId == null || docId.isEmpty()) {
android.util.Log.e("BatteryHealth", "docId 为空")
return result
}
try {
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(safUri!!, docId)
contentResolver.query(childrenUri, null, null, null, null)?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
while (cursor.moveToNext()) {
val name = cursor.getString(nameIndex)
if (name != null) {
result.add(name)
}
}
}
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "列出文件失败: ${e.message}", e)
}
return result
}
private fun getFileUri(fileName: String): Uri? {
val docId = getTreeDocId() ?: return null
try {
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(safUri!!, docId)
contentResolver.query(childrenUri, null, null, null, null)?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val idIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
while (cursor.moveToNext()) {
val name = cursor.getString(nameIndex)
if (name == fileName) {
val fileDocId = cursor.getString(idIndex)
return DocumentsContract.buildDocumentUriUsingTree(safUri!!, fileDocId)
}
}
}
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "获取文件URI失败: ${e.message}")
}
return null
}
private fun readFile(uri: Uri): String? {
return try {
contentResolver.openInputStream(uri)?.use { inputStream ->
BufferedReader(InputStreamReader(inputStream)).use { reader ->
reader.readText()
}
}
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "读取文件失败: ${e.message}")
null
}
}
private fun readLogFile(fileName: String): String? {
val fileUri = getFileUri(fileName)
return fileUri?.let { readFile(it) }
}
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHARGE_CHANNEL)
.setMethodCallHandler { call, result ->
if (call.method == "getChargeState") {
val isCharging = getBatteryStatus()
val chargeType = if (isCharging) {
val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val plug = batteryIntent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1
when (plug) {
BatteryManager.BATTERY_PLUGGED_AC -> "AC"
BatteryManager.BATTERY_PLUGGED_USB -> "USB"
BatteryManager.BATTERY_PLUGGED_WIRELESS -> "WIRELESS"
else -> "UNKNOWN"
}
} else {
"NONE"
}
result.success(mapOf("isCharging" to isCharging, "chargeType" to chargeType))
} else {
result.notImplemented()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, SAF_CHANNEL)
.setMethodCallHandler { call, result ->
when (call.method) {
"restoreUri" -> {
val uriString = call.argument<String>("uri")
if (uriString != null) {
restoreUri(uriString)
result.success(true)
} else {
result.error("INVALID_ARGUMENT", "uri is required", null)
}
}
"selectFolder" -> {
safResult = result
openFolderPicker()
}
"readLogFile" -> {
val fileName = call.argument<String>("fileName")
if (fileName != null) {
val content = readLogFile(fileName)
result.success(content)
} else {
result.error("INVALID_ARGUMENT", "fileName is required", null)
}
}
"listFiles" -> {
val files = listFiles()
result.success(files)
}
"getUri" -> {
result.success(safUri?.toString())
}
else -> result.notImplemented()
}
}
EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL)
.setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events
val filter = IntentFilter().apply {
addAction(Intent.ACTION_POWER_CONNECTED)
addAction(Intent.ACTION_POWER_DISCONNECTED)
}
registerReceiver(chargeReceiver, filter)
}
override fun onCancel(arguments: Any?) {
eventSink = null
unregisterReceiver(chargeReceiver)
}
}
)
}
}
+14 -12
View File
@@ -1,18 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
<!-- 应用主主题(浅色) -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:statusBarColor">@android:color/white</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowTranslucentStatus">false</item>
<item name="android:windowTranslucentNavigation">false</item>
<item name="android:navigationBarColor">@android:color/white</item>
<item name="android:windowLightNavigationBar">true</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
<!-- 启动主题(用于闪屏,保持透明/深色以避免白屏闪烁) -->
<style name="LaunchTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- 启动时可保持透明 -->
<item name="android:windowBackground">@android:color/white</item>
<item name="android:statusBarColor">@android:color/white</item>
<item name="android:windowLightStatusBar">true</item>
</style>
</resources>
+4
View File
@@ -1,3 +1,7 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
android.enableJetifier=true
# This builtInKotlin flag was added automatically by Flutter migrator
android.builtInKotlin=false
# This newDsl flag was added automatically by Flutter migrator
android.newDsl=false
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
description: This file stores settings for Dart & Flutter DevTools.
documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states
extensions:
+54
View File
@@ -0,0 +1,54 @@
/// 容量提取工具
/// 支持两种日志格式:
/// 1. learned_cap21 系列):单位 µAh,除以 1000 得到 mAh
/// 🟢 优先级最高,不受 status 限制(BMS 可能在任意状态行更新此值)
/// 2. remaining_cap20 系列):仅从 status=Full 行提取,单位智能识别(µAh/mAh)
class CapacityExtractor {
static int? extractCapacity(List<String> lines) {
final validLines = lines.where((line) => line.contains('tbat=')).toList();
if (validLines.isEmpty) return null;
// ============================================================
// 🟢 第一优先级:learned_cap21 系列专属)
// 不限制 status,在所有有效行中搜索,取最新的一条
// ============================================================
final learnedReg = RegExp(r'learned_cap=(\d+)');
for (String line in validLines.reversed) {
final match = learnedReg.firstMatch(line);
if (match != null) {
final value = int.parse(match.group(1)!);
// learned_cap 单位固定为 µAh,直接除以 1000 转 mAh
return value ~/ 1000;
}
}
// ============================================================
// 🟢 第二优先级:remaining_cap20 系列回退方案)
// 仅从 status=Full 行提取(充满状态下 BMS 最准确)
// ============================================================
final fullLines = validLines
.where((line) => line.contains('status=Full'))
.toList();
if (fullLines.isEmpty) return null;
final remainingReg = RegExp(r'remaining_cap=(\d+)');
int? maxRemaining;
for (String line in fullLines) {
final match = remainingReg.firstMatch(line);
if (match != null) {
final value = int.parse(match.group(1)!);
if (maxRemaining == null || value > maxRemaining) {
maxRemaining = value;
}
}
}
if (maxRemaining == null) return null;
// 🟢 智能单位识别:如果数值大于 100000(约 100 mAh),视为 µAh 需除以 1000
if (maxRemaining > 100000) {
return maxRemaining ~/ 1000;
} else {
return maxRemaining;
}
}
}
+140
View File
@@ -0,0 +1,140 @@
import 'dart:developer' as dev;
import '../utils/time_utils.dart';
/// 充电日志解析器
class ChargeParser {
/// 解析充电数据,返回解析结果
static ParseResult parse(List<String> lines, DateTime? chargingStartTime) {
dev.log('[ChargeParser] 开始解析,共 ${lines.length}', name: 'BatteryHealth');
final validLines = _collectValidLines(lines, chargingStartTime);
if (validLines.isEmpty) {
dev.log('[ChargeParser] 无有效时间窗口内的数据行', name: 'BatteryHealth');
return ParseResult.empty();
}
// 按时间戳从新到旧排序
validLines.sort((a, b) => b['timestamp'].compareTo(a['timestamp']));
final latest = validLines.first;
final latestLine = latest['line'] as String;
final latestType = latest['type'] as String;
dev.log(
'[ChargeParser] 最新有效数据: $latestType, 时间: ${latest['timestamp']}',
name: 'BatteryHealth',
);
if (latestType == 'wls') {
return _parseWireless(latestLine);
} else {
return _parseWired(latestLine);
}
}
static List<Map<String, dynamic>> _collectValidLines(
List<String> lines,
DateTime? chargingStartTime,
) {
final result = <Map<String, dynamic>>[];
for (String line in lines) {
final timestamp = TimeUtils.parseLogTimestamp(line);
if (!TimeUtils.isLogTimestampValid(timestamp, chargingStartTime)) {
continue;
}
final isUsb =
line.contains('chg_usb') &&
(line.contains('ibus=') || line.contains('real_type='));
final isWls = line.contains('chg_wls') && line.contains('wls_online=1');
if (isUsb || isWls) {
result.add({
'line': line,
'timestamp': timestamp,
'type': isWls ? 'wls' : 'usb',
});
}
}
return result;
}
static ParseResult _parseWireless(String line) {
final typeReg = RegExp(r'wls_type=(\w+)');
final voltReg = RegExp(r'wls_volt=(\d+)');
final currReg = RegExp(r'wls_curr=(\d+)');
final wlsType = typeReg.firstMatch(line)?.group(1);
final volt = int.parse(voltReg.firstMatch(line)?.group(1) ?? '0');
final curr = int.parse(currReg.firstMatch(line)?.group(1) ?? '0');
return ParseResult(
isWireless: true,
chargeType: wlsType ?? '无线',
power: (volt * curr) / 1000000.0,
volt: volt / 1000.0,
curr: curr / 1000.0,
wiredLevel: null,
);
}
static ParseResult _parseWired(String line) {
final ibusReg = RegExp(r'ibus=(\d+)');
final vbusReg = RegExp(r'vbus=(\d+)');
final levelReg = RegExp(r'wired_level=(\d+)');
final typeReg = RegExp(r'real_type=(\w+)');
final ibus = int.parse(ibusReg.firstMatch(line)?.group(1) ?? '0');
final vbus = int.parse(vbusReg.firstMatch(line)?.group(1) ?? '0');
final realType = typeReg.firstMatch(line)?.group(1);
final level = int.parse(levelReg.firstMatch(line)?.group(1) ?? '0');
String chargeType;
if (realType == 'PPS') {
chargeType = 'PPS';
} else if (realType == 'SDP' || realType == 'FLOAT') {
chargeType = 'SDP';
} else if (level >= 3) {
chargeType = 'PPS';
} else {
chargeType = 'SDP';
}
return ParseResult(
isWireless: false,
chargeType: chargeType,
power: (vbus * ibus) / 1000000000000.0,
volt: vbus / 1000000.0,
curr: ibus / 1000000.0,
wiredLevel: chargeType == 'PPS' ? level : null,
);
}
}
class ParseResult {
final bool isWireless;
final String chargeType;
final double power;
final double volt;
final double curr;
final int? wiredLevel;
ParseResult({
required this.isWireless,
required this.chargeType,
required this.power,
required this.volt,
required this.curr,
this.wiredLevel,
});
factory ParseResult.empty() {
return ParseResult(
isWireless: false,
chargeType: '',
power: 0.0,
volt: 0.0,
curr: 0.0,
wiredLevel: null,
);
}
}
+39 -2
View File
@@ -5,7 +5,6 @@ import 'services/saf_storage_service.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 🟢 初始化 SAF 服务
await SafStorageService().init();
runApp(const MyApp());
@@ -19,8 +18,46 @@ class MyApp extends StatelessWidget {
return MaterialApp(
title: '电池健康度',
theme: ThemeData(
// 🟢 中文用 HarmonyOS Sans SC
fontFamily: 'HarmonyOS_Sans_SC',
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
// 🟢 数字回退到 FlymeFont
fontFamilyFallback: const ['Flyme'],
// 🟢 统一文字颜色为黑色
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFFFFFFFF),
).copyWith(onSurface: Colors.black),
textTheme: const TextTheme(
// 大标题/数字(健康度、容量等)
displayMedium: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontFamilyFallback: ['Flyme'],
color: Colors.black,
),
// 标题(如“容量百分比变动趋势”)
headlineMedium: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontFamilyFallback: ['Flyme'],
color: Colors.black,
),
// 正文(电压、温度、循环次数等)
bodyMedium: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontFamilyFallback: ['Flyme'],
color: Colors.black,
),
// 小字(日期、辅助信息)
bodySmall: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontFamilyFallback: ['Flyme'],
color: Colors.black87,
),
// 数字专用(大号数字,如健康度百分比)
displayLarge: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontFamilyFallback: ['Flyme'],
color: Colors.black,
),
),
useMaterial3: true,
),
home: const BatteryHealthPage(),
+2 -4
View File
@@ -2,11 +2,10 @@
class DeviceMatching {
/// 根据机型返回设计容量(mAh)
static int getDesignCapacity(String model) {
if (model.contains('22')) return 5510;
if (model.contains('21 Pro')) return 5050;
if (model.contains('21')) return 4800;
if (model.contains('20 Pro')) return 5000;
if (model.contains('20 INFINITY')) return 4800;
if (model.contains('20 Inf')) return 4800;
if (model.contains('20')) return 4700;
if (model.contains('18s Pro')) return 4500;
if (model.contains('18s')) return 4000;
@@ -29,11 +28,10 @@ class DeviceMatching {
/// 根据机型返回显示名称
static String getModelName(String model) {
if (model.contains('22')) return '魅族22';
if (model.contains('21 Pro')) return '魅族21 Pro';
if (model.contains('21')) return '魅族21';
if (model.contains('20 Pro')) return '魅族20 Pro';
if (model.contains('20 INFINITY')) return '魅族20 INFINITY';
if (model.contains('20 Inf')) return '魅族20 Infinity';
if (model.contains('20')) return '魅族20';
if (model.contains('18s Pro')) return '魅族18s Pro';
if (model.contains('18s')) return '魅族18s';
File diff suppressed because it is too large Load Diff
+107
View File
@@ -0,0 +1,107 @@
import 'dart:developer' as dev;
import '../services/database_service.dart';
import '../logic/capacity_extractor.dart';
import '../models/saf_permission_state.dart';
import '../services/saf_storage_service.dart';
///
class BatteryDataService {
final SafStorageService _safService = SafStorageService();
final DatabaseService _dbService = DatabaseService();
///
Future<void> scanAndUpdateDB() async {
dev.log('🔵 scanAndUpdateDB 开始', name: 'BatteryHealth');
final state = await _safService.getPermissionState();
if (state != SafPermissionState.authorized) {
dev.log('🔵 scanAndUpdateDB: 未授权', name: 'BatteryHealth');
return;
}
try {
final files = await _safService.listFiles();
final filePattern = RegExp(r'mbattery_charger_log_(\d{4}_\d{2}_\d{2})$');
for (String fileName in files) {
final match = filePattern.firstMatch(fileName);
if (match == null) continue;
final dateStr = match.group(1)!.replaceAll('_', '-');
dev.log('🔵 处理文件: $fileName, 日期: $dateStr', name: 'BatteryHealth');
try {
final lines = await _safService.readLogFile(fileName);
if (lines.isEmpty) continue;
// 🟢 1.4.5 使 CapacityExtractor Full
int? cap = CapacityExtractor.extractCapacity(lines);
// 🟢 cap == null
if (cap == null) {
dev.log('🔵 日期 $dateStr 无充满记录,尝试复制前一天数据', name: 'BatteryHealth');
//
final recentData = await _dbService.queryRecentData(1);
if (recentData.isNotEmpty) {
final yesterdayCap = recentData.first['capacity'] as int;
final yesterdayMaxVolt =
recentData.first['volt_max'] as double? ?? 0.0;
final yesterdayMinVolt =
recentData.first['volt_min'] as double? ?? 0.0;
dev.log(
'🔵 复制前一天数据: cap=$yesterdayCap, date=$dateStr',
name: 'BatteryHealth',
);
// 🟢
await _dbService.insertOrUpdate(
dateStr,
yesterdayCap,
yesterdayMaxVolt,
yesterdayMinVolt,
);
} else {
dev.log('🔵 无历史数据可复制,跳过日期 $dateStr', name: 'BatteryHealth');
}
continue; //
}
// Full
final voltReg = RegExp(r'vbat=(\d+)');
double? maxVolt, minVolt;
for (String line in lines) {
if (!line.contains('tbat=')) continue;
final match = voltReg.firstMatch(line);
if (match != null) {
final v = int.parse(match.group(1)!) / 1000000;
if (maxVolt == null || v > maxVolt) maxVolt = v;
if (minVolt == null || v < minVolt) minVolt = v;
}
}
if (maxVolt == null || minVolt == null) continue;
await _dbService.insertOrUpdate(dateStr, cap, maxVolt, minVolt);
dev.log('🔵 插入数据库: $dateStr, cap=$cap', name: 'BatteryHealth');
} catch (e) {
dev.log('🔵 处理文件 $fileName 异常: $e', name: 'BatteryHealth');
}
}
} catch (e) {
dev.log('🔵 scanAndUpdateDB 异常: $e', name: 'BatteryHealth');
}
}
/// N
Future<List<Map<String, dynamic>>> getTrendData(int days) async {
return await _dbService.queryRecentData(days);
}
///
Future<Map<String, dynamic>?> getLatestData() async {
final data = await _dbService.queryRecentData(1);
if (data.isNotEmpty) return data.first;
return null;
}
}
+130
View File
@@ -0,0 +1,130 @@
import 'dart:developer' as dev;
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
///
class DatabaseService {
static Database? _database;
static const String _tableName = 'battery_data';
///
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
///
Future<Database> _initDatabase() async {
final dbPath = await getDatabasesPath();
final path = join(dbPath, 'battery_health.db');
return await openDatabase(
path,
version: 1,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE $_tableName (
date TEXT PRIMARY KEY,
capacity INTEGER NOT NULL,
volt_max REAL NOT NULL,
volt_min REAL NOT NULL,
updated_at TEXT NOT NULL
)
''');
await db.execute('''
CREATE INDEX idx_date ON $_tableName (date DESC)
''');
dev.log('✅ 数据库表创建成功', name: 'DatabaseService');
},
);
}
///
Future<void> insertOrUpdate(
String date,
int capacity,
double voltMax,
double voltMin,
) async {
final db = await database;
final now = DateTime.now().toIso8601String();
await db.insert(_tableName, {
'date': date,
'capacity': capacity,
'volt_max': voltMax,
'volt_min': voltMin,
'updated_at': now,
}, conflictAlgorithm: ConflictAlgorithm.replace);
dev.log('📝 数据已保存: $date, cap=$capacity', name: 'DatabaseService');
}
/// N
Future<List<Map<String, dynamic>>> queryRecentData(int limit) async {
final db = await database;
try {
final result = await db.query(
_tableName,
orderBy: 'date DESC',
limit: limit,
);
return result;
} catch (e) {
dev.log('⚠️ 查询数据失败: $e', name: 'DatabaseService');
return [];
}
}
/// 🟢 1.4.5
Future<Map<String, dynamic>?> queryByDate(String date) async {
final db = await database;
try {
final result = await db.query(
_tableName,
where: 'date = ?',
whereArgs: [date],
);
return result.isNotEmpty ? result.first : null;
} catch (e) {
dev.log('⚠️ 查询单日数据失败: $e', name: 'DatabaseService');
return null;
}
}
///
Future<void> deleteByDate(String date) async {
final db = await database;
await db.delete(_tableName, where: 'date = ?', whereArgs: [date]);
}
///
Future<List<String>> getAllDates() async {
final db = await database;
try {
final result = await db.query(
_tableName,
columns: ['date'],
orderBy: 'date DESC',
);
return result.map((row) => row['date'] as String).toList();
} catch (e) {
return [];
}
}
///
Future<void> clearAll() async {
final db = await database;
await db.delete(_tableName);
dev.log('🗑️ 所有数据已清空', name: 'DatabaseService');
}
///
Future<void> close() async {
if (_database != null) {
await _database!.close();
_database = null;
}
}
}
+98 -188
View File
@@ -1,129 +1,56 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
<<<<<<< HEAD
import 'package:file_picker/file_picker.dart';
import '../models/saf_permission_state.dart';
/// 使 file_picker 访
=======
import 'package:flutter_saf/flutter_saf.dart';
import '../models/saf_permission_state.dart';
/// SAF
/// SAF 访
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
class SafStorageService {
static final SafStorageService _instance = SafStorageService._internal();
factory SafStorageService() => _instance;
SafStorageService._internal();
<<<<<<< HEAD
static const String _prefKeySafPath = 'saf_storage_path';
String? _cachedPath;
Future<void> init() async {
final prefs = await SharedPreferences.getInstance();
_cachedPath = prefs.getString(_prefKeySafPath);
if (kDebugMode) {
print('[SAF] 初始化,缓存路径: $_cachedPath');
}
}
Future<SafPermissionState> getPermissionState() async {
if (_cachedPath == null || _cachedPath!.isEmpty) {
return SafPermissionState.unauthorized;
}
try {
final dir = Directory(_cachedPath!);
if (!await dir.exists()) {
=======
static const MethodChannel _channel = MethodChannel(
'com.lxh.battery_health/saf',
);
static const String _prefKeySafUri = 'saf_storage_uri';
static const String _prefKeySafPermission = 'saf_permission_uri';
String? _cachedUri;
/// URI
String? _cachedUriString;
/// SharedPreferences
/// SharedPreferences URI
Future<void> init() async {
final prefs = await SharedPreferences.getInstance();
_cachedUriString = prefs.getString(_prefKeySafUri);
if (kDebugMode) {
print('[SAF] 初始化,缓存 URI: $_cachedUriString');
try {
final prefs = await SharedPreferences.getInstance();
_cachedUri = prefs.getString(_prefKeySafUri);
if (kDebugMode) {
print('[SAF] 初始化,缓存 URI: $_cachedUri');
}
} catch (e) {
if (kDebugMode) {
print('[SAF] 初始化失败: $e');
}
_cachedUri = null;
}
}
///
///
Future<SafPermissionState> getPermissionState() async {
if (_cachedUriString == null || _cachedUriString!.isEmpty) {
if (_cachedUri == null || _cachedUri!.isEmpty) {
return SafPermissionState.unauthorized;
}
try {
final uri = Uri.parse(_cachedUriString!);
// Uri
final isValid = await FlutterSaf.isDirectory(uri);
if (!isValid) {
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
_clearCache();
return SafPermissionState.expired;
}
return SafPermissionState.authorized;
} catch (e) {
_clearCache();
return SafPermissionState.expired;
}
// authorized
return SafPermissionState.authorized;
}
<<<<<<< HEAD
Future<SafAuthorizationResult> requestPermission() async {
try {
// 使 file_picker
String? selectedPath = await FilePicker.platform.getDirectoryPath();
if (selectedPath == null || selectedPath.isEmpty) {
return SafAuthorizationResult.denied();
}
// mbattery_charger
if (!selectedPath.contains('mbattery_charger')) {
return SafAuthorizationResult.error('请选择 mbattery_charger 文件夹');
}
_cachedPath = selectedPath;
await _savePath(selectedPath);
if (kDebugMode) {
print('[SAF] 授权成功,路径: $selectedPath');
}
return SafAuthorizationResult.success(selectedPath);
=======
/// SAF
///
Future<SafAuthorizationResult> requestPermission() async {
try {
//
// /storage/emulated/0/mbattery_charger/
//
final uri = await FlutterSaf.openDocumentTree();
final String? uriString = await _channel.invokeMethod('selectFolder');
if (uri == null) {
if (uriString == null || uriString.isEmpty) {
return SafAuthorizationResult.denied();
}
// URI
await FlutterSaf.takePersistableUriPermission(uri);
//
final isValid = await FlutterSaf.isDirectory(uri);
if (!isValid) {
return SafAuthorizationResult.error('选择的路径不是有效目录');
}
// URI
final uriString = uri.toString();
_cachedUriString = uriString;
_cachedUri = uriString;
await _saveUri(uriString);
if (kDebugMode) {
@@ -131,7 +58,6 @@ class SafStorageService {
}
return SafAuthorizationResult.success(uriString);
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
} catch (e) {
if (kDebugMode) {
print('[SAF] 授权失败: $e');
@@ -140,58 +66,63 @@ class SafStorageService {
}
}
<<<<<<< HEAD
/// 🟢 URI Kotlin safUri
Future<bool> restoreUri() async {
if (_cachedUri == null || _cachedUri!.isEmpty) {
if (kDebugMode) {
print('[SAF] restoreUri: 缓存 URI 为空');
}
return false;
}
try {
final bool? result = await _channel.invokeMethod('restoreUri', {
'uri': _cachedUri,
});
if (result == true) {
if (kDebugMode) {
print('[SAF] restoreUri 成功: $_cachedUri');
}
return true;
} else {
if (kDebugMode) {
print('[SAF] restoreUri 失败: 返回 false');
}
return false;
}
} catch (e) {
if (kDebugMode) {
print('[SAF] restoreUri 异常: $e');
}
return false;
}
}
///
Future<bool> logFileExists(String fileName) async {
final state = await getPermissionState();
if (state != SafPermissionState.authorized) return false;
try {
final file = File('${_cachedPath!}/$fileName');
return await file.exists();
=======
///
Future<bool> logFileExists(String fileName) async {
final state = await getPermissionState();
if (state != SafPermissionState.authorized) {
return false;
}
try {
final uri = Uri.parse(_cachedUriString!);
final fileUri = await FlutterSaf.getFile(uri, fileName);
return fileUri != null && await FlutterSaf.isFile(fileUri);
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
final files = await listFiles();
return files.contains(fileName);
} catch (e) {
return false;
}
}
<<<<<<< HEAD
///
Future<List<String>> readLogFile(String fileName) async {
// 🟢 URI
await restoreUri();
final state = await getPermissionState();
if (state != SafPermissionState.authorized) return [];
try {
final file = File('${_cachedPath!}/$fileName');
if (!await file.exists()) return [];
return await file.readAsLines();
=======
///
///
Future<List<String>> readLogFile(String fileName) async {
final state = await getPermissionState();
if (state != SafPermissionState.authorized) {
return [];
}
try {
final uri = Uri.parse(_cachedUriString!);
final fileUri = await FlutterSaf.getFile(uri, fileName);
if (fileUri == null || !await FlutterSaf.isFile(fileUri)) {
return [];
}
final content = await FlutterSaf.readTextFile(fileUri);
final String? content = await _channel.invokeMethod('readLogFile', {
'fileName': fileName,
});
if (content == null || content.isEmpty) return [];
return content.split('\n');
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
} catch (e) {
if (kDebugMode) {
print('[SAF] 读取文件失败: $e');
@@ -200,83 +131,62 @@ class SafStorageService {
}
}
<<<<<<< HEAD
///
Future<List<String>> listFiles() async {
// 🟢 URI
await restoreUri();
final state = await getPermissionState();
if (state != SafPermissionState.authorized) return [];
try {
final dir = Directory(_cachedPath!);
if (!await dir.exists()) return [];
final entities = await dir.list().toList();
return entities
.where((e) => e is File)
.map((e) => e.path.split(Platform.pathSeparator).last)
.toList();
final result = await _channel.invokeMethod('listFiles');
if (result is List) {
return result.cast<String>();
}
return [];
} catch (e) {
if (kDebugMode) {
print('[SAF] 列出文件失败: $e');
}
=======
///
Future<List<String>> listFiles() async {
final state = await getPermissionState();
if (state != SafPermissionState.authorized) {
return [];
}
try {
final uri = Uri.parse(_cachedUriString!);
final files = await FlutterSaf.listFiles(uri);
return files.where((f) => f.isFile).map((f) => f.name).toList();
} catch (e) {
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
return [];
}
}
<<<<<<< HEAD
=======
///
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
///
Future<bool> validatePermission() async {
final state = await getPermissionState();
return state == SafPermissionState.authorized;
}
<<<<<<< HEAD
///
void _clearCache() {
_cachedPath = null;
_savePath(null);
}
Future<void> _savePath(String? path) async {
final prefs = await SharedPreferences.getInstance();
if (path != null && path.isNotEmpty) {
await prefs.setString(_prefKeySafPath, path);
} else {
await prefs.remove(_prefKeySafPath);
}
}
String? get cachedPath => _cachedPath;
=======
///
void _clearCache() {
_cachedUriString = null;
_cachedUri = null;
_saveUri(null);
}
/// URI SharedPreferences
Future<void> _saveUri(String? uriString) async {
final prefs = await SharedPreferences.getInstance();
if (uriString != null && uriString.isNotEmpty) {
await prefs.setString(_prefKeySafUri, uriString);
} else {
await prefs.remove(_prefKeySafUri);
Future<void> _saveUri(String? uri) async {
try {
final prefs = await SharedPreferences.getInstance();
if (uri != null && uri.isNotEmpty) {
await prefs.setString(_prefKeySafUri, uri);
if (kDebugMode) {
print('[SAF] 保存 URI 成功: $uri');
}
} else {
await prefs.remove(_prefKeySafUri);
if (kDebugMode) {
print('[SAF] 清除 URI');
}
}
} catch (e) {
if (kDebugMode) {
print('[SAF] 保存 URI 失败: $e');
}
}
}
/// URI
String? get cachedUri => _cachedUriString;
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
String? get cachedUri => _cachedUri;
}
+53 -6
View File
@@ -1,6 +1,7 @@
import '../constants/charge_maps.dart';
class ChargeUtils {
// ============ 线 ============
static String getDisplayPowerWireless(double power) {
if (power == 0) return '读取中...';
const List<int> levels = [5, 7, 15, 27, 40, 50, 66];
@@ -12,21 +13,17 @@ class ChargeUtils {
return '${matchedLevel}W';
}
// ============ 线 ============
static String getDisplayPowerWired(
double power,
int? wiredLevel,
String chargeType,
) {
// USB 7.5W
if (chargeType == "SDP") return "≈7.5W";
// 🟢 使 wiredLevel
if (wiredLevel != null && ChargeMaps.wiredPower.containsKey(wiredLevel)) {
double p = ChargeMaps.wiredPower[wiredLevel]!;
if (p > 0) return '${p.toInt()}W';
}
// 🟢 ±3W
double best = 0;
for (var entry in ChargeMaps.wiredPower.entries) {
if (entry.value <= power + 3 && entry.value > best) {
@@ -37,11 +34,61 @@ class ChargeUtils {
return best > 0 ? '${best.toInt()}W' : '${power.round()}W';
}
// ============ 🟢 1.5.0 / ============
/// 30w/65w
static String getMainDisplayPowerWired(
double power,
int? wiredLevel,
String chargeType,
) {
// USB 7.5W
if (chargeType == "SDP") return "≈7.5w";
if (power == 0) return "读取中...";
final actual = power.round();
//
if (wiredLevel != null && ChargeMaps.wiredPower.containsKey(wiredLevel)) {
final requested = ChargeMaps.wiredPower[wiredLevel]!.round();
return "${actual}w/${requested}w";
}
//
return "${actual}w";
}
// ============ 🟢 1.5.0 ============
/// 80w/L-10
static String getDetailRequestedPowerWired(
double power,
int? wiredLevel,
String chargeType,
) {
if (chargeType == "SDP") return "≈7.5w";
if (power == 0) return "读取中...";
if (wiredLevel != null && ChargeMaps.wiredPower.containsKey(wiredLevel)) {
final requested = ChargeMaps.wiredPower[wiredLevel]!.round();
return "${requested}w/L-$wiredLevel";
}
return "${power.round()}w";
}
// ============ 🟢 1.5.0 ============
static String getDetailActualPowerWired(double power, String chargeType) {
if (chargeType == "SDP") return "≈7.5w";
if (power == 0) return "读取中...";
return "${power.round()}w";
}
// ============ ============
static String getChargeTypeLabel(bool isWireless, String chargeType) {
if (isWireless) {
return chargeType == "无线" ? "无线" : chargeType;
}
// 🟢 "识别中...""等待log信息"
if (chargeType.isEmpty) {
return "识别中...";
}
+46
View File
@@ -0,0 +1,46 @@
class TimeUtils {
/// UTC
static DateTime? parseLogTimestamp(String line) {
final reg = RegExp(r'\[(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})\]');
final match = reg.firstMatch(line);
if (match == null) return null;
try {
final dateParts = match.group(1)!.split('-');
final timeParts = match.group(2)!.split(':');
return DateTime.utc(
int.parse(dateParts[0]),
int.parse(dateParts[1]),
int.parse(dateParts[2]),
int.parse(timeParts[0]),
int.parse(timeParts[1]),
int.parse(timeParts[2]),
);
} catch (_) {
return null;
}
}
///
static bool isLogTimestampValid(
DateTime? logTime,
DateTime? chargingStartTime,
) {
if (logTime == null) return false;
if (chargingStartTime == null) {
final nowUtc = DateTime.now().toUtc();
final diff = nowUtc.difference(logTime);
return diff.abs().inMinutes <= 3;
}
final endTime = chargingStartTime.add(const Duration(minutes: 3));
return logTime.isAfter(chargingStartTime) && logTime.isBefore(endTime);
}
/// UTC
static String getTodayFileName() {
final nowUtc = DateTime.now().toUtc();
final year = nowUtc.year.toString();
final month = nowUtc.month.toString().padLeft(2, '0');
final day = nowUtc.day.toString().padLeft(2, '0');
return 'mbattery_charger_log_${year}_${month}_$day';
}
}
+194
View File
@@ -0,0 +1,194 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class BatteryInfoPanel extends StatelessWidget {
final double batteryVolt;
final double batteryTemp;
final double maxVolt;
final double minVolt;
final double maxTemp;
final double minTemp;
const BatteryInfoPanel({
super.key,
required this.batteryVolt,
required this.batteryTemp,
required this.maxVolt,
required this.minVolt,
required this.maxTemp,
required this.minTemp,
});
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildInfoItem(
_buildIcon('voltage'),
'电压',
'${batteryVolt.toStringAsFixed(3)}V',
),
const SizedBox(height: 8),
Row(
children: [
RichText(
text: TextSpan(
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.red,
),
children: [
const TextSpan(
text: '',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
color: Colors.red,
),
),
TextSpan(text: '${maxVolt.toStringAsFixed(3)}V'),
],
),
),
const SizedBox(width: 12),
RichText(
text: TextSpan(
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.blue,
),
children: [
const TextSpan(
text: '',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
color: Colors.blue,
),
),
TextSpan(text: '${minVolt.toStringAsFixed(3)}V'),
],
),
),
],
),
],
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildInfoItem(
_buildIcon('temperature'),
'温度',
'${batteryTemp.toStringAsFixed(0)}',
),
const SizedBox(height: 8),
Row(
children: [
RichText(
text: TextSpan(
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.red,
),
children: [
const TextSpan(
text: '',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
color: Colors.red,
),
),
TextSpan(text: '${maxTemp.toStringAsFixed(0)}'),
],
),
),
const SizedBox(width: 12),
RichText(
text: TextSpan(
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.blue,
),
children: [
const TextSpan(
text: '',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
color: Colors.blue,
),
),
TextSpan(text: '${minTemp.toStringAsFixed(0)}'),
],
),
),
],
),
],
),
),
],
);
}
Widget _buildIcon(String type) {
switch (type) {
case 'voltage':
return SvgPicture.asset(
'assets/icons/si--lightning-fill.svg',
width: 18,
height: 18,
colorFilter: const ColorFilter.mode(Colors.grey, BlendMode.srcIn),
);
case 'temperature':
return SvgPicture.asset(
'assets/icons/mdi--temperature.svg',
width: 18,
height: 18,
colorFilter: const ColorFilter.mode(Colors.grey, BlendMode.srcIn),
);
default:
return const Icon(Icons.help_outline, size: 18, color: Colors.grey);
}
}
Widget _buildInfoItem(Widget icon, String label, String value) {
return Row(
children: [
icon,
const SizedBox(width: 6),
Text(
label,
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 14,
color: Colors.grey,
),
),
const SizedBox(width: 6),
Text(
value,
style: const TextStyle(
fontFamily: 'Flyme',
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.black,
),
),
],
);
}
}
+115
View File
@@ -0,0 +1,115 @@
import 'package:flutter/material.dart';
class BatterySummary extends StatelessWidget {
final double healthPercent;
final int cycleCount;
final double currentCap;
final int designCap;
const BatterySummary({
super.key,
required this.healthPercent,
required this.cycleCount,
required this.currentCap,
required this.designCap,
});
@override
Widget build(BuildContext context) {
final bool isLowHealth = healthPercent < 70;
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
//
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
healthPercent.toStringAsFixed(1),
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 40,
fontWeight: FontWeight.w500,
height: 1.0,
color: isLowHealth ? Colors.red : Colors.black,
),
),
const SizedBox(width: 2),
Text(
'%',
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 20,
fontWeight: FontWeight.w300,
height: 1.0,
color: isLowHealth ? Colors.red : Colors.grey.shade600,
),
),
],
),
const Spacer(),
// cycles + mAh
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
RichText(
text: TextSpan(
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 16,
fontWeight: FontWeight.w500,
height: 1.2,
color: Colors.black,
),
children: [
TextSpan(text: '$cycleCount'),
TextSpan(
text: ' cycles',
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
color: Colors.black,
),
),
],
),
),
const SizedBox(height: 4),
RichText(
text: TextSpan(
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 20,
fontWeight: FontWeight.w300,
height: 1.0,
color: const Color(0xFF5F5F5F),
),
children: [
TextSpan(text: currentCap.toStringAsFixed(0)),
TextSpan(
text: ' / ',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
color: const Color(0xFF5F5F5F).withValues(alpha: 0.5),
),
),
TextSpan(text: designCap.toString()),
TextSpan(
text: ' mAh',
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 16,
fontWeight: FontWeight.w500,
color: Color(0xFF5F5F5F),
),
),
],
),
),
],
),
],
);
}
}
+113 -42
View File
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/charge_utils.dart';
///
class ChargeDetailPage extends StatelessWidget {
final String chargeType;
final bool isWireless;
@@ -20,62 +20,91 @@ class ChargeDetailPage extends StatelessWidget {
this.wiredLevel,
});
String _getDisplayPower() {
if (isWireless) {
return ChargeUtils.getDisplayPowerWireless(power);
} else {
return ChargeUtils.getDisplayPowerWired(power, wiredLevel, chargeType);
}
}
String _getProtocolDisplay() {
if (isWireless) return '无线充电($chargeType';
if (chargeType == 'PPS') return 'PPS 快充';
if (chargeType == 'SDP') return 'USB 充电'; // 🟢
if (chargeType == 'SDP') return 'USB 充电';
return chargeType;
}
String _getRequestedDisplay() {
return ChargeUtils.getDetailRequestedPowerWired(
power,
wiredLevel,
chargeType,
);
}
String _getActualDisplay() {
return ChargeUtils.getDetailActualPowerWired(power, chargeType);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('充电详情'),
backgroundColor: const Color.fromARGB(0, 255, 255, 255),
elevation: 0,
foregroundColor: Colors.black,
iconTheme: const IconThemeData(color: Colors.black),
return AnnotatedRegion<SystemUiOverlayStyle>(
value: const SystemUiOverlayStyle(
statusBarColor: Color.fromRGBO(157, 212, 237, 0.1),
statusBarIconBrightness: Brightness.dark,
statusBarBrightness: Brightness.dark,
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildDetailRow('协议', _getProtocolDisplay()),
const Divider(),
_buildDetailRow('功率', _getDisplayPower()),
const Divider(),
_buildDetailRow('电压', '${volt.toStringAsFixed(2)}V'),
const Divider(),
_buildDetailRow('电流', '${curr.toStringAsFixed(2)}A'),
const Divider(),
if (!isWireless && wiredLevel != null)
_buildDetailRow('档位', '$wiredLevel'),
if (!isWireless && wiredLevel == null) _buildDetailRow('档位', '自动'),
if (isWireless) _buildDetailRow('类型', '无线'),
const Spacer(),
Center(
child: Text(
'数据来自 BMS 实时日志',
style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('充电详情'),
backgroundColor: Colors.white,
elevation: 0,
scrolledUnderElevation: 0,
shadowColor: Colors.transparent,
surfaceTintColor: Colors.transparent,
foregroundColor: Colors.black,
iconTheme: const IconThemeData(color: Colors.black),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildTextRow('协议', _getProtocolDisplay()),
const Divider(),
if (!isWireless) ...[
_buildTextRow('标定档位', _getRequestedDisplay()),
const Divider(),
_buildTextRow('实际功率', _getActualDisplay()),
const Divider(),
] else ...[
_buildTextRow('功率', ChargeUtils.getDisplayPowerWireless(power)),
const Divider(),
],
_buildDetailRow('电压', volt, 'V'),
const Divider(),
_buildDetailRow('电流', curr, 'A'),
const Divider(),
if (isWireless) _buildTextRow('类型', '无线'),
if (!isWireless && wiredLevel == null) _buildTextRow('档位', '自动'),
const Spacer(),
Center(
child: Text(
'数据来自 BMS 实时日志',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 12,
color: Colors.grey.shade500,
),
),
),
),
],
],
),
),
),
);
}
Widget _buildDetailRow(String label, String value) {
///
Widget _buildTextRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0),
child: Row(
@@ -84,6 +113,7 @@ class ChargeDetailPage extends StatelessWidget {
Text(
label,
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 16,
fontWeight: FontWeight.w400,
color: Colors.grey,
@@ -92,6 +122,7 @@ class ChargeDetailPage extends StatelessWidget {
Text(
value,
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC', // Harmony
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.black87,
@@ -101,4 +132,44 @@ class ChargeDetailPage extends StatelessWidget {
),
);
}
/// / Flyme Harmony
Widget _buildDetailRow(String label, double value, String unit) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
label,
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 16,
fontWeight: FontWeight.w400,
color: Colors.grey,
),
),
RichText(
text: TextSpan(
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.black87,
),
children: [
TextSpan(
text: value.toStringAsFixed(2),
style: const TextStyle(fontFamily: 'Flyme'), // 🟢 Flyme
),
TextSpan(
text: unit,
style: const TextStyle(fontFamily: 'HarmonyOS_Sans_SC'),
),
],
),
),
],
),
);
}
}
+58
View File
@@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
class ChargeEntry extends StatelessWidget {
final String summary;
final bool isCharging;
final VoidCallback onTap;
const ChargeEntry({
super.key,
required this.summary,
required this.isCharging,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: isCharging ? onTap : null,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
summary,
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC', // 🟢 Harmony
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.black87,
),
),
Row(
children: [
Text(
'充电信息',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.grey.shade700,
),
),
const SizedBox(width: 4),
Text(
'>',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.grey.shade700,
),
),
],
),
],
),
);
}
}
+234
View File
@@ -0,0 +1,234 @@
import 'package:flutter/material.dart';
// --- ---
const Color kHealthGreen = Color(0xFF00B140);
const Color kHealthYellow = Color(0xFFEFDF00);
const Color kHealthOrange = Color(0xFFD75A16);
///
class TrendChart extends StatelessWidget {
final List<Map<String, dynamic>> data;
final int designCap;
const TrendChart({super.key, required this.data, required this.designCap});
@override
Widget build(BuildContext context) {
List<Map<String, dynamic>> displayData = data.isNotEmpty
? data
: _getMockData();
List<String> dates = displayData.map((e) {
String date = e['date'] as String;
var parts = date.split('-');
return '${parts[1]}/${parts[2]}';
}).toList();
List<double> percents = displayData.map((e) {
int cap = e['capacity'] as int;
return (cap / designCap) * 100;
}).toList();
while (percents.length < 15) {
percents.insert(0, 0);
dates.insert(0, '');
}
if (percents.length > 15) {
percents = percents.sublist(percents.length - 15);
dates = dates.sublist(dates.length - 15);
}
int todayIndex = percents.length - 1;
int sevenDaysAgoIndex = todayIndex - 7;
bool showSevenDaysAgo = sevenDaysAgoIndex >= 0;
String sevenDaysAgoDate = showSevenDaysAgo ? dates[sevenDaysAgoIndex] : '';
String todayDate = dates[todayIndex];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'容量百分比变动趋势(近15天)',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 8),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 180,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Text(
'100',
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 10,
color: Colors.grey,
height: 1.0,
),
),
Text(
'70',
style: TextStyle(
fontFamily: 'Flyme',
fontSize: 10,
color: Colors.grey,
height: 1.0,
),
),
],
),
),
const SizedBox(width: 4),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
double totalWidth = constraints.maxWidth;
double step = totalWidth / 15;
return SizedBox(
height: 180,
child: Stack(
children: [
Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: List.generate(percents.length, (index) {
double value = percents[index];
Color barColor;
if (value > 0) {
if (value >= 80) {
barColor = kHealthGreen;
} else if (value >= 70) {
barColor = kHealthYellow;
} else {
barColor = Colors.red;
}
} else {
barColor = Colors.grey.shade300;
}
double clampedValue = value.clamp(70.0, 100.0);
double heightFactor =
(clampedValue - 70.0) / 30.0;
return Expanded(
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: const EdgeInsets.symmetric(
horizontal: 2,
),
height: 20 + (100 * heightFactor),
width: 18,
decoration: BoxDecoration(
color: barColor,
borderRadius: BorderRadius.circular(4),
),
),
),
);
}),
),
),
if (showSevenDaysAgo && sevenDaysAgoDate.isNotEmpty)
Positioned(
left: sevenDaysAgoIndex * step + (step / 2) - 14,
bottom: 2,
child: Text(
sevenDaysAgoDate,
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 9,
color: Colors.grey,
height: 1.0,
),
),
),
if (todayDate.isNotEmpty)
Positioned(
left: todayIndex * step + (step / 2) - 14,
bottom: 2,
child: Text(
todayDate,
style: const TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 9,
color: Colors.black,
height: 1.0,
fontWeight: FontWeight.w600,
),
),
),
],
),
);
},
),
),
],
),
if (percents.every((v) => v == 0))
const Padding(
padding: EdgeInsets.only(top: 8.0),
child: Text(
'暂无历史数据,请点击刷新按钮更新',
style: TextStyle(
fontFamily: 'HarmonyOS_Sans_SC',
fontSize: 12,
color: Colors.grey,
),
),
),
],
);
}
List<Map<String, dynamic>> _getMockData() {
List<String> mockDates = [
'2026-06-14',
'2026-06-15',
'2026-06-16',
'2026-06-17',
'2026-06-18',
'2026-06-19',
'2026-06-20',
'2026-06-21',
'2026-06-22',
'2026-06-23',
'2026-06-24',
'2026-06-25',
'2026-06-26',
'2026-06-27',
'2026-06-28',
];
List<int> mockCap = [
4635,
4632,
4628,
4625,
4620,
4618,
4615,
4610,
4608,
4605,
4600,
4598,
4595,
4590,
4585,
];
return List.generate(
15,
(i) => {'date': mockDates[i], 'capacity': mockCap[i]},
);
}
}
@@ -6,19 +6,11 @@ import FlutterMacOS
import Foundation
import device_info_plus
<<<<<<< HEAD
=======
import path_provider_foundation
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
import shared_preferences_foundation
import sqflite_darwin
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
<<<<<<< HEAD
=======
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin"))
}
-50
View File
@@ -113,14 +113,6 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "7.0.1"
file_picker:
dependency: "direct main"
description:
name: file_picker
sha256: "1bbf65dd997458a08b531042ec3794112a6c39c07c37ff22113d2e7e4f81d4e4"
url: "https://pub.flutter-io.cn"
source: hosted
version: "6.2.1"
flutter:
dependency: "direct main"
description: flutter
@@ -134,14 +126,6 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "5.0.0"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
name: flutter_plugin_android_lifecycle
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.0.35"
flutter_svg:
dependency: "direct main"
description:
@@ -416,7 +400,6 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.1.8"
<<<<<<< HEAD
pub_semver:
dependency: transitive
description:
@@ -433,45 +416,28 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.6.0"
=======
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
shared_preferences:
dependency: "direct main"
description:
name: shared_preferences
sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf
<<<<<<< HEAD
url: "https://pub.flutter-io.cn"
=======
url: "https://pub.dev"
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
source: hosted
version: "2.5.5"
shared_preferences_android:
dependency: transitive
description:
name: shared_preferences_android
<<<<<<< HEAD
sha256: "93ae5884a9df5d3bb696825bceb3a17590754548b5d740eba51500afc8d088f5"
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.4.26"
=======
sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53
url: "https://pub.dev"
source: hosted
version: "2.4.23"
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
shared_preferences_foundation:
dependency: transitive
description:
name: shared_preferences_foundation
sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f"
<<<<<<< HEAD
url: "https://pub.flutter-io.cn"
=======
url: "https://pub.dev"
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
source: hosted
version: "2.5.6"
shared_preferences_linux:
@@ -479,11 +445,7 @@ packages:
description:
name: shared_preferences_linux
sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
<<<<<<< HEAD
url: "https://pub.flutter-io.cn"
=======
url: "https://pub.dev"
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
source: hosted
version: "2.4.1"
shared_preferences_platform_interface:
@@ -491,11 +453,7 @@ packages:
description:
name: shared_preferences_platform_interface
sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9"
<<<<<<< HEAD
url: "https://pub.flutter-io.cn"
=======
url: "https://pub.dev"
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
source: hosted
version: "2.4.2"
shared_preferences_web:
@@ -503,11 +461,7 @@ packages:
description:
name: shared_preferences_web
sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
<<<<<<< HEAD
url: "https://pub.flutter-io.cn"
=======
url: "https://pub.dev"
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
source: hosted
version: "2.4.3"
shared_preferences_windows:
@@ -515,11 +469,7 @@ packages:
description:
name: shared_preferences_windows
sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
<<<<<<< HEAD
url: "https://pub.flutter-io.cn"
=======
url: "https://pub.dev"
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
source: hosted
version: "2.4.1"
sky_engine:
+5 -6
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.3.0-dev.2
version: 1.5.3
environment:
sdk: ^3.9.2
@@ -38,12 +38,8 @@ dependencies:
path: ^1.9.0
flutter_svg: ^2.0.10+1
shared_preferences: ^2.2.0
<<<<<<< HEAD
file_picker: ^6.0.0
=======
flutter_saf: ^0.1.0
>>>>>>> c5a85e05a3bb50cd4ea7de0da2db94c867eb7ddd
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
@@ -79,6 +75,9 @@ flutter:
weight: 400
- asset: assets/fonts/HarmonyOS_Sans_SC_Medium.ttf
weight: 500
- family: Flyme
fonts:
- asset: assets/fonts/flymeFont.ttf
assets:
- assets/icons/