高低版本方法兼容

新的方法带来许多便利,但没法在低版本系统上运行,若是兼容性处理不恰当,APP在低版本系统上,运行时将会crash。java

本文以一个具体的例子说明如何在使用高API level的方法时处理好兼容性问题。android

例子:根据给出路径,获取此路径所在分区的总空间大小。ui

安卓中的文件存储使用参考中提到:this

获取文件系统用量状况,在API level 9及其以上的系统,可直接调用File对象的相关方法,如下需自行计算spa

通常实现

就此需求而言,API level 9及其以上,调用 File.getTotalSpace() 便可, 可是在API level 8 如下系统File对象并不存在此方法。.net

如如下方法:code

  
  
  
  
    
    
    
    
  1. { 
  2.     if (path == null) { 
  3.         return -1; 
  4.     } 
  5.     return path.getTotalSpace(); 
  6. }

/** * Returns the total size in bytes of the partition containing this path. * Returns 0 if this path does not exist. * @param path* @return -1 means path is null, 0 means path is not exist. */ public static long getTotalSpace(File path) 
处理没法编译经过

若是minSdkVersion设置为8,那么build时候会报如下错误:对象

  
  
  
  
    
    
    
    

Call requires API level 9 (current min is 8)

为了编译能够经过,能够添加 @SuppressLint("NewApi") 或者 @TargeApi(9)ip

@TargeApi($API_LEVEL)显式代表方法的API level要求,而不是@SuppressLint("NewApi");get

可是这样只是能编译经过,到了API level8的系统运行,将会引起 java.lang.NoSuchMethodError

正确的作法

为了运行时不报错, 须要:

  1. 判断运行时版本,在低版本系统不调用此方法
  2. 同时为了保证功能的完整性,须要提供低版本功能实现

    以下:

        
        
        
        
    /** * Returns the total size in bytes of the partition containing this path. * Returns 0 if this path does not exist. * * @param path * @return -1 means path is null, 0 means path is not exist. */@TargetApi(Build.VERSION_CODES.GINGERBREAD) // using @TargeApi instead of @SuppressLint("NewApi")@SuppressWarnings("deprecation")public static long getTotalSpace(File path) { if (path == null) { return -1; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { return path.getTotalSpace(); } // implements getTotalSpace() in API lower than GINGERBREAD else { if (!path.exists()) { return 0; } else { final StatFs stats = new StatFs(path.getPath()); // Using deprecated method in low API level system, // add @SuppressWarnings("description") to suppress the warning return (long) stats.getBlockSize() * (long) stats.getBlockCount(); } }}

总结

在使用高于minSdkVersion API level的方法须要:

  1. @TargeApi($API_LEVEL) 使能够编译经过, 不建议使用@SuppressLint("NewApi");
  2. 运行时判断API level; 仅在足够高,有此方法的API level系统中,调用此方法;
  3. 保证功能完整性,保证低API版本经过其余方法提供功能实现。
     


相关文章
相关标签/搜索