如何同一份代码兼顾新老的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中是否有新加入的类不知此方法是否可行?

 

 

 

 

你可能感兴趣的:(编程,android,工作)