Giới thiệu
Giải mã Base64 ngược lại quá trình encode, chuyển chuỗi ASCII về dữ liệu gốc (text/binary). Android dùng Base64.decode() trả về byte[], sau đó chuyển về String bằng charset UTF-8.
Triển khai Encode + Decode
Bước 1: Tạo dự án
Android Studio → New Project → Empty Activity.
Bước 2: Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Nhập chuỗi gốc"
android:inputType="textMultiLine"
android:minHeight="80dp" />
<Button
android:id="@+id/buttonPanel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Encode & Decode" />
<TextView
android:id="@+id/text_encoded"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textSize="14sp"
android:textStyle="bold"
tools:text="Encoded: ..." />
<TextView
android:id="@+id/text_decoded"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#4CAF50"
tools:text="Decoded: ..." />
</LinearLayout>
Bước 3: MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
EditText editQuery;
TextView textEncoded, textDecoded;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editQuery = findViewById(R.id.edit_query);
textEncoded = findViewById(R.id.text_encoded);
textDecoded = findViewById(R.id.text_decoded);
findViewById(R.id.buttonPanel).setOnClickListener(v -> {
String input = editQuery.getText().toString();
if (input.isEmpty()) {
textEncoded.setText("Vui lòng nhập chuỗi");
textDecoded.setText("");
return;
}
// 1. ENCODE: String → Base64 String
String encoded = Base64.encodeToString(
input.getBytes(StandardCharsets.UTF_8),
Base64.NO_WRAP
);
textEncoded.setText("Encoded (Base64):\n" + encoded);
// 2. DECODE: Base64 String → String
try {
byte[] decodedBytes = Base64.decode(encoded, Base64.NO_WRAP);
String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
textDecoded.setText("Decoded (Original):\n" + decoded);
} catch (IllegalArgumentException e) {
textDecoded.setText("Lỗi decode: " + e.getMessage());
}
});
}
}
Chi tiết Base64.decode()
// Trả về byte[] byte[] decodedBytes = Base64.decode(encodedString, flags); // Flags phải KHỚP với khi encode: // - Nếu encode dùng NO_WRAP → decode dùng NO_WRAP // - Nếu encode dùng URL_SAFE → decode dùng URL_SAFE // - DEFAULT tương thích với DEFAULT/NO_WRAP
Xử lý lỗi thường gặp
| Lỗi | Nguyên nhân | Khắc phục |
|---|---|---|
| IllegalArgumentException: bad base-64 | Chuỗi không phải Base64 hợp lệ | Kiểm tra input, flag đúng |
| Ký tự lạ sau decode | Sai charset (mặc định platform) | Luôn dùng StandardCharsets.UTF_8 |
| Mất dữ liệu cuối | Thiếu padding '=' | Không dùng NO_PADDING khi encode, hoặc tự pad trước decode |
Decode Base64 thành Bitmap/Image
// Base64 String → Bitmap
String base64Image = "iVBORw0KGgoAAAANSUhEUg..."; // data:image/png;base64,...
// Bỏ prefix "data:image/png;base64," nếu có
if (base64Image.contains(",")) {
base64Image = base64Image.split(",")[1];
}
byte[] decodedBytes = Base64.decode(base64Image, Base64.NO_WRAP);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
imageView.setImageBitmap(bitmap);
Ứng dụng thực tế
- API Communication: Truyền binary (ảnh, file) trong JSON
- Auth Token: JWT, Basic Auth header
- Data URI: Embed ảnh nhỏ vào HTML/CSS
- SharedPreferences: Lưu byte[] dưới dạng String
- Deep Link/QR Code: Encode data phức tạp thành chuỗi
Quan trọng: Base64 KHÔNG phải mã hóa bảo mật (encryption). Ai cũng decode được. Cần bảo mật → dùng AES/SSL/TLS.