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? = null
override 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?> {
//项目内不要使用array
return resources.getTextArray(id)
}
override fun getStringArray(id: Int): Array<String?> {
//项目内不要使用array
return 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)
else
resources.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 null
handlerXmlText(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 = value
}
if (view is EditText) {
val 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)
if (view is EditText)
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中就创建完成
"com.xxx.ItemView" -> ItemView(context, attrs)
"com.xxx.SelectView" -> SelectView(context, attrs)
else -> null
}
}
}
最后把两种方式一块使用,然后就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
本文地址:https://blog.csdn.net/qq_33505109/article/details/112212969
上一篇: 急救课
下一篇: Servlet实现简单的用户登录功能