Base64 support for different API levels

白昼怎懂夜的黑 提交于 2020-08-02 05:38:33

问题


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?


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/47431337/base64-support-for-different-api-levels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!