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

Hiển thị Custom Alert/View khi nhận thông báo Android

Giới thiệu

Ví dụ này minh họa cách hiển thị một Custom Alert/Dialog/View ngay khi thông báo được tạo/nhận. Trong ví dụ dùng Toast đơn giản, nhưng thực tế có thể dùng Dialog, Activity, hoặc Overlay window.

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:onClick="createNotification"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:text="Tạo thông báo + Custom Alert" />

</RelativeLayout>

Bước 3: MainActivity với Toast Alert (src/MainActivity.java)

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);
    }

    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("Thông báo mới");
        mBuilder.setContentText("Đã kích hoạt Custom Alert View");
        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 Custom Alert", importance);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

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

        // HIỂN THỊ CUSTOM ALERT NGAY LẬP TỨC
        showCustomAlert();
    }

    private void showCustomAlert() {
        // CÁCH 1: TOAST ĐƠN GIẢN
        Toast.makeText(MainActivity.this, "🔔 Custom Alert View Activated!", Toast.LENGTH_LONG).show();

        // CÁCH 2: CUSTOM TOAST VỚI LAYOUT RIÊNG
        // View customToastView = getLayoutInflater().inflate(R.layout.custom_toast, null);
        // Toast customToast = new Toast(this);
        // customToast.setView(customToastView);
        // customToast.setDuration(Toast.LENGTH_LONG);
        // customToast.show();

        // CÁCH 3: DIALOG (CẦN ACTIVITY FOREGROUND)
        // new AlertDialog.Builder(this)
        //     .setTitle("Thông báo")
        //     .setMessage("Bạn có thông báo mới!")
        //     .setPositiveButton("OK", null)
        //     .show();
    }
}

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>

Mở rộng: Custom Alert thực tế

1. Custom Toast Layout (res/layout/custom_toast.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#333333"
    android:padding="16dp"
    android:orientation="horizontal"
    android:layout_margin="16dp">

    <ImageView
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:src="@drawable/ic_notification"
        android:layout_marginEnd="16dp"/>

    <TextView
        android:id="@+id/toastText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom Alert!"
        android:textColor="#FFFFFF"
        android:textSize="16sp"
        android:gravity="center_vertical"/>

</LinearLayout>

2. Full-screen Activity/Dialog khi nhận Push (Background)

// Trong FirebaseMessagingService hoặc BroadcastReceiver
public void showFullScreenAlert(Context context, String title, String message) {
    Intent intent = new Intent(context, FullScreenAlertActivity.class);
    intent.putExtra("title", title);
    intent.putExtra("message", message);
    // FLAGS QUAN TRỌNG ĐỂ HIỆN TRÊN LOCK SCREEN
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
        | Intent.FLAG_ACTIVITY_CLEAR_TASK
        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
        | Intent.FLAG_ACTIVITY_NO_HISTORY
        | Intent.FLAG_SHOW_WHEN_LOCKED
        | Intent.FLAG_TURN_SCREEN_ON
        | Intent.FLAG_KEEP_SCREEN_ON);
    context.startActivity(intent);
}

3. FullScreenAlertActivity (theme Translucent/Fullscreen)

// AndroidManifest.xml
<activity
    android:name=".FullScreenAlertActivity"
    android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
    android:showOnLockScreen="true"
    android:turnScreenOn="true" />

// FullScreenAlertActivity.java
public class FullScreenAlertActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fullscreen_alert);
        
        // Hiển thị custom view, play sound, vibrate
        // Tự động đóng sau vài giây hoặc khi user tương tác
    }
}

Lưu ý quan trọng

⚠️ Hạn chế hiển thị UI từ Background

  • Android 10+ (API 29+): Khởi động Activity từ background bị hạn chế
  • Cần quyền SYSTEM_ALERT_WINDOW cho overlay window
  • Foreground Service + Notification mới được launch Activity
  • Khuyên dùng: High-priority notification + Full-screen Intent

Full-screen Intent (Cách chuẩn cho Call/Alarm)

// Trong Notification Builder
Intent fullScreenIntent = new Intent(context, IncomingCallActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(
    context, 0, fullScreenIntent, PendingIntent.FLAG_IMMUTABLE);

mBuilder.setFullScreenIntent(fullScreenPendingIntent, true); // true = high priority

// Manifest cho Activity
<activity android:name=".IncomingCallActivity"
    android:showOnLockScreen="true"
    android:turnScreenOn="true" />

Chạy thử nghiệm

Chạy app → Nhấn nút → Thông báo xuất hiện + Toast "Custom Alert View Activated" hiển thị.