Compare commits
3 Commits
7ba2e612f1
...
1.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 2b34b6c8b6 | |||
| f8ffb32bb0 | |||
| 8e93cbeed2 |
@@ -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
|
||||
|
||||
@@ -44,18 +44,20 @@ class MainActivity : FlutterActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
android.util.Log.d("BatteryHealth", "onCreate 开始")
|
||||
|
||||
// 🟢 从 SharedPreferences 恢复 URI
|
||||
val prefs: SharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
val uriString = prefs.getString(KEY_SAF_URI, null)
|
||||
if (uriString != null) {
|
||||
try {
|
||||
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", "恢复 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) {
|
||||
@@ -68,6 +70,18 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
@@ -125,9 +139,8 @@ class MainActivity : FlutterActivity() {
|
||||
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
contentResolver.takePersistableUriPermission(uri, takeFlags)
|
||||
safUri = uri
|
||||
// 🟢 保存到 SharedPreferences
|
||||
saveUri(uri)
|
||||
android.util.Log.d("BatteryHealth", "SAF URI: $uri")
|
||||
android.util.Log.d("BatteryHealth", "SAF 授权成功 URI: $uri")
|
||||
safResult?.success(uri.toString())
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("BatteryHealth", "SAF 授权失败: ${e.message}")
|
||||
@@ -141,15 +154,13 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
|
||||
private fun getTreeDocId(): String? {
|
||||
android.util.Log.d("BatteryHealth", "getTreeDocId: safUri = $safUri")
|
||||
return safUri?.let { DocumentsContract.getTreeDocumentId(it) }
|
||||
}
|
||||
|
||||
private fun listFiles(): List<String> {
|
||||
android.util.Log.d("BatteryHealth", "listFiles 被调用")
|
||||
android.util.Log.d("BatteryHealth", "listFiles 被调用,safUri = $safUri")
|
||||
val result = mutableListOf<String>()
|
||||
val docId = getTreeDocId()
|
||||
android.util.Log.d("BatteryHealth", "docId = $docId")
|
||||
if (docId == null || docId.isEmpty()) {
|
||||
android.util.Log.e("BatteryHealth", "docId 为空")
|
||||
return result
|
||||
@@ -157,18 +168,15 @@ class MainActivity : FlutterActivity() {
|
||||
|
||||
try {
|
||||
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(safUri!!, docId)
|
||||
android.util.Log.d("BatteryHealth", "childrenUri = $childrenUri")
|
||||
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) {
|
||||
android.util.Log.d("BatteryHealth", "找到文件: $name")
|
||||
result.add(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
android.util.Log.d("BatteryHealth", "共找到 ${result.size} 个文件")
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("BatteryHealth", "列出文件失败: ${e.message}", e)
|
||||
}
|
||||
@@ -242,6 +250,15 @@ class MainActivity : FlutterActivity() {
|
||||
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()
|
||||
|
||||
@@ -1,18 +1,9 @@
|
||||
<?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>
|
||||
<!-- 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="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
|
||||
<!-- 状态栏背景白色 -->
|
||||
<item name="android:statusBarColor">@android:color/white</item>
|
||||
<!-- 状态栏图标亮色(深色图标) -->
|
||||
<item name="android:windowLightStatusBar">true</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -885,11 +885,17 @@ class _BatteryHealthPageState extends State<BatteryHealthPage>
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: SystemUiOverlayStyle.dark,
|
||||
value: SystemUiOverlayStyle(
|
||||
statusBarColor: Colors.white,
|
||||
statusBarIconBrightness: Brightness.dark,
|
||||
statusBarBrightness: Brightness.dark,
|
||||
),
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.white, // 🟢 页面背景色与 AppBar 统一
|
||||
appBar: AppBar(
|
||||
backgroundColor: const Color.fromARGB(0, 255, 255, 255),
|
||||
elevation: 0,
|
||||
backgroundColor: Colors.white,
|
||||
elevation: 0, // 🟢 去掉阴影
|
||||
scrolledUnderElevation: 0, // 🟢 滚动时也不出现阴影
|
||||
title: const Text(
|
||||
'电池健康度',
|
||||
style: TextStyle(
|
||||
|
||||
@@ -3,6 +3,8 @@ import 'package:flutter/services.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../models/saf_permission_state.dart';
|
||||
|
||||
/// SAF 存储服务
|
||||
/// 负责管理通过 SAF 授权的文件夹访问
|
||||
class SafStorageService {
|
||||
static final SafStorageService _instance = SafStorageService._internal();
|
||||
factory SafStorageService() => _instance;
|
||||
@@ -14,7 +16,7 @@ class SafStorageService {
|
||||
static const String _prefKeySafUri = 'saf_storage_uri';
|
||||
String? _cachedUri;
|
||||
|
||||
// 🟢 初始化时从 SharedPreferences 恢复 URI
|
||||
/// 初始化,从 SharedPreferences 恢复 URI
|
||||
Future<void> init() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
@@ -30,14 +32,16 @@ class SafStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取当前授权状态(简化版,直接根据缓存判断)
|
||||
Future<SafPermissionState> getPermissionState() async {
|
||||
if (_cachedUri == null || _cachedUri!.isEmpty) {
|
||||
return SafPermissionState.unauthorized;
|
||||
}
|
||||
// 🟢 直接返回 authorized,相信缓存
|
||||
// 直接返回 authorized,相信缓存
|
||||
return SafPermissionState.authorized;
|
||||
}
|
||||
|
||||
/// 请求 SAF 授权(引导用户选择文件夹)
|
||||
Future<SafAuthorizationResult> requestPermission() async {
|
||||
try {
|
||||
final String? uriString = await _channel.invokeMethod('selectFolder');
|
||||
@@ -62,23 +66,57 @@ class SafStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 🟢 将 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 files = await _channel.invokeMethod('listFiles');
|
||||
if (files is List) {
|
||||
return files.contains(fileName);
|
||||
}
|
||||
return false;
|
||||
final files = await listFiles();
|
||||
return files.contains(fileName);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取日志文件内容(返回行列表)
|
||||
Future<List<String>> readLogFile(String fileName) async {
|
||||
// 🟢 先尝试恢复 URI
|
||||
await restoreUri();
|
||||
|
||||
final state = await getPermissionState();
|
||||
if (state != SafPermissionState.authorized) return [];
|
||||
|
||||
try {
|
||||
final String? content = await _channel.invokeMethod('readLogFile', {
|
||||
'fileName': fileName,
|
||||
@@ -93,9 +131,14 @@ class SafStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取文件夹中的文件列表
|
||||
Future<List<String>> listFiles() async {
|
||||
// 🟢 先尝试恢复 URI
|
||||
await restoreUri();
|
||||
|
||||
final state = await getPermissionState();
|
||||
if (state != SafPermissionState.authorized) return [];
|
||||
|
||||
try {
|
||||
final result = await _channel.invokeMethod('listFiles');
|
||||
if (result is List) {
|
||||
@@ -110,16 +153,19 @@ class SafStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 验证授权是否有效(简化版)
|
||||
Future<bool> validatePermission() async {
|
||||
final state = await getPermissionState();
|
||||
return state == SafPermissionState.authorized;
|
||||
}
|
||||
|
||||
/// 清除缓存
|
||||
void _clearCache() {
|
||||
_cachedUri = null;
|
||||
_saveUri(null);
|
||||
}
|
||||
|
||||
/// 保存 URI 到 SharedPreferences
|
||||
Future<void> _saveUri(String? uri) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
@@ -141,5 +187,6 @@ class SafStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取缓存的 URI(用于调试)
|
||||
String? get cachedUri => _cachedUri;
|
||||
}
|
||||
|
||||
+1
-1
@@ -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.4
|
||||
version: 1.4.0
|
||||
|
||||
environment:
|
||||
sdk: ^3.9.2
|
||||
|
||||
Reference in New Issue
Block a user