在 android 2.1(api 7)中,`string.tobytearray(charset)` 不可用,会抛出 `nosuchmethoderror`;应改用 `string.getbytes(string charsetname)` 方法,并捕获 `unsupportedencodingexception`,确保向后兼容。
Android 2.1(即 API Level 7)是较早期的 Android 版本,其 java.lang.String 类尚未支持 Java N

✅ 正确且兼容 API 1+ 的写法如下(Java 风格,Kotlin 中同样适用):
val string = "string"
val bytes: ByteArray
try {
bytes = string.getBytes("UTF-8") // 使用字符串形式的字符集名
} catch (e: UnsupportedEncodingException) {
// UTF-8 在所有 Android 版本中均受强制支持,此异常理论上不会发生,但编译器要求处理
throw RuntimeException("UTF-8 not supported", e)
}⚠️ 注意事项:
fun String.toUtf8Bytes(): ByteArray = try {
getBytes("UTF-8")
} catch (e: UnsupportedEncodingException) {
throw RuntimeException(e) // 安全兜底:UTF-8 不可能不支持
}总结:面向低版本 Android(尤其是 API ≤ 7)开发时,应放弃 Charset 对象和 Kotlin 扩展函数的“现代语法”,回归 String.getBytes(String charsetName) 这一最广泛兼容的 API,兼顾健壮性与最小化兼容成本。