Android开发中MinSDK与TargetSDK不在同一个版本时,如何很好的兼容新版本中的API

AndroidManifest.xml 中会有一项配置指定当前编译所用的sdk版本及向前兼容的SDK的最小版本:

<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" />

首先解释一下Min SDK 与 Target SDK分别的作用。主要是针对一些版本敏感的(即旧版本中没有,新版本中加入的)API起作用。

Target SDK:是指定当前的程序使用哪个Level的API进行编译及运行,API level也就对应了SDK的版本,例如,指定API Level为19,则运行在SDK4.4(kitkat),则该版本下定 义的所有的API在程序中是可以访问的。

Min SDK:是真当前的程序要不要向旧版本的SDK兼容,如果两个值设成一样的,说明无需兼容。但是,比如Min SDK设为11 (android3.0 honeycomb),则如果在程序中调用了level11中还没有存在的API,IDE会报一个提示,但依然可以运行,因为设了min sdk即告诉系统我知道自己的程序最低会运行在3.0版本,我调用API的时候会在程序中处理版本兼容问题。但如果程序运行时调用到的API在当前程序运行的系统版本中并没有定义的话,就会导致如下异常。

E/dalvikvm(  792): Could not find method android.view.MotionEvent.getX, referenced from method com.example.android.touchexample.TouchExampleView.onTouchEvent
W/dalvikvm(  792): VFY: unable to resolve virtual method 17: Landroid/view/MotionEvent;.getX (I)F
W/dalvikvm(  792): VFY:  rejecting opcode 0x6e at 0x0006
W/dalvikvm(  792): VFY:  rejected Lcom/example/android/touchexample/TouchExampleView;.onTouchEvent (Landroid/view/MotionEvent;)Z
W/dalvikvm(  792): Verifier rejected class Lcom/example/android/touchexample/TouchExampleView;
D/AndroidRuntime(  792): Shutting down VM
W/dalvikvm(  792): threadid=3: thread exiting with uncaught exception (group=0x4000fe70)

同时用户也会看到错误提示框。

如何在程序中解决版本敏感的API导致的以上错误呢?

方法一:直接在调用API的位置check当前版本

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

方法二:定义一个抽象类,可以有多个版本的实现类。提供工厂方法,根据当前环境决定实例化哪个子类。

public static VersionedGestureDetector newInstance(Context context,
        OnGestureListener listener) {
    final int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
    VersionedGestureDetector detector = null;
    if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
        detector = new CupcakeDetector();
    } else if (sdkVersion < Build.VERSION_CODES.FROYO) {
        detector = new EclairDetector();
    } else {
        detector = new FroyoDetector(context);
    }

    detector.mListener = listener;

    return detector;
}

方法二详见Android Develpers Blog中的一篇文章,http://android-developers.blogspot.com/2010/07/how-to-have-your-cupcake-and-eat-it-too.html










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值