標籤:
在Android系統中向下相容性比較差,但是一個應用APP經過處理還是可以在各個版本間啟動並執行。向下相容性不好,不同版本的系統其API版本也不同,自然有些介面也不同,新的平台不能使用舊的API,舊的平台也使用不了新的API。
為了應用APP有更好的相容性,咱們可以利用高版本的SDK開發應用,並在程式運行時(Runtime)對應用所啟動並執行平台判斷,舊平台使用舊的API,而新平台可使用新的API,這樣可以較好的提高軟體相容性。
那麼,如何在軟體運行時做出這樣的判斷呢?答案下邊揭曉:
在Android SDK開發文檔中有段話這樣的話:
Check System Version at Runtime(在軟體運行時檢查判斷系統版本)
Android provides a unique code for each platform version in the Build constants class. Use these codes within your app to build conditions that ensure the code thatdepends on higher API levels is executed only when those APIs are available on the system.
private void setUpActionBar() { // Make sure we‘re running on Honeycomb or higher to use ActionBar APIs if (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 the targetSdkVersion="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 set android: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 the showAsAction attribute (that is, you do not need a separate version in res/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 in SDK. Version numbers increment monotonically with each official platform release.
其成員就是一些從最早版本開始到當前啟動並執行系統的一些版本號碼常量。
在我們自己開發應用過程中,常常使用如下的代碼形式判斷運行新API還是舊的API:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // 包含新API的代碼塊 } else { // 包含舊的API的代碼塊 }
OK,大家都知道原理了吧! 需要執行個體的百度蠻多的,這裡就不提供了。
原文:http://blog.csdn.net/leichelle/article/details/7988561
android應用的不同版本間相容性處理