2011-02-02 192 views
7

我開發使用Android的向後代碼兼容性

android.hardware.Camera.parameters.getSupportedPictureSizes()

這隻能從SDK版本8,我想一個應用程序後與SDK 4兼容,所以我這樣做:

如果(Build.VERSION.SDK_INT> = 8){...}

但在模擬器上,它煤層,它試圖檢查參考這個功能,它失敗:

11月2日至2日:20:10.930:ERROR/dalvikvm(1841):找不到方法android.hardware.Camera $ Parameters.getSupportedPictureSizes,從方法com.test.demo.CameraCustom.takeAPicture

有關如何解決這個向後兼容性問題的任何想法引用?

我試着用這段代碼在surfaceChanged裏面使用這個代碼。顯然,代碼工作的情況下直接invokation:

try{ 
    windowmanager_defaultdisplay_Rotation = getWindowManager().getDefaultDisplay().getClass().getMethod("getRotation"); 
    Log.v(MainMenu.TAG, "getRotation exist"); 
}catch(Exception e){ 
    Log.v(MainMenu.TAG, "getRotation dont exist"); 
} 

try{ 
    windowmanager_defaultdisplay_Rotation.invoke(null, null); 
    Log.v(MainMenu.TAG, "getRotation invoking ok, rotation "); 
}catch(Exception e){ 
    Log.v(MainMenu.TAG, "exception invoking getRotation "+e.toString()); 
} 

我得到「getRotation存在」但隨後「異常調用getRotation顯示java.lang.NullPointerException

任何想法

回答

5

不能加載包含的代碼?因此,您需要根據Build之前的決定,在之前加載包含版本相關語句的代碼。

您的選項包括:

  • 禁用菜單選項,按鈕,或任何導致使用getSupportedPictureSizes()活動,基於API級別
  • 使用條件的類加載或類似的技術來加載基於一個合適的實現在API級別,這裏的「合適的實現」僅API級採用getSupportedPictureSizes() 8或更高

後一種技術的例子可以看出,在this sample project,其中I支持API級9朝前相機,但仍舊可以跑老Android的呃版本。

+0

是的,我認爲我應該這樣做:http://developer.android.com/resources/articles/backward-compatibility.html,謝謝! – zegnus 2011-02-02 16:24:58

3

好的,Commonsware提供的答案是正確的,特別是如果你研究他提供的優秀示例項目。此外,zegnus是在正確的軌道上時,他指出, http://developer.android.com/resources/articles/backward-compatibility.html

的關鍵,這雖然,這是不是從對方的回答清楚的,就是你需要支持,你需要的功能的API進行編譯。否則你會得到錯誤。在Commonsware的示例中,前向攝像頭首先在API級別9中得到支持,這是您必須在項目中指定才能進行編譯的內容。然後,您可以使用上述其他技術來測試應用程序運行的操作系統是否實際支持您嘗試使用的類和/或方法。如果您的應用程序在較早版本的操作系統上運行,則這些調用將生成一個異常,您可以捕獲該異常併爲舊操作系統採取適當的操作。

爲了完整起見,以下是我曾經與API 7兼容的代碼,即使我使用包含ThumbnailUtils的API 8進行編譯。

import com.Flashum.util.WrapThumbnailUtils; 

    public static Bitmap createVideoThumbnail(String filePath, int kind) { 
     try { 
     WrapThumbnailUtils.checkAvailable(); // will cause exception if ThumbnailUtils not supported 
     return WrapThumbnailUtils.createVideoThumbnail(filePath, kind); 
     } catch (Exception e) { 
     return null; 
     } 
    } 

package com.Flashum.util; 

import android.graphics.Bitmap; 
import android.media.ThumbnailUtils; 

// To be compatible with Android 2.1 need to create 
// wrapper class for WrapThumbnailUtils. 
public class WrapThumbnailUtils { 
    /* class initialization fails when this throws an exception */ 
    static { 
     try { 
     Class.forName("android.media.ThumbnailUtils"); 
     } catch (Exception ex) { 
     throw new RuntimeException(ex); 
     } 
    } 

    /* calling here forces class initialization */ 
    public static void checkAvailable() {} 

    public static Bitmap createVideoThumbnail(String filePath, int kind) { 
     return ThumbnailUtils.createVideoThumbnail(filePath, kind); 
    } 
}