2

我正在尝试使用反射加载 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();

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

4

2 回答 2

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();
}
于 2013-07-26T05:44:36.713 回答
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,即使在 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;
  }
}
于 2014-03-13T16:10:07.967 回答