11package com.omarea.common.shell
22
33import android.content.Context
4- import android.content.res.Configuration
5- import android.content.res.Resources
6- import java.io.File
7- import java.util.Locale
4+ import com.tool.tree.LanguageManager
85
96// 从Resource解析字符串,实现输出内容多语言
10- class ShellTranslation (val context : Context ) {
7+ class ShellTranslation (private val context : Context ) {
8+
119 // 示例:
1210 // @string:home_shell_01
1311 private val resRegex =
14- Regex (" @(string|dimen)[:/][_a-z][_0-9a-z]*" , RegexOption .IGNORE_CASE )
15-
16- private val appResources: Resources by lazy {
17- runCatching {
18- val langFile = File (context.filesDir, " home/usr/log/language" )
19- val lang = langFile
20- .takeIf { it.exists() }
21- ?.readText()
22- ?.trim()
23- ?.takeIf { it.isNotEmpty() }
24- ? : return @runCatching context.resources
25- val locale = Locale .forLanguageTag(lang.replace(" _" , " -" ))
26- val config = Configuration (context.resources.configuration)
27- config.setLocale(locale)
28- context.createConfigurationContext(config).resources
29- }.getOrElse {
30- context.resources
31- }
32- }
12+ Regex (" @(string|dimen)[:/][_a-z][_0-9a-z]*" , RegexOption .IGNORE_CASE )
3313
3414 fun resolveRow (originRow : String ): String? {
3515 var result = originRow
36- val res = appResources
16+ val res = LanguageManager .resources(context)
17+
3718 resRegex.findAll(originRow).forEach { match ->
38- val row = match.value // @string:notification_ui
19+ val row = match.value
3920 val separator = if (row.contains(" :" )) ' :' else ' /'
4021 val type = row.substring(1 , row.indexOf(separator))
4122 val name = row.substring(row.indexOf(separator) + 1 )
42-
23+
4324 val id = res.getIdentifier(name, type, context.packageName)
4425 if (id != 0 ) {
4526 val value = when (type) {
@@ -58,10 +39,10 @@ class ShellTranslation(val context: Context) {
5839 fun resolveRows (rows : List <String >): String {
5940 val builder = StringBuilder ()
6041 var first = true
61-
42+
6243 for (row in rows) {
6344 val resolved = resolveRow(row) ? : continue
64-
45+
6546 if (! first) {
6647 builder.append(' \n ' )
6748 }
@@ -72,7 +53,7 @@ class ShellTranslation(val context: Context) {
7253 }
7354
7455 fun getTranslatedResult (shellCommand : String , executor : KeepShell ? ): String {
75- val shell = executor? : KeepShellPublic .getDefaultInstance()
56+ val shell = executor ? : KeepShellPublic .getDefaultInstance()
7657 val rows = shell.doCmdSync(shellCommand).split(" \n " )
7758 return if (rows.isNotEmpty()) {
7859 resolveRows(rows)
0 commit comments