安卓&调用当前 API 没有的方法 [英] Android & calling methods that current API doesnt have

查看:33
本文介绍了安卓&调用当前 API 没有的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想获得这样的外部路径,并且设备有 Android 2.1 (api 7)

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 将显示:

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;

,但应用程序不会粉碎.我想知道什么是VFY?虚拟机dalvik中是否有一些东西可以检查被调用方法中的代码是否有效?因为当前的项目是针对 Android 2.2 重新编译的,所以 Eclipse 没有抱怨......但是在运行时,我得到了 LogCat 条目

, 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:我真的不使用这样的方法,我有一个 Helper 类,它为 API<=7 或另一个为 API>=8 初始化一个类......但仍然请回答!

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!

推荐答案

是的,VFY 错误是从 dalvik 中的 dex 验证器记录的.

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

您遇到此问题是因为您正在对 SDK 版本执行运行时检查并调用 API 方法.问题是,即使方法调用位于 if(){} 块内,该块可能永远不会在较低的 API 级别执行,符号信息也存在于生成的字节码中.如果需要执行平台特定的函数调用,则需要使用反射.

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();
}

这篇关于安卓&amp;调用当前 API 没有的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆