Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีล้างการแจ้งเตือน Android หลังจากผ่านไปไม่กี่วินาที

ภาพรวม

ตัวอย่างนี้สาธิตวิธีสร้างการแจ้งเตือน (Notification) ใน Android และกำหนดให้หายไปโดยอัตโนมัติหลังจากแสดงผลเป็นเวลา 5 วินาที โดยใช้ Handler.postDelayed() เพื่อเรียก NotificationManager.cancel()

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่ใน Android Studio

เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: จัดทำ Layout (res/layout/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="Create notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java)

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

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

        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(v -> {
            Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
            notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            notificationIntent.setAction(Intent.ACTION_MAIN);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

            PendingIntent resultIntent = PendingIntent.getActivity(
                MainActivity.this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    MainActivity.this, default_notification_channel_id)
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentTitle("Test")
                    .setContentIntent(resultIntent)
                    .setStyle(new NotificationCompat.InboxStyle())
                    .setContentText("Hello! This is my first push notification");

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

            if (android.os.Build.VERSION.SDK_INT >= android.os.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);
            }

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

            // ล้างการแจ้งเตือนหลัง 5 วินาที
            Handler handler = new Handler();
            long delayInMilliseconds = 5000;
            handler.postDelayed(() -> mNotificationManager.cancel(notificationId), delayInMilliseconds);
        });
    }
}

ขั้นตอนที่ 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">

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

ทดสอบการทำงาน

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือเป็นเป้าหมาย และตรวจสอบหน้าจออุปกรณ์ - การแจ้งเตือนจะปรากฏขึ้นและหายไปด้วยตัวเองภายใน 5 วินาที