尝试解决二次启动时文件读取问题

This commit is contained in:
2026-07-05 00:59:41 +08:00
parent c7ee563e84
commit 7ba2e612f1
3 changed files with 164 additions and 60 deletions
@@ -4,6 +4,7 @@ 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
@@ -20,18 +21,17 @@ 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
// ---------- SAF 相关 ----------
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
@@ -42,6 +42,32 @@ class MainActivity : FlutterActivity() {
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 🟢 从 SharedPreferences 恢复 URI
val prefs: SharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val uriString = prefs.getString(KEY_SAF_URI, null)
if (uriString != null) {
try {
safUri = Uri.parse(uriString)
android.util.Log.d("BatteryHealth", "恢复 SAF URI: $safUri")
} catch (e: Exception) {
android.util.Log.e("BatteryHealth", "恢复 URI 失败: ${e.message}")
}
}
}
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 sendChargeState(isCharging: Boolean) {
val chargeType = if (isCharging) {
val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
@@ -66,7 +92,6 @@ class MainActivity : FlutterActivity() {
status == BatteryManager.BATTERY_STATUS_FULL
}
// ---------- SAF 方法 ----------
private fun openFolderPicker() {
try {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
@@ -100,6 +125,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")
safResult?.success(uri.toString())
} catch (e: Exception) {
@@ -114,27 +141,36 @@ 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 被调用")
val result = mutableListOf<String>()
val docId = getTreeDocId()
if (docId == null || docId.isEmpty()) return result
android.util.Log.d("BatteryHealth", "docId = $docId")
if (docId == null || docId.isEmpty()) {
android.util.Log.e("BatteryHealth", "docId 为空")
return result
}
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}")
android.util.Log.e("BatteryHealth", "列出文件失败: ${e.message}", e)
}
return result
}
@@ -178,11 +214,9 @@ class MainActivity : FlutterActivity() {
return fileUri?.let { readFile(it) }
}
// ---------- Flutter 通道配置 ----------
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// 充电状态通道
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHARGE_CHANNEL)
.setMethodCallHandler { call, result ->
if (call.method == "getChargeState") {
@@ -205,7 +239,6 @@ class MainActivity : FlutterActivity() {
}
}
// SAF 通道
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, SAF_CHANNEL)
.setMethodCallHandler { call, result ->
when (call.method) {
@@ -233,7 +266,6 @@ class MainActivity : FlutterActivity() {
}
}
// 充电状态事件通道
EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL)
.setStreamHandler(
object : EventChannel.StreamHandler {