android verify error

来源:互联网 发布:ubuntu什么系统 编辑:程序博客网 时间:2024/05/16 16:57

android高版本api导致低版本手机出现VerifyError

android api从1.1(SDK 2) 到现在4.4(SDK 19) 变化还是很大的,最近在做一个游戏升级,遇到了VerifyError,顺手做个记录。
一般做法是先判断一下当前系统sdk版本来确定是否使用高版本api,比如:
MenuItem menu1=menu.add(0, MENU_NEW_GAME, 0, R.string.menu_new_game);if(sdk >=11)    menu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
这里setShowAsAction是API level 11加入的方法
在android 1.5手机运行后出现:
W/dalvikvm( 9179): threadid=3: thread exiting with uncaught exception (group=0x40013140)E/AndroidRuntime( 9179): Uncaught handler: thread main exiting due to uncaught exceptionE/AndroidRuntime( 9179): java.lang.VerifyError: com.shootbubble.bubbledexlue.MainActivityE/AndroidRuntime( 9179): at java.lang.Class.newInstanceImpl(Native Method)E/AndroidRuntime( 9179): at java.lang.Class.newInstance(Class.java:1472)E/AndroidRuntime( 9179): at android.app.Instrumentation.newActivity(Instrumentation.java:1100)E/AndroidRuntime( 9179): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)E/AndroidRuntime( 9179): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284)E/AndroidRuntime( 9179): at android.app.ActivityThread.access$1800(ActivityThread.java:112)E/AndroidRuntime( 9179): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)E/AndroidRuntime( 9179): at android.os.Handler.dispatchMessage(Handler.java:99)E/AndroidRuntime( 9179): at android.os.Looper.loop(Looper.java:123)E/AndroidRuntime( 9179): at android.app.ActivityThread.main(ActivityThread.java:3948)E/AndroidRuntime( 9179): at java.lang.reflect.Method.invokeNative(Native Method)E/AndroidRuntime( 9179): at java.lang.reflect.Method.invoke(Method.java:521)E/AndroidRuntime( 9179): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)E/AndroidRuntime( 9179): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)E/AndroidRuntime( 9179): at dalvik.system.NativeStart.main(Native Method)
可以看出if没有起到效果,看了网上一些分析,在stackoverflow上看到
When Dalvik compiles your class/function from bytecode into native machine code, it compiles all statements, even those that are inside if conditions. On Android 1.6 virtual machine tries to resolve (verify) getActionBar function, and since there is no such function, Dalvik throws VerifyError
也就是说虚拟机在第一次加载类的时候还是会verify if的每一个分支,具体解决思路就是避免在加载时检查,到运行时再通过if判定是否执行,一般有以下两种方式:
1.内部类
if(sdk >= 11)    new Object() {public void function(MenuItem m) {    m.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);}    }.function(menu1);

2.反射
if(sdk >=11) {    Class<?> refelct_class = null;    refelct_class = Class.forName("android.view.MenuItem");    Method m = refelct_class.getMethod("setShowAsAction", int.class);    m.invoke(menu1, MenuItem.SHOW_AS_ACTION_IF_ROOM);}

内容参考:参考