ภาพรวม
การสร้าง Notification ที่เมื่อกดแล้วจะเปิด Activity ต้องใช้ PendingIntent ร่วมกับ NotificationCompat.Builder ตั้งแต่ Android 8.0 (API 26+) ต้องสร้าง Notification Channel ด้วย
ตัวอย่าง: สร้าง Notification เปิด MainActivity เมื่อกด
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → New Project → Empty Activity (Package: app.tutorialspoint.com.notifyme)
ขั้นตอนที่ 2: 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"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ขั้นตอนที่ 3: MainActivity.java
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
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 {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private static final String DEFAULT_CHANNEL_ID = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
btnCreateNotification.setOnClickListener(v -> createNotification());
}
private void createNotification() {
// Intent ที่จะเปิดเมื่อกด Notification
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// PendingIntent - สำคัญ: ใช้ FLAG_IMMUTABLE (Android 12+) หรือ FLAG_UPDATE_CURRENT
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags |= PendingIntent.FLAG_IMMUTABLE;
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, flags);
// สร้าง Notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test Notification")
.setContentText("Hello! This is my first push notification")
.setContentIntent(contentIntent)
.setAutoCancel(true) // หายเมื่อกด
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// สร้าง Channel สำหรับ Android 8.0+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Notification Channel Name";
String description = "Channel for test notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
}
// แสดง Notification
int notificationId = (int) System.currentTimeMillis();
notificationManager.notify(notificationId, builder.build());
}
}
ขั้นตอนที่ 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">
<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>
จุดสำคัญที่ต้องระวัง
1. PendingIntent Flags (Android 12+ / API 31+)
- บังคับต้องระบุ
FLAG_IMMUTABLEหรือFLAG_MUTABLE - ใช้
FLAG_IMMUTABLEสำหรับ Notification ปกติ (ปลอดภัยกว่า) - ใช้
FLAG_MUTABLEเฉพาะต้องการแก้ไข Intent ภายหลัง
2. Notification Channel (Android 8.0+)
- ทุก Notification ต้องมี Channel
- Channel มี Importance Level ควบคุมเสียง/น้ำเสียง/แสดงบนหน้าจอล็อก
- ผู้ใช้สามารถปิด/ปรับ Channel ได้เองใน Settings
3. Intent Flags สำหรับ Activity เป้าหมาย
FLAG_ACTIVITY_NEW_TASK: เริ่ม Task ใหม่ (จำเป็นเมื่อเรียกจากบริบทที่ไม่ใช่ Activity)FLAG_ACTIVITY_CLEAR_TASK: ล้าง Task เดิม เริ่มใหม่FLAG_ACTIVITY_SINGLE_TOP: ไม่สร้าง Instance ใหม่ถ้าอยู่บนสุด Stack แล้ว
รูปแบบ Notification อื่นๆ
BigTextStyle (ข้อความยาว)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("ข้อความยาวมากที่จะแสดงเต็มเมื่อขยาย Notification"))
BigPictureStyle (รูปภาพ)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(bitmap)
.setSummaryText("คำอธิบายรูป"))
InboxStyle (รายการ)
.setStyle(new NotificationCompat.InboxStyle()
.addLine("รายการ 1")
.addLine("รายการ 2")
.setBigContentTitle("มี 2 รายการ")
.setSummaryText("สรุป"))
การทดสอบ
- รันแอปบนอุปกรณ์จริงหรือ Emulator
- กดปุ่ม "Create notification"
- ดู Notification ใน Shade (ลากลงจากด้านบน)
- กด Notification → ควรเปิด MainActivity
เคล็ดลับ: สำหรับแอปจริง ควรจัดการ Navigation อย่างถูกต้องด้วย Task Stack (TaskStackBuilder) เพื่อให้ปุ่ม Back ทำงานถูกต้อง