在A(yíng)ndroid系統中向下兼容性比較差,但是一個(gè)應用APP經(jīng)過(guò)處理還是可以在各個(gè)版本間運行的。向下兼容性不好,不同版本的系統其API版本也不同,自然有些接口也不同,新的平臺不能使用舊的API,舊的平臺也使用不了新的API。
為了應用APP有更好的兼容性,咱們可以利用高版本的SDK開(kāi)發(fā)應用,并在程序運行時(shí)(Runtime)對應用所運行的平臺判斷,舊平臺使用舊的API,而新平臺可使用新的API,這樣可以較好的提高軟件兼容性。
那么,如何在軟件運行時(shí)做出這樣的判斷呢?答案下邊揭曉:
在A(yíng)ndroid SDK開(kāi)發(fā)文檔中有段話(huà)這樣的話(huà):
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 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 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為我們提供了一個(gè)常量類(lèi)Build,其中最主要是Build中的兩個(gè)內部類(lèi)VERSION和VERSION_CODES,
VERSION表示當前系統版本的信息,其中就包括SDK的版本信息,用于成員SDK_INT表示;
對于VERSION_CODES在SDK開(kāi)發(fā)文檔中時(shí)這樣描述的,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.
其成員就是一些從最早版本開(kāi)始到當前運行的系統的一些版本號常量。
在我們自己開(kāi)發(fā)應用過(guò)程中,常常使用如下的代碼形式判斷運行新API還是舊的API:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // 包含新API的代碼塊 } else { // 包含舊的API的代碼塊 }OK,大家都知道原理了吧! 需要實(shí)例的百度蠻多的,這里就不提供了。
聯(lián)系客服