1.Setting the minSdkVersion
設置最小支持的sdk
<manifest>
...
<uses-sdkandroid:minSdkVersion="3"/>
...
</manifest>
2.Using reflection
使用反射檢測要 使用的類 在當前運行環境下 是否有須要調用的屬性或方法。
like
android.os.Debug.dumpHprofData(String filename)
. The
Debug
class has existed since Android 1.0, but the method is new in Anroid 1.5 (API Level 3). If you try to call it directly, your app will fail to run on devices running Android 1.1 or earlier.
public class Reflect{
private static Method mDebug_dumpHprofData;
static{
initCompatibility();
};
private static void initCompatibility(){
try{
mDebug_dumpHprofData =Debug.class.getMethod(
"dumpHprofData",newClass[]{String.class});
/* success, this is a newer device */
}catch(NoSuchMethodException nsme){
/* failure, must be older device */
}
}
private static void dumpHprofData(String fileName)throws IOException{
try{
mDebug_dumpHprofData.invoke(null, fileName);
}catch(InvocationTargetException ite){
/* unpack original exception when possible */
Throwable cause = ite.getCause();
if(cause instanceof IOException){
throw(IOException) cause;
}else if(cause instanceofRuntimeException){
throw(RuntimeException) cause;
}else if(cause instanceofError){
throw(Error) cause;
}else{
/* unexpected checked exception; wrap and re-throw */
thrownewRuntimeException(ite);
}
}catch(IllegalAccessException ie){
System.err.println("unexpected "+ ie);
}
}
public void fiddle(){
if(mDebug_dumpHprofData !=null){
/* feature is supported */
try{
dumpHprofData("/sdcard/dump.hprof");
}catch(IOException ie){
System.err.println("dump failed!");
}
}else{
/* feature not supported, do something else */
System.out.println("dump not supported");
}
}
}
3.Using a wrapper class
使用一個包裹類。
public class NewClass{
private static int mDiv =1;
private int mMult;
public static void setGlobalDiv(int div){
mDiv = div;
}
public NewClass(int mult){
mMult = mult;
}
public int doStuff(int val){
return(val * mMult)/ mDiv;
}
}
包裹類:
class WrapNew Class{
private NewClass mInstance;
/* class initialization fails when this throws an exception */
static{
try{
Class.forName("NewClass");
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
/* calling here forces class initialization */
public static void checkAvailable(){}
public static void setGlobalDiv(int div){
NewClass.setGlobalDiv(div);
}
public WrapNewClass(int mult){
mInstance =new NewClass(mult);
}
public int doStuff(int val){
return mInstance.doStuff(val);
}
}
4.Testing is key
進行完整的sdk測試