ภาพรวม
ตัวอย่างนี้สาธิตการแสดง Custom Alert/Dialog เมื่อมีการแจ้งเตือนเข้ามา โดยใช้ Toast แบบง่าย และอธิบายวิธีการแสดง Dialog จริงจาก Background (ต้องใช้ System Alert Window Permission)
ขั้นตอนที่ 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 - แสดง Toast พร้อม Notification
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
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);
onNewIntent(getIntent());
}
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("Notify Me");
mBuilder.setContentText("Something important!");
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, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
// แสดง Toast พร้อมกับ Notification (ทำงานได้ก็ต่อเมื่อแอปอยู่ Foreground)
Toast.makeText(MainActivity.this, "Custom Alert View", Toast.LENGTH_SHORT).show();
}
}
ขั้นตอนที่ 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>
⚠️ ข้อจำกัดสำคัญ: ไม่สามารถแสดง Dialog จาก Background ได้โดยตรง
Android ไม่อนุญาตให้แอปใน Background แสดง Dialog/Activity ทับแอปอื่นได้
เนื่องจากเหตุผลด้านความปลอดภัยและประสบการณ์ผู้ใช้ (Security & UX)
เนื่องจากเหตุผลด้านความปลอดภัยและประสบการณ์ผู้ใช้ (Security & UX)
วิธีการที่ถูกต้องสำหรับแต่ละสถานการณ์
1. แอปอยู่ Foreground (กำลังเปิดอยู่) → ใช้ Dialog/Fragment ปกติ
// ใน Activity หรือ Fragment
public void showCustomAlert(String title, String message) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("ตกลง", (dialog, which) -> { /* action */ })
.setNegativeButton("ยกเลิก", null)
.show();
}
2. แอปอยู่ Background → ใช้ High Priority Notification + Full Screen Intent (Android 10+)
// ใน FirebaseMessagingService หรือ Notification Service
Intent fullScreenIntent = new Intent(this, FullScreenAlertActivity.class);
fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(
this, 0, fullScreenIntent,
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("แจ้งเตือนสำคัญ")
.setContentText("กดเพื่อดูรายละเอียด")
.setFullScreenIntent(fullScreenPendingIntent, true) // สำคัญ!
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM); // หรือ CALL, MESSAGE
// ต้องมี Permission ใน Manifest (Android 10+)
/*
*/
3. ใช้ System Alert Window (Overlay) - ต้องขอ Permission เฉพาะ
// Manifest
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
// ตรวจสอบและขอ Permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE);
} else {
showOverlayView();
}
}
// แสดง Overlay View (ไม่ใช่ Dialog จริง แต่คล้ายกัน)
private void showOverlayView() {
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
View overlayView = LayoutInflater.from(this).inflate(R.layout.overlay_alert, null);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
: WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
);
params.gravity = Gravity.CENTER;
windowManager.addView(overlayView, params);
}
4. ใช้ Notification Actions (แนะนำที่สุด)
เพิ่มปุ่ม Action ใน Notification ให้ผู้ใช้ตอบโต้ได้ทันที
NotificationCompat.Action action = new NotificationCompat.Action.Builder(
R.drawable.ic_action, "ดูรายละเอียด", pendingIntent).build();
mBuilder.addAction(action);
สรุปแนวทางเลือก
| สถานการณ์ | วิธีที่แนะนำ | Permission |
|---|---|---|
| App Foreground | AlertDialog / BottomSheetDialog | ไม่ต้องการ |
| App Background - ด่วนมาก | Full Screen Intent + High Priority | USE_FULL_SCREEN_INTENT (API 29+) |
| App Background - ทั่วไป | Notification + Actions | ไม่ต้องการ |
| ต้องแสดง UI ทับระบบ | SYSTEM_ALERT_WINDOW (Overlay) | SYSTEM_ALERT_WINDOW (User grant) |
แนวทางปฏิบัติที่ดี
- หลีกเลี่ยงการรบกวนผู้ใช้โดยไม่จำเป็น (Respect user attention)
- ใช้ Notification Channel ความสำคัญเหมาะสม (HIGH/MAX เฉพาะเรื่องด่วน)
- Full Screen Intent ใช้เฉพาะโทรเข้า, นาฬิกาปลุก, แจ้งเตือนฉุกเฉิน
- Overlay Permission ยากต่อการขอจากผู้ใช้ ใช้เฉพาะกรณีจำเป็น (Chat heads, Screen recorder)
- ทดสอบบน Android 10+ (Q) ซึ่งมีการจำกัด Background Activity Launch