Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 support for different API levels

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?

like image 976
Alexey Avatar asked Nov 22 '17 09:11

Alexey


People also ask

What is Base64 in API?

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.

Is Base64 encoding always the same?

The short answer is yes, unique binary/hex values will always encode to a unique base64 encoded string.

Is Base64 encoding efficient?

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.

Why is Base64 6 bit?

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.


2 Answers

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)); 
like image 151
Abhishek Singh Avatar answered Oct 19 '22 21:10

Abhishek Singh


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     ) } 
like image 33
norbDEV Avatar answered Oct 19 '22 23:10

norbDEV