NoSuchMethodException使用反射加载Build.getRadioVersion()

时间:2013-07-26 04:28:47

标签: java android reflection

我正在尝试使用反射加载Android设备的广播版本。我需要这样做,因为我的SDK支持API 7,但在API 8中添加了Build.RADIO,在API 14中添加了Build.getRadioVersion()。

// This line executes fine, but is deprecated in API 14
String radioVersion = Build.RADIO;

// This line executes fine, but is deprecated in API 14
String radioVersion = (String) Build.class.getField("RADIO").get(null);

// This line executes fine.
String radioVersion = Build.getRadioVersion();

// This line throws a MethodNotFoundException.
Method method = Build.class.getMethod("getRadioVersion", String.class);
// The rest of the attempt to call getRadioVersion().
String radioVersion = method.invoke(null).toString();

我可能在这里做错了什么。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

try {
    Method getRadioVersion = Build.class.getMethod("getRadioVersion");
    if (getRadioVersion != null) {
        try {
            String version = (String) getRadioVersion.invoke(Build.class);
            // Add your implementation here
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        Log.wtf(TAG, "getMethod returned null");
    }
} catch (NoSuchMethodException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

答案 1 :(得分:1)

Build.getRadioVersion()实际做的是返回gsm.version.baseband系统属性的值。查看BuildTelephonyProperties来源:

static final String PROPERTY_BASEBAND_VERSION = "gsm.version.baseband";

public static String getRadioVersion() {
    return SystemProperties.get(TelephonyProperties.PROPERTY_BASEBAND_VERSION, null);
}

根据AndroidXref,此属性为available even in API 4。因此,您可以通过SystemProperties使用反射在任何版本的Android上获取它:

public static String getRadioVersion() {
  return getSystemProperty("gsm.version.baseband");
}


// reflection helper methods

static String getSystemProperty(String propName) {
  Class<?> clsSystemProperties = tryClassForName("android.os.SystemProperties");
  Method mtdGet = tryGetMethod(clsSystemProperties, "get", String.class);
  return tryInvoke(mtdGet, null, propName);
}

static Class<?> tryClassForName(String className) {
  try {
    return Class.forName(className);
  } catch (ClassNotFoundException e) {
    return null;
  }
}

static Method tryGetMethod(Class<?> cls, String name, Class<?>... parameterTypes) {
  try {
    return cls.getDeclaredMethod(name, parameterTypes);
  } catch (Exception e) {
    return null;
  }
}

static <T> T tryInvoke(Method m, Object object, Object... args) {
  try {
    return (T) m.invoke(object, args);
  } catch (InvocationTargetException e) {
    throw new RuntimeException(e.getTargetException());
  } catch (Exception e) {
    return null;
  }
}