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

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

ภาพรวม

ตัวอย่างนี้แสดงวิจิธีปิดแผ่นการแจ้งเตือน (Notification Shade) หลังจากผู้ใช้กดปุ่ม Action บนการแจ้งเตือน โดยใช้ PendingIntent.getBroadcast() ร่วมกับ BroadcastReceiver เพื่อส่งสัญญาณปิดแผ่นการแจ้งเตือน

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

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.java - เพิ่ม Action พร้อม BroadcastReceiver

package app.tutorialspoint.com.notifyme;

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

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";
    public static final String ACTION_CLOSE_PANEL = "app.tutorialspoint.com.notifyme.CLOSE_PANEL";

    private BroadcastReceiver closePanelReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // ปิดแผ่นการแจ้งเตือนโดยส่ง Intent ไปยังระบบ
            Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            sendBroadcast(closeDialogs);
        }
    };

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

        // ลงทะเบียน BroadcastReceiver
        LocalBroadcastManager.getInstance(this).registerReceiver(
                closePanelReceiver, new IntentFilter(ACTION_CLOSE_PANEL));

        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(v -> {
            // Intent สำหรับ Action "ปิด"
            Intent closeIntent = new Intent(ACTION_CLOSE_PANEL);
            PendingIntent closePendingIntent = PendingIntent.getBroadcast(
                    this, 0, closeIntent, PendingIntent.FLAG_IMMUTABLE);

            // Intent สำหรับเปิด Activity (ตัวอย่าง)
            Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent contentIntent = PendingIntent.getActivity(
                    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("Notification with Action")
                    .setContentText("Press button to close panel")
                    .setContentIntent(contentIntent)
                    .addAction(R.drawable.ic_launcher_foreground, "Close Panel", closePendingIntent)
                    .setAutoCancel(true);

            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 channel = new NotificationChannel(
                        NOTIFICATION_CHANNEL_ID, "Channel", importance);
                mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
                assert mNotificationManager != null;
                mNotificationManager.createNotificationChannel(channel);
            }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(closePanelReceiver);
    }
}

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

คำอธิบาย

  • ใช้ LocalBroadcastManager สำหรับสื่อสารภายในแอป (ปลอดภัยกว่า system broadcast)
  • Action ปุ่มใช้ PendingIntent.getBroadcast() ส่งสัญญาณไปยัง BroadcastReceiver
  • Receiver ส่ง Intent.ACTION_CLOSE_SYSTEM_DIALOGS เพื่อปิดแผ่นการแจ้งเตือน
  • หมายเหตุ: Android 10+ จำกัดการใช้ ACTION_CLOSE_SYSTEM_DIALOGS อาจต้องใช้วิธีอื่น