Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตั้งค่า Notification Icon ใน Android

ภาพรวม

Notification Icon (Small Icon) เป็นสิ่งสำคัญที่สุดของ Notification เพราะแสดงใน Status Bar, Notification Shade และ Lockscreen Android กำหนดข้อกำหนดเข้มงวดสำหรับ Icon เพื่อความสอดคล้องทาง UI

ข้อกำหนดของ Notification Icon

คุณสมบัติข้อกำหนด
**รูปแบบ**PNG (แนะนำ) หรือ XML Vector Drawable
**สี**ขาวเพียงสีเดียว (White only) + Alpha transparency
**พื้นหลังโปร่งใส (Transparent background)
**ขนาด**24x24 dp (mdpi), 36x36 (hdpi), 48x48 (xhdpi), 72x72 (xxhdpi), 96x96 (xxxhdpi)
**Safe Zone**เนื้อหาอยู่ในวงกลม 20x20 dp (mdpi) ไม่ให้ชิดขอบ
⚠️ สำคัญ: หากใช้ Icon หลายสี หรือมีพื้นหลัง Android จะแสดงเป็น **สีขาวทึบ (Silhouette)** ตั้งแต่ Android 5.0 (Lollipop) เป็นต้นมา

ตัวอย่าง: ตั้งค่า Icon ใน Notification

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → New Project → Empty Activity (Package: app.tutorialspoint.com.notifyme)

ขั้นตอนที่ 2: เพิ่ม Icon Resource

**วิธีที่ 1: ใช้ Vector Asset (แนะนำ)**

  1. Right-click res → New → Vector Asset
  2. เลือก Material Icon (เช่น "message", "email", "alarm")
  3. ตั้งชื่อ: ic_notification
  4. สี: White (#FFFFFF)
  5. Opacity: 100%
**วิธีที่ 2: ใช้ Image Asset (Legacy)**
  1. Right-click res → New → Image Asset
  2. Asset Type: Notification Icons
  3. Source: Image file (PNG ขาวโปร่งใส)
  4. Shape: None
**วิธีที่ 3: สร้างเอง (Custom Design)**
  • ใช้ Figma/Sketch/Adobe Illustrator
  • Canvas: 96x96 px (xxxhdpi)
  • วาดเฉพาะ Shape สีขาว #FFFFFF พื้นหลังโปร่งใส
  • Export PNG ทุก Density (mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi)
  • วางใน res/drawable-*/ic_notification.png

ขั้นตอนที่ 3: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnCreateNotification"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Create notification with custom icon"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

ขั้นตอนที่ 4: MainActivity.java

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private static final String CHANNEL_ID = "icon_demo_channel";
    private static final String DEFAULT_CHANNEL_ID = "default";

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

        createNotificationChannel();

        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(v -> createNotificationWithCustomIcon());
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Icon Demo Notifications",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            channel.setDescription("Demo notification icons");
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    private void createNotificationWithCustomIcon() {
        // ใช้ Custom Icon ที่สร้างไว้ (ic_notification)
        // หากไม่มี ให้ใช้ ic_launcher_foreground หรือ ic_stat_notify
        int smallIconRes = R.drawable.ic_notification; // ต้องสร้างไฟล์นี้ก่อน
        // Fallback ถ้ายังไม่มี custom icon
        // int smallIconRes = R.drawable.ic_launcher_foreground;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(smallIconRes) // สำคัญ: ต้องเป็น White + Transparent
                .setContentTitle("Custom Icon Notification")
                .setContentText("This notification uses a custom white icon")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true)
                // Large Icon (ตัวเลือก) - แสดงใหญ่ใน Expanded View
                .setLargeIcon(androidx.core.graphics.drawable.IconCompat
                        .createWithResource(this, R.mipmap.ic_launcher)
                        .toBitmap());

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int id = (int) System.currentTimeMillis();
        manager.notify(id, builder.build());
    }
}

ขั้นตอนที่ 5: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.notifyme">
    <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 vs Small Icon

คุณสมบัติSmall Icon (setSmallIcon)Large Icon (setLargeIcon)
**ตำแหน่ง**Status Bar, Shade Header, LockscreenExpanded View, Media Style, Messaging Style
**ขนาด**24dp (Fixed)48-64dp (ปรับตาม Style)
**ข้อกำหนดสี**ขาว + Alpha เท่านั้น (บังคับ)สีเต็มได้ (Full color)
**บังคับ** (Crash หากไม่ตั้ง)ไม่บังคับ
**ใช้สำหรับ**Brand Identity, App RecognitionUser Photo, Album Art, Contact Photo

Large Icon - การใช้งาน

// จาก Resource
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))

// จาก URL (ต้องโหลด Async - ใช้ Glide/Coil/Picasso)
// Glide.with(this).asBitmap().load(url).into(new CustomTarget() { ... })

// จาก Contact
.setLargeIcon(Contact.getPhotoBitmap())

Adaptive Icon (Android 8.0+) และ Notification

  • App Icon (Launcher) ใช้ Adaptive Icon (Foreground + Background Layer)
  • Notification Small Icon **ไม่ได้ใช้** Adaptive Icon ต้องเป็น Asset แยกต่างหาก
  • แนะนำ: สร้าง ic_stat_notify_name เป็น Vector Drawable สีขาว

Notification Icon Generator Tools

  • Android Studio Built-in: New → Vector Asset / Image Asset → Notification Icons
  • Notification Icon Generator (Web): Android Asset Studio
  • Material Design Icons: Google Fonts Icons (ดาวน์โหลด SVG → Import เป็น Vector Asset)

การทดสอบ

  1. สร้าง Custom Icon (White + Transparent) วางใน res/drawable/ic_notification.xml (Vector) หรือ PNG ทุก Density
  2. รันแอป กดปุ่มสร้าง Notification
  3. ดู Status Bar: ควรเห็น Icon ขาวเล็กๆ
  4. ลาก Notification Shade: เห็น Icon เดียวกัน + Large Icon (App Icon)
  5. ลองใช้ Icon หลายสี → จะเห็น Silhouette สีขาวทึบ (ผิด規格)

Debug: Icon ไม่แสดงหรือแสดงผิด

  1. ตรวจสอบ setSmallIcon() ถูกเรียกหรือไม่ (บังคับ)
  2. ตรวจสอบ Icon เป็นสีขาว + Transparent (เปิดใน Editor ดู Alpha Channel)
  3. Clean Project → Rebuild
  4. Uninstall App → Install ใหม่ (บางครั้ง Cache Icon)
  5. ดู Logcat: "Could not find icon resource" หรือ "Invalid icon"
Best Practice: สร้าง Icon Set ครบ: ic_stat_notify_message, ic_stat_notify_email, ic_stat_notify_alert, ic_stat_notify_update ใช้ Vector Drawable เพื่อรองรับทุก Density และ Dark Mode อัตโนมัติ