当前位置: 移动技术网 > IT编程>移动开发>Android > Android 高版本API方法在低版本系统上的兼容性处理

Android 高版本API方法在低版本系统上的兼容性处理

2019年07月24日  | 移动技术网IT编程  | 我要评论

刘习全,黄有泉,怎样治疗生殖器疱疹

android 版本更替,新的版本带来新的特性,新的方法。

新的方法带来许多便利,但无法在低版本系统上运行,如果兼容性处理不恰当,app在低版本系统上,运行时将会crash。

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

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

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

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

一般实现

就此需求而言,api level 9及其以上,调用 file.gettotalspace() 即可, 但是在api level 8 以下系统file对象并不存在此方法。

如以下方法:

/**
 * 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) {
  if (path == null) {
    return -1;
  }
  return path.gettotalspace();
}

处理无法编译通过

如果minsdkversion设置为8,那么build时候会报以下错误:

call requires api level 9 (current min is 8)

为了编译可以通过,可以添加 @suppresslint("newapi") 或者 @targeapi(9)。

用@targeapi($api_level)显式表明方法的api level要求,而不是@suppresslint("newapi");

但是这样只是能编译通过,到了api level8的系统运行,将会引发 java.lang.nosuchmethoderror。

正确的做法

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

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

如下:

/**
 * 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版本通过其他方法提供功能实现。

通过此文希望能帮助到您,解决android版本api兼容性问题!谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网