Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Đặt Large Icon thay vì Small Icon cho thông báo Android

Giới thiệu

Mặc định thông báo chỉ hiển thị Small Icon (24dp) ở góc trái. Bài này hướng dẫn dùng setLargeIcon() để hiển thị ảnh lớn (avatar, hình sản phẩm, logo) kích thước 64dp×64dp bên cạnh nội dung.

Sự khác biệt Small vs Large Icon

Đặc điểm Small Icon Large Icon
Kích thước 24dp × 24dp 64dp × 64dp (tròn hoặc vuông)
Vị trí Góc trái status bar & notification Bên trái nội dung, thay thế small icon trong notification shade
Bắt buộc Có Không (tùy chọn)
Dùng cho Logo app, biểu tượng đơn giản Avatar user, ảnh sản phẩm, ảnh bài viết
Tint color Hệ thống tự nhuộm Giữ nguyên màu gốc

Các bước thực hiện

Bước 1: Tạo dự án mới

Tạo project Android Studio mới.

Bước 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:onClick="createNotification"
        android:text="Tạo thông báo Large Icon" />

</RelativeLayout>

Bước 3: MainActivity với Large Icon (src/MainActivity.java)

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void createNotification(View view) {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            MainActivity.this, default_notification_channel_id);

        mBuilder.setContentTitle("Tiêu đề thông báo");
        mBuilder.setContentText("Nội dung kèm Large Icon");
        
        // QUAN TRỌNG: SET LARGE ICON TỪ DRAWABLE
        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground);
        mBuilder.setLargeIcon(largeIcon);
        
        // VẪN CẦN SMALL ICON CHO STATUS BAR
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        
        mBuilder.setAutoCancel(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(
                NOTIFICATION_CHANNEL_ID, "Kênh Large Icon", importance);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.notifyme">

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Large Icon từ nhiều nguồn

1. Từ Drawable Resource (như ví dụ trên)

Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);

2. Từ URL (cần load async - dùng Glide/Picasso/Coil)

// Ví dụ với Glide (trong coroutine/background thread)
Glide.with(context)
    .asBitmap()
    .load(imageUrl)
    .apply(new RequestOptions().override(64, 64))
    .into(new CustomTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
            builder.setLargeIcon(bitmap);
            notificationManager.notify(id, builder.build());
        }
        @Override
        public void onLoadCleared(Drawable placeholder) {}
    });

3. Từ File/Content Provider

Bitmap largeIcon = MediaStore.Images.Media.getBitmap(contentResolver, imageUri);

Tối ưu hiệu suất

  • Resize bitmap: Chỉ load kích thước 64×64dp, không load full rồi scale xuống
  • Cache: Cache bitmap nếu dùng lặp lại
  • Background thread: Không decode bitmap trên main thread
  • VectorDrawable: Không dùng trực tiếp, phải convert sang Bitmap trước
// Helper function tối ưu
private Bitmap getOptimizedLargeIcon(int drawableRes) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), drawableRes, options);
    
    options.inSampleSize = calculateInSampleSize(options, 64, 64);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(getResources(), drawableRes, options);
}

Chạy thử nghiệm

Chạy app → Nhấn nút → Kéo thanh thông báo → Thấy avatar/hình lớn 64dp bên trái nội dung, small icon vẫn ở status bar.

Đặt Large Icon thay vì Small Icon cho thông báo Android