Android不同版本間兼容性處理
來自: http://www.jcodecraeer.com//a/anzhuokaifa/androidkaifa/2014/0523/1619.html
在Android系統中向下兼容性比較差,但是一個應用APP經過處理還是可以在各個版本間運行的。向下兼容性不好,不同版本的系統其API版本也不同,自然有些接口也不同,主要是舊的平臺使用不了新的API。
但這并不代表每個平臺都需要一個單獨的apk,也不代表使用了新sdk的apk在低版本系統手機上不能運行。可以在高SDK上開發,并在程序中作版本判斷,低版本運行環境使用舊的API
那么,如何在軟件運行時做出這樣的判斷呢?
在Android SDK開發文檔中有段話這樣的話:
在運行時檢查系統版本
Android provides a unique code for each platform version in theBuild
constants class. Use these codes within your app to build conditions that ensure the code that depends on higher API levels is executed only when those APIs are available on the system.
privatevoid setUpActionBar(){// Make sure we're running on Honeycomb or higher to use ActionBar APIsif(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB){ ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true);}}
Note: When parsing XML resources, Android ignores XML attributes that aren’t supported by the current device. So you can safely use XML attributes thatare only supported by newer versions without worrying about older versions breaking when theyencounter that code. For example, if you set thetargetSdkVersion="11"
, your app includes the ActionBar
by defaulton Android 3.0 and higher. To then add menu items to the action bar, you need to setandroid:showAsAction="ifRoom"
in your menu resource XML. It's safe to do this in a cross-version XML file, because the older versions of Android simply ignore theshowAsAction
attribute (that is, you do not need a separate version inres/menu-v11/
).
從上面可以知道Android為我們提供了一個常量類Build,其中最主要是Build中的兩個內部類VERSION和VERSION_CODES,
VERSION表示當前系統版本的信息,其中就包括SDK的版本信息,用于成員SDK_INT表示;
對于VERSION_CODES在SDK開發文檔中時這樣描述的,Enumeration of the currently known SDK version codes. These are the values that can be found inSDK. Version numbers increment monotonically with each official platform release.
其成員就是一些從最早版本開始到當前運行的系統的一些版本號常量。
在我們自己開發應用過程中,常常使用如下的代碼形式判斷運行新API還是舊的API:
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB){ // 包含新API的代碼塊 }else{ // 包含舊的API的代碼塊 }