On Android 5.0 and below, sometimes the course not find method causes verifyerror, which leads to crash. The writing method is as follows:
As shown in the figure above, calling static method test1 on Android 4.4 mobile phone will report the following error:
10-28 16:02:40.913 2792-2792/com.example.myapplication I/dalvikvm: Could not find method com.bumptech.glide.Glide.with, referenced from method com.example.myapplication.TestKt.test2
10-28 16:02:40.913 2792-2792/com.example.myapplication W/dalvikvm: VFY: unable to resolve static method 4: Lcom/bumptech/glide/Glide;. with (Landroid/content/Context;)Lcom/bumptech/glide/RequestManager;
The reason is that Android 5 is a delvikvm virtual machine before, and then other static methods will be loaded when the static method is invoked. So when the test1 is called, the Glide in test2 will be loaded, but at this time it will be found that the with method can not find the method, so the problem can not be found, which will lead to the explosion of VerifyError error.
Solution: Although compileonly is intentionally written above, brand differentiation may occur on mobile phones of different brands, and then some brands do not rely on relevant classes to report errors. Therefore, you can change the places in test2 that need to be called to the dynamic loading mode, that is, the reflection mode, so that test2 will be loaded when test1 is called, However, the reflection method must be called to load the class, that is, the problem of calling test1 and then failing to find the method will not occur.
Examples of solutions are as follows:
public fun test2(context:Context) {
try {
Log.e("Test", "test1")
val clazz = Class.forName("com.bumptech.glide.Glide")
val getMethod: Method = clazz.getMethod("with", context.javaClass)
getMethod.invoke(null, context)
} catch (e: Exception) {
Log.e("Test","test1 e "+e.message)
}
}
Note: the above error is OK on Android 5.0 and above phones. It should be the difference between dalvikvm and artvm