Android & calling methods that current API doesnt have

梦想与她 提交于 2019-12-13 04:44:40

问题


If i want to get the external path like this, and device has Android 2.1 (api 7)

        File f;
        int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
        if (sdkVersion >= 8) {
            System.out.println(">=8");
            f = getApplicationContext().getExternalFilesDir(null);
        } else {
            System.out.println("<=7");
            f = Environment.getExternalStorageDirectory();
        }

LogCat will display:

05-25 15:44:08.355: W/dalvikvm(16688): VFY: unable to resolve virtual method 12: Landroid/content/Context;.getExternalFilesDir (Ljava/lang/String;)Ljava/io/File;

, but app will not crush. I want to know what is VFY? Is there something in the virtual machine dalvik that checks if code inside a called method is valid? Because current proj was compiled agains Android 2.2 so Eclipse didn't complained.. but at runtime, i get LogCat entry

PS: i dont use method like this in really, i have Helper class which initialises a class for API<=7 or another for API>=8.. but still please answer!


回答1:


Yes, VFY errors are logged from dex verifier in dalvik.

You are facing this issue because you are performing runtime checks for the SDK version and calling the API methods. The problem is even if the method call is inside the if(){} block which may never be executed in lower API levels, the symbolic information is present in the generated bytecode. If you need to perform platform specific function calls, you need to use reflection.

File f;
int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion >= 8) {
    System.out.println(">=8");
    try {
        Method getExternalFilesDir = Context.class.getMethod("getExternalFilesDir",  new Class[] { String.class } );
        f = (File)getExternalFilesDir.invoke(getApplicationContext(), new Object[]{null});                  
    } catch (Exception e) {
        e.printStackTrace();
    } 

} else {
    System.out.println("<=7");
    f = Environment.getExternalStorageDirectory();
}


来源:https://stackoverflow.com/questions/10929546/android-calling-methods-that-current-api-doesnt-have

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!