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

Cách tạo thông báo Android không biến mất khi bấm vào

Giới thiệu

Mặc định, thông báo Android sẽ tự đóng khi người dùng bấm vào (do setAutoCancel(true)). Bài này hướng dẫn cách giữ thông báo hiển thị lại sau khi bấm bằng cách đặt setAutoCancel(false).

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

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

Android Studio → File → New Project → điền thông tin → Finish.

Bước 2: Giao diện (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/btnCreateNotification"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Tạo thông báo bền"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Bước 3: Logic chính (MainActivity.java)

Điểm khác biệt chính: .setAutoCancel(false) trên Builder.

package com.example.persistentnotification;

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 {

    public static final String CHANNEL_ID = "persistent_channel";
    private static final String DEFAULT_CHANNEL = "default";

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

        Button btn = findViewById(R.id.btnCreateNotification);
        btn.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 bền")
                    .setContentText("Tôi không biến mất khi bạn bấm vào!")
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(false) // ==== KEY POINT ====
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText("Thông báo này vẫn ở lại thanh trạng thái sau khi bấm. Bạn phải vuốt tay để xóa thủ công."));

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

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(
                        CHANNEL_ID, "Kênh bền", NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                builder.setChannelId(CHANNEL_ID);
            }

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

Bước 4: AndroidManifest.xml

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

    <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.PersistentNotification">

        <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>

Kết quả

Chạy app, nhấn nút tạo thông báo. Khi kéo xuống thanh thông báo và bấm vào nó, ứng dụng mở ra nhưng thông báo vẫn còn hiển thị. Người dùng phải vuốt ngang để xóa.

Khi nào dùng?

  • Thông báo quan trọng cần người dùng xác nhận đã đọc (ví dụ: cảnh báo bảo mật).
  • Đồng bộ với trạng thái server (thông báo chỉ xóa khi server xác nhận).
  • Nhạc player: giữ thông báo điều khiển phát/dừng.