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

Cách xóa thông báo Android sau vài giây

Giới thiệu

Hướng dẫn này minh họa cách tự động xóa một thông báo Android sau một khoảng thời gian nhất định (ví dụ: 5 giây) bằng cách sử dụng Handler và NotificationManager.cancel().

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project, điền đầy đủ thông tin cần thiết để tạo dự án mới.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

Thêm nút bấm để tạo thông báo:

<?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="Tạo thông báo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Lưu ý: Code mẫu dùng AndroidX (thay vì thư viện support cũ). Hãy đảm bảo dự án đã migrate sang AndroidX.

Bước 3: Viết logic chính (src/MainActivity.java)

Sử dụng Handler.postDelayed() để hủy thông báo sau 5000ms:

package com.example.notificationdemo;

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 android.os.Handler;
import android.os.Looper;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
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 -> {
            // Intent để mở lại MainActivity khi bấm vào thông báo
            Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent resultIntent = PendingIntent.getActivity(
                    MainActivity.this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

            // Xây dựng thông báo
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentTitle("Thông báo test")
                    .setContentText("Thông báo này sẽ tự biến mất sau 5 giây")
                    .setContentIntent(resultIntent)
                    .setAutoCancel(true); // Tự xóa khi người dùng bấm

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            // Tạo kênh thông báo cho Android 8.0+
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(
                        NOTIFICATION_CHANNEL_ID, "Kênh test", NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                builder.setChannelId(NOTIFICATION_CHANNEL_ID);
            }

            // ID duy nhất cho thông báo (dùng timestamp)
            int notificationId = (int) System.currentTimeMillis();
            manager.notify(notificationId, builder.build());

            // ==== QUAN TRỌNG: Tự động xóa sau 5 giây ====
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                manager.cancel(notificationId);
            }, 5000); // 5000ms = 5 giây
        });
    }
}

Bước 4: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.notificationdemo">

    <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/Theme.NotificationDemo">

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị Android thật, chọn thiết bị từ toolbar và nhấn Run. Nhấn nút "Tạo thông báo", thông báo sẽ xuất hiện và tự động biến mất sau 5 giây.

Giải thích kỹ thuật

  • Handler + postDelayed: Chạy code trên luồng chính (Main Thread) sau độ trễ xác định.
  • NotificationManager.cancel(id): Xóa thông báo theo ID. Cần lưu ID khi gọi notify() để dùng sau.
  • Notification Channel: Bắt buộc từ Android 8.0 (API 26) trở lên.
  • PendingIntent.FLAG_IMMUTABLE: Yêu cầu từ Android 12 (API 31) cho PendingIntent.