ภาพรวม
ตัวอย่างนี้สาธิตวิธีตรวจสอบว่า Notification ยังคงแสดงอยู่ (Visible) หรือถูกผู้ใช้ปิด (Dismissed) แล้ว โดยใช้ PendingIntent.FLAG_NO_CREATE
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project
ขั้นตอนที่ 2: 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:onClick="createNotification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="16dp"
android:text="Create notification" />
</RelativeLayout>
ขั้นตอนที่ 3: MainActivity - ตรวจสอบสถานะ Notification
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
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";
private static final int NOTIFICATION_ID = 123; // ID คงที่เพื่อตรวจสอบ
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onNewIntent(getIntent());
}
public void createNotification(View view) {
// ตรวจสอบก่อนสร้าง: Notification ยังแสดงอยู่หรือไม่
if (isNotificationVisible()) {
// Notification ยังอยู่ → อาจจะอัปเดต หรือไม่สร้างใหม่
Log.d("Notification", "Notification is still visible, updating...");
updateExistingNotification();
} else {
// Notification หายแล้ว → สร้างใหม่
createNewNotification();
}
}
private boolean isNotificationVisible() {
Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
// FLAG_NO_CREATE: คืนค่า PendingIntent ที่มีอยู่แล้วเท่านั้น ไม่สร้างใหม่
PendingIntent test = PendingIntent.getActivity(
MainActivity.this,
NOTIFICATION_ID,
notificationIntent,
PendingIntent.FLAG_NO_CREATE | PendingIntent.FLAG_IMMUTABLE
);
// หากคืนค่าไม่ใช่ null = PendingIntent ยังอยู่ = Notification ยังแสดง
return test != null;
}
private void createNewNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
mBuilder.setContentTitle("Notify Me");
mBuilder.setContentText("Something important!");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true);
// สร้าง PendingIntent ด้วย ID เดิม (NOTIFICATION_ID = 123)
Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this, NOTIFICATION_ID, notificationIntent,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private void updateExistingNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
mBuilder.setContentTitle("Notify Me (Updated)");
mBuilder.setContentText("Updated at " + new java.util.Date());
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true);
Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this, NOTIFICATION_ID, notificationIntent,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
// ใช้ ID เดิมเพื่ออัปเดต Notification ที่มีอยู่
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.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">
<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>
หลักการทำงานของ FLAG_NO_CREATE
PendingIntent.FLAG_NO_CREATE: ไม่สร้าง PendingIntent ใหม่ คืนค่าที่มีอยู่แล้ว (หรือ null หากไม่มี)- ใช้ร่วมกับ Request Code เดียวกัน (ในตัวอย่างคือ 123)
- หาก Notification ถูกปิด (Swipe away) หรือ AutoCancel → PendingIntent จะถูก Cancel → คืนค่า null
- หาก Notification ยังแสดงอยู่ → PendingIntent ยังคงมี效力 → คืนค่า PendingIntent object
ข้อจำกัดของวิธีนี้
| ข้อจำกัด | คำอธิบาย |
|---|---|
| ทำงานได้เฉพาะ PendingIntent เดียวกัน | ต้องใช้ Request Code และ Intent เดียวกันทุกครั้ง |
| ไม่แยกได้ว่า "ผู้ใช้กด" หรือ "ผู้ใช้สวายปิด" | ทั้งสองกรณี PendingIntent จะหายไป |
| ไม่ทำงานกับ Notification ที่ไม่มี ContentIntent | ต้องมี setContentIntent() เสมอ |
| Android 12+ FLAG_IMMUTABLE | ต้องระบุ FLAG_IMMUTABLE หรือ FLAG_MUTABLE เสมอ |
วิธีอื่น: ใช้ NotificationListenerService (API 18+)
วิธีที่ครอบคลุมกว่า แต่ต้องขอ Permission จากผู้ใช้
1. สร้าง Service
public class MyNotificationListener extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
// Notification ถูกโพสต์ (แสดง)
String packageName = sbn.getPackageName();
int id = sbn.getId();
String tag = sbn.getTag();
Log.d("NLService", "Posted: " + packageName + " ID:" + id);
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
super.onNotificationRemoved(sbn);
// Notification ถูกลบ (สวายปิด หรือ cancel)
String packageName = sbn.getPackageName();
int id = sbn.getId();
Log.d("NLService", "Removed: " + packageName + " ID:" + id);
}
}
2. Manifest
<service
android:name=".MyNotificationListener"
android:label="My Notification Listener"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
3. นำผู้ใช้ไปยัง Settings เพื่ออนุญาต
Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS); startActivity(intent);
สรุป: เลือกวิธีไหนดี?
- PendingIntent.FLAG_NO_CREATE: เรียบง่าย ไม่ต้อง Permission เหมาะสำหรับตรวจสอบ Notification ของตัวเองก่อนสร้างใหม่/อัปเดต
- NotificationListenerService: ครอบคลุมทุก Notification (รวมแอปอื่น) ต้องขอ Permission เหมาะสำหรับแอปจัดการ Notification, Parental Control, Automation