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

Cách thêm nút bấm (Action Button) vào thông báo Android

Giới thiệu

Thông báo Android có thể chứa tối đa 3 nút bấm (Action Buttons) hiển thị ngay trên thông báo (Android 7.0+) hoặc trong expanded view. Mỗi nút gán một PendingIntent (Activity, Broadcast, hoặc Service).

Code mẫu: Thêm nút "Snooze" (Broadcast)

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tạo thông báo có nút bấm" />

</RelativeLayout>

MainActivity.java

package com.example.notificationaction;

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 = "action_channel";

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

        Button btn = findViewById(R.id.btnCreateNotification);
        btn.setOnClickListener(v -> {
            // 1. Tạo PendingIntent cho nút "Snooze" (BroadcastReceiver)
            Intent snoozeIntent = new Intent(this, SnoozeReceiver.class);
            snoozeIntent.setAction("ACTION_SNOOZE");
            snoozeIntent.putExtra("EXTRA_NOTIFICATION_ID", 1001);
            PendingIntent snoozePendingIntent = PendingIntent.getBroadcast(
                    this, 1, snoozeIntent, PendingIntent.FLAG_IMMUTABLE);

            // 2. Tạo PendingIntent cho nút "Mở app" (Activity)
            Intent openIntent = new Intent(this, MainActivity.class);
            openIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent openPendingIntent = PendingIntent.getActivity(
                    this, 2, openIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

            // 3. Build Notification với 2 action
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentTitle("Thông báo có nút bấm")
                    .setContentText("Chọn hành động: Snooze hoặc Mở app")
                    .setAutoCancel(true)
                    // Action 1: Snooze (Broadcast)
                    .addAction(R.drawable.ic_snooze, "Ngủ nướng 10p", snoozePendingIntent)
                    // Action 2: Mở app (Activity)
                    .addAction(R.drawable.ic_launcher_foreground, "Mở app", openPendingIntent);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(
                        CHANNEL_ID, "Action Buttons", NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                builder.setChannelId(CHANNEL_ID);
            }

            manager.notify(1001, builder.build());
        });
    }
}

SnoozeReceiver.java (BroadcastReceiver xử lý nút Snooze)

package com.example.notificationaction;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class SnoozeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("ACTION_SNOOZE".equals(intent.getAction())) {
            int notifId = intent.getIntExtra("EXTRA_NOTIFICATION_ID", -1);
            
            // 1. Xử lý logic snooze: đặt lịch thông báo lại 10 phút sau
            // (Dùng AlarmManager như bài Schedule Notification)
            
            // 2. Xóa thông báo hiện tại
            if (notifId != -1) {
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                manager.cancel(notifId);
            }
            
            Toast.makeText(context, "Đã ngủ nướng 10 phút", Toast.LENGTH_SHORT).show();
        }
    }
}

AndroidManifest.xml

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

    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.VIBRATE" />

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

        <receiver
            android:name=".SnoozeReceiver"
            android:exported="false" />
    </application>
</manifest>

Các loại PendingIntent cho Action

LoạiPhương thứcDùng cho
ActivityPendingIntent.getActivity()Mở màn hình chi tiết, settings, chat
BroadcastPendingIntent.getBroadcast()Xử lý nhanh không mở UI: like, delete, snooze, reply
ServicePendingIntent.getService()Khởi động foreground service (download, media)

Lưu ý UI/UX

  • Icon: Nên dùng icon vector (XML) hoặc PNG trong drawable, kích thước 24x24dp.
  • Text: Ngắn gọn, rõ ràng (tối đa 2 từ).
  • Số lượng: Tối đa 3 action hiển thị. Thứ tự addAction = thứ tự hiển thị.
  • Inline Reply (API 24+): Dùng RemoteInput cho phép trả lời ngay trên thông báo.

Ví dụ Inline Reply (Trả lời nhanh)

RemoteInput remoteInput = new RemoteInput.Builder("key_reply")
        .setLabel("Trả lời...")
        .build();

PendingIntent replyPendingIntent = PendingIntent.getBroadcast(
        this, 3, new Intent(this, ReplyReceiver.class), 
        PendingIntent.FLAG_IMMUTABLE);

NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
        R.drawable.ic_reply, "Trả lời", replyPendingIntent)
        .addRemoteInput(remoteInput)
        .build();

builder.addAction(replyAction);

// Trong ReplyReceiver.onReceive():
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
if (remoteInput != null) {
    CharSequence replyText = remoteInput.getCharSequence("key_reply");
    // Gửi replyText lên server
}