Base64 support for different API levels

Viewed 30408

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?

4 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));
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
    )
}

You should be using the android.util.Base64 class. It is supported from API 8,

The Base64.getDecoder() function is part of java.util.Base64 and new in Java8.

private String encodeFromImage() {
        String encode = null;
        if (imageView.getVisibility() == View.VISIBLE) {
            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            //encode = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
            //String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap,"Title",null);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                encode = Base64.getEncoder().encodeToString(stream.toByteArray());
            } else {
                encode = android.util.Base64.encodeToString(stream.toByteArray(), android.util.Base64.DEFAULT);
            }
        }
        return encode;
    }
Related