Hook安卓项目内的字符串获取,用服务器的key value优先代替本地的key value
前言
前段時間接到一個需求,要動態的增加多語言語種,且可以動態更新用戶app上的不規范語言(比如一個英語過長導致按鈕內顯示不全)
服務端的邏輯和前端動態獲取的邏輯就不說了
修改app內的語言參考這篇安卓多語言設置,深淵巨坑,適配7.0以上,并且解決因WebView產生的問題
正文
首先確定一下安卓中有幾種獲取字符串的方式
1.Context#getResources().getString()
2.Context#getString()//其實內部還是用的上一種方式,只不過少寫了一點代碼
3.xml#android:text="@string/xxx"
那其實算下來只有兩種,一種是通過resources來獲取String,另一種是在xml解析的時候獲取String
第一種:通過包裝并攔截resources來Hook getString()
原理其實也很簡單:
通過觀察源碼,發現Context每次調用getString()之前都會先調用一下getResources(),這時只要重寫一下Application和BaseActivity的getResources(),返回自己包裝的resources,即可攔截到getString()方法,然后通過資源id獲取資源名,查找服務器返回的對應key的value,如果有就返回服務器的,沒有則使用應用自身的.
至于為什么不需要重寫BaseFragment和BaseDialog的,因為BaseFragment的getResources()會調用requireContext(),而requireContext()返回的Context對象就是附加到的Activity對象,所以不用設置,同理Dialog需要在構造的時候傳入Activity,so
ps:既然Fragment是每次調用getString()都會調用getContext(),那這樣在Fragment銷毀之后就不能調用getString()了,否則就會拋異常!
代碼如下:
BaseActivity為例:private var resources: Resources? = nulloverride fun getResources(): Resources {if (resources == null) {resources = LanguageResources(super.getResources())}return resources!!}資源包裝類LanguageResources如下:/*** creator: lt lt.dygzs@qq.com* 通過攔截appResources來攔截字符串*/class LanguageResources(val resources: Resources): Resources(resources.assets, resources.displayMetrics, resources.configuration) {override fun getText(id: Int): CharSequence {resources.getResourceEntryName(id)?.let { thisLanguageKVMap[it]?.let { return it } }return resources.getText(id)}override fun getText(id: Int, def: CharSequence?): CharSequence? {resources.getResourceEntryName(id)?.let { thisLanguageKVMap[it]?.let { return it } }return resources.getText(id, def)}override fun getString(id: Int): String {resources.getResourceEntryName(id)?.let { thisLanguageKVMap[it]?.let { return it } }return resources.getString(id)}override fun getString(id: Int, vararg formatArgs: Any?): String {resources.getResourceEntryName(id)?.let { thisLanguageKVMap[it]?.let { return it.format(*formatArgs) } }return resources.getString(id, *formatArgs)}override fun getTextArray(id: Int): Array<CharSequence?> {//項目內不要使用arrayreturn resources.getTextArray(id)}override fun getStringArray(id: Int): Array<String?> {//項目內不要使用arrayreturn resources.getStringArray(id)}override fun getQuantityText(id: Int, quantity: Int): CharSequence {return resources.getQuantityText(id, quantity)}override fun getQuantityString(id: Int, quantity: Int, vararg formatArgs: Any?): String {return resources.getQuantityString(id, quantity, *formatArgs)}override fun getQuantityString(id: Int, quantity: Int): String {return resources.getQuantityString(id, quantity)}override fun getIntArray(id: Int): IntArray {return resources.getIntArray(id)}override fun obtainTypedArray(id: Int): TypedArray {return resources.obtainTypedArray(id)}override fun getDimension(id: Int): Float {return resources.getDimension(id)}override fun getDimensionPixelOffset(id: Int): Int {return resources.getDimensionPixelOffset(id)}override fun getDimensionPixelSize(id: Int): Int {return resources.getDimensionPixelSize(id)}override fun getFraction(id: Int, base: Int, pbase: Int): Float {return resources.getFraction(id, base, pbase)}override fun getDrawable(id: Int): Drawable? {return resources.getDrawable(id)}@RequiresApi(21)override fun getDrawable(id: Int, theme: Theme?): Drawable? {return resources.getDrawable(id, theme)}override fun getDrawableForDensity(id: Int, density: Int): Drawable? {return resources.getDrawableForDensity(id, density)}@RequiresApi(21)override fun getDrawableForDensity(id: Int, density: Int, theme: Theme?): Drawable? {return resources.getDrawableForDensity(id, density, theme)}override fun getMovie(id: Int): Movie? {return resources.getMovie(id)}override fun getColor(id: Int): Int {return resources.getColor(id)}override fun getColorStateList(id: Int): ColorStateList {return resources.getColorStateList(id)}override fun getBoolean(id: Int): Boolean {return resources.getBoolean(id)}override fun getInteger(id: Int): Int {return resources.getInteger(id)}override fun getLayout(id: Int): XmlResourceParser {return resources.getLayout(id)}override fun getAnimation(id: Int): XmlResourceParser {return resources.getAnimation(id)}override fun getXml(id: Int): XmlResourceParser {return resources.getXml(id)}override fun openRawResource(id: Int): InputStream {return resources.openRawResource(id)}override fun openRawResource(id: Int, value: TypedValue?): InputStream {return resources.openRawResource(id, value)}override fun openRawResourceFd(id: Int): AssetFileDescriptor? {return resources.openRawResourceFd(id)}override fun getValue(id: Int, outValue: TypedValue?, resolveRefs: Boolean) {resources.getValue(id, outValue, resolveRefs)}override fun getValueForDensity(id: Int, density: Int, outValue: TypedValue?, resolveRefs: Boolean) {resources.getValueForDensity(id, density, outValue, resolveRefs)}override fun getValue(name: String?, outValue: TypedValue?, resolveRefs: Boolean) {resources.getValue(name, outValue, resolveRefs)}override fun obtainAttributes(set: AttributeSet?, attrs: IntArray?): TypedArray? {return resources.obtainAttributes(set, attrs)}override fun updateConfiguration(config: Configuration?, metrics: DisplayMetrics?) {if (resources == null)super.updateConfiguration(config, metrics)elseresources.updateConfiguration(config, metrics)}override fun getDisplayMetrics(): DisplayMetrics? {return resources.displayMetrics}override fun getConfiguration(): Configuration? {return resources.configuration}override fun getIdentifier(name: String?, defType: String?, defPackage: String?): Int {return resources.getIdentifier(name, defType, defPackage)}override fun getResourceName(resid: Int): String? {return resources.getResourceName(resid)}override fun getResourcePackageName(resid: Int): String? {return resources.getResourcePackageName(resid)}override fun getResourceTypeName(resid: Int): String? {return resources.getResourceTypeName(resid)}override fun getResourceEntryName(resid: Int): String? {return resources.getResourceEntryName(resid)}override fun parseBundleExtras(parser: XmlResourceParser?, outBundle: Bundle?) {resources.parseBundleExtras(parser, outBundle)}override fun parseBundleExtra(tagName: String?, attrs: AttributeSet?, outBundle: Bundle?) {resources.parseBundleExtra(tagName, attrs, outBundle)}@RequiresApi(Build.VERSION_CODES.M)override fun getColor(id: Int, theme: Theme?): Int {return resources.getColor(id, theme)}@RequiresApi(Build.VERSION_CODES.M)override fun getColorStateList(id: Int, theme: Theme?): ColorStateList {return resources.getColorStateList(id, theme)}@RequiresApi(Build.VERSION_CODES.O)override fun getFont(id: Int): Typeface {return resources.getFont(id)}@RequiresApi(Build.VERSION_CODES.Q)override fun getFloat(id: Int): Float {return resources.getFloat(id)}}簡單解釋一下:resources.getResourceEntryName()是通過id獲取對應的資源名,thisLanguageKVMap是從服務端獲取的多語言鍵值對HashMap(因為查找快),而我沒有攔截getStringArray()和getTextArray()是因為項目內只有一個地方用了,且多語言不好搞,且實現方式不同,我就給改成getString()的形式懶得去研究它了
ps:不能混淆資源名(騰訊的一個混淆資源框架),否則該方案無效
pps:順便吐槽一下,為啥kotlin的類委托只支持接口,不支持類..好坑,多寫了一堆模板代碼
第二種:通過攔截xml解析來Hook @string/
最開始我通過參考TextView的text獲取邏輯,然后找到TypedArray#getText(),然后發現傳進去的是個index,然后各種亂七八糟不熟悉的東西快給我繞暈了,果斷使用其他方案
然后我想起來前兩年有個很火的快捷開發的方案,通過攔截View生成來在xml中寫shape,當時我也模仿寫了個ShapeAndSelectUtil,用到的原理也是攔截LayoutInflater.Factory2,正好能用這個來攔截xml解析
原理:
通過攔截View的創建過程,拿到會用到@string/的View的對象(比如TextView和EditText或自定義View),獲取對應的id并重新從key value中獲取和設置
代碼如下:
//在BaseActivity的onCreate()中的super.onCreate()之前調用 layoutInflater.factory2 = LanguageLayoutInflaterFactory(this)/*** creator: lt lt.dygzs@qq.com*/ class LanguageLayoutInflaterFactory(val activity: Activity) : LayoutInflater.Factory2 {private val APP_KEY = "http://schemas.android.com/apk/res-auto"private val ANDROID_KEY = "http://schemas.android.com/apk/res/android"//sdk的activity使用的布局生成器private val delegate: AppCompatDelegate by lazy(LazyThreadSafetyMode.NONE) { AppCompatDelegate.create(activity, null) }//獲取默認的createView方法,可以在這里判斷并適配換膚框架等fun checkAndCreateView(parent: View?, name: String?, context: Context, attrs: AttributeSet): View? {return when (activity) {is AppCompatActivity -> activity.delegate.createView(parent, name, context, attrs)else -> delegate.createView(parent, name, context, attrs)}}override fun onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet): View? {return checkAndReturnView(name, context, attrs, checkAndCreateView(parent, name, context, attrs))}override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {return null}fun checkAndReturnView(name: String, context: Context, attrs: AttributeSet, view: View?): View? {val view = view ?: try {createViewGroup(name, context, attrs)} catch (e: Exception) {e.toString().e()null} ?: return nullhandlerXmlText(view, attrs)return view}private fun handlerXmlText(view: View, attrs: AttributeSet) {if (view is TextView) {val value = getStringValue(attrs, true, "text")if (value != null)view.text = valueval value = getStringValue(attrs, true, "hint")if (value != null)view.hint = value}//下面兩個是自定義View使用了@string/if (view is ItemView) {val value = getStringValue(attrs, false, "left_text")if (value != null)view.setLeftText(value)}if (view is SelectView) {val value = getStringValue(attrs, false, "middle_text")if (value != null)view.setMiddleText(value)}//或者下面這種寫法/*if (view is TextView) {getStringValue(attrs, true, "text")?.let(view::setText)getStringValue(attrs, true, "hint")?.let(view::setHint)}if (view is ItemView)getStringValue(attrs, false, "left_text")?.let(view::setLeftText)if (view is SelectView)getStringValue(attrs, false, "middle_text")?.let(view::setMiddleText)*/}private fun Int.toText() = activity.getString(this)private fun getStringValue(attrs: AttributeSet, isAndroidSystem: Boolean, valueName: String): String? {val value = attrs.getAttributeValue(if (isAndroidSystem) ANDROID_KEY else APP_KEY, valueName)if (value?.startsWith("@") == true)try {return value.substring(1).toIntOrNull()?.toText()} catch (e: Exception) {e.upload()}return null}private fun createViewGroup(name: String, context: Context, attrs: AttributeSet): View? {return when (name) {//下面兩個是自定義View使用了@string///且下面兩個是ViewGroup,如果是View則會在delegate中就創建完成//可能還需要加AppCompatTextView"com.xxx.ItemView" -> ItemView(context, attrs)"com.xxx.SelectView" -> SelectView(context, attrs)else -> null}//想省事的話直接全部生成://Class.forName(if (name.contains('.')) name else "android.widget.$name")// .getConstructor(Context::class.java, AttributeSet::class.java)// .newInstance(context, attrs) as View} }最后把兩種方式一塊使用,然后就ok了(應該不會有人只用xml或只用getString()吧)
擴展
多語言使用過程中可能會遇見類似阿拉伯語的從右往左的習慣,其文字也是從右往左看的,這時需要將類似paddingLeft和paddingRight改成paddingStart和paddingEnd,更多的多語言適配可以參考安卓官網:https://developer.android.com/training/basics/supporting-devices/languages?hl=zh-cn#kotlin
然后獲取是否是從左到右的api:
fun isLTR(context: Context): Boolean {return context.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_LTR}end
總結
以上是生活随笔為你收集整理的Hook安卓项目内的字符串获取,用服务器的key value优先代替本地的key value的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构特性解析 (四)LinkedLi
- 下一篇: 动手实现Kotlin协程同步切换线程,以