In my Android app
build.gradle
android { compileSdkVersion 27 defaultConfig { minSdkVersion 16 targetSdkVersion 27 ... } .... }
Kotlin code
val data = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Base64.getDecoder().decode(str) } else { Base64.decode(str, Base64.DEFAULT) // Unresolved reference: decode }
Obviously, I got compilation error, when using Base64 variant prior to API 24.
But how can I support all the API levels and use Base64 as before 24, as after?
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.
The short answer is yes, unique binary/hex values will always encode to a unique base64 encoded string.
Although Base64 is a relatively efficient way of encoding binary data it will, on average still increase the file size for more than 25%. This not only increases your bandwidth bill, but also increases the download time.
Because the ASCII standard defines the use of seven bits, Base64 only uses 6 bits (corresponding to 2^6 = 64 characters) to ensure the encoded data is printable and none of the special characters available in ASCII are used. The algorithm's name Base64 comes from the use of these 64 ASCII characters.
Use android.util.Base64
will resolve your problem its available from API 8
data = android.util.Base64.decode(str, android.util.Base64.DEFAULT);
Example usage:
Log.i(TAG, "data: " + new String(data));
fun String.toBase64(): String { return String( android.util.Base64.encode(this.toByteArray(), android.util.Base64.DEFAULT), StandardCharsets.UTF_8 ) } fun String.fromBase64(): String { return String( android.util.Base64.decode(this, android.util.Base64.DEFAULT), StandardCharsets.UTF_8 ) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With