如何同一份代码兼顾新老的API

实际编程中如果代码需要同时考虑Android1/2的API时,如何在同一份代码中做到兼容?

 

其实在Android2.2的开发包Sample (/ApiDemos/src/com/example/android/apis/app/ForegroundService.java)中就有很好的例子。

 

此处主要考虑Android 2.2中 Service类中新添加的接口

startForeground(int id, Notification notification)

stopForeground(boolean removeNotification)

 

 

        try {
            mStartForeground = getClass().getMethod("startForeground",
                    mStartForegroundSignature);
            mStopForeground = getClass().getMethod("stopForeground",
                    mStopForegroundSignature);
        } catch (NoSuchMethodException e) {
            // Running on an older platform.
            mStartForeground = mStopForeground = null;
        }

  

开始时对这段代码不是很理解,为什么明明可以直接调用还要拐一个弯,通过反射来调用。看到后来的代码明白了,为了兼容Android1的代码。即如果mStartForeground / mStopForeground  为空就表示是Android1的环境。

 

 

该种方法在实际工作中也经常用到,可以让客户端代码不要显示依赖于API。

 

 

在此有另一个问题,如果是判断API中是否有新加入的类不知此方法是否可行?

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值