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

Cách đóng thông báo Android khi người dùng bấm vào

Giới thiệu

Đây là hành vi mặc định của Android: thông báo tự đóng khi người dùng bấm vào. Bài viết xác nhận cách làm đúng chuẩn bằng setAutoCancel(true).

Code mẫu hoàn chỉnh (AndroidX)

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/btnNotify"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Tạo thông báo tự đóng"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.autocancelnotification;

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.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private static final String CHANNEL_ID = "auto_cancel_channel";
    private static final String DEFAULT_CHANNEL = "default";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btnNotify).setOnClickListener(v -> {
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                    this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL)
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentTitle("Thông báo tự đóng")
                    .setContentText("Bấm vào tôi sẽ biến mất ngay")
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true); // ==== MẶC ĐỊNH, NHƯNG NÊN KHAI BÁO RÕ ====

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

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(
                        CHANNEL_ID, "Tự đóng", NotificationManager.IMPORTANCE_DEFAULT);
                manager.createNotificationChannel(channel);
                builder.setChannelId(CHANNEL_ID);
            }

            int id = (int) System.currentTimeMillis();
            manager.notify(id, builder.build());
        });
    }
}

Lưu ý quan trọng

  • Mặc định: Từ API 16+, setAutoCancel(true) là mặc định. Việc khai báo rõ ràng giúp code dễ đọc và tránh bug nếu mặc định thay đổi.
  • PendingIntent: Phải dùng FLAG_IMMUTABLE (API 31+) hoặc FLAG_MUTABLE nếu cần sửa đổi sau.
  • ID thông báo: Dùng System.currentTimeMillis() để đảm bảo ID duy nhất mỗi lần.

So sánh nhanh

setAutoCancelHành vi
true (mặc định)Thông báo biến mất khi bấm
falseThông báo ở lại, phải vuốt tay để xóa