How to combine the same code with the old and new APIs

Source: Internet
Author: User

In actual programming, if the code needs to consider the android1/2 API at the same time, how can we achieve compatibility in the same code?

 

In fact, there are good examples in the android2.2 Development Kit sample (/apidemos/src/COM/example/Android/APIs/APP/foregroundservice. Java.

 

Here, we mainly consider the newly added interfaces in the service class of Android 2.2.

Startforeground (int id, 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;        }

At the beginning, I was not very familiar with this Code. Why do I need to turn a bend and call it through reflection. The later code is clear, to be compatible with the android 1 code. That is, if mstartforeground/mstopforeground is null, it indicates the android1 environment.

 

 

This method is also frequently used in actual work, so that client code does not depend on APIs.

 

 

There is another problem here. If it is to determine whether the API has a newly added class, do not know whether this method is feasible?

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.