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

Ví dụ Notification Android đầy đủ: Rung, Âm thanh, Action, BigTextStyle

Bài viết demo một Notification hoàn chỉnh kết hợp: rung (vibrate), âm thanh mặc định, Action button, BigTextStyle mở rộng nội dung, và PendingIntent mở Activity khi bấm.

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

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

Tạo dự án Android Studio, package app.tutorialspoint.com.notifyme.

Bước 2: Giao diện (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="Tạo Notification đầy đủ"
        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: Code Notification đầy đủ (src/MainActivity.java)

package app.tutorialspoint.com.notifyme;

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

public class MainActivity extends AppCompatActivity {
    private static final String DEFAULT_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 -> createFullNotification());
    }

    private void createFullNotification() {
        // Intent mở MainActivity khi bấm notification
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(
            this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // Action button "Thêm" (ví dụ: quick reply, like, etc.)
        PendingIntent actionIntent = PendingIntent.getActivity(
            this, 1, new Intent(this, MainActivity.class), 
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("Thông báo đầy đủ tính năng")
            .setContentText("Hello! Đây là push notification đầu tiên của tôi")
            .setStyle(new NotificationCompat.BigTextStyle()
                .bigText("Big View Styles: Nội dung dài hiển thị đầy đủ khi người dùng kéo xuống mở rộng notification. " +
                    "Có thể chứa nhiều dòng văn bản, link, định dạng cơ bản."))
            .setContentIntent(contentIntent)           // Bấm vào body notification
            .addAction(R.drawable.ic_launcher_foreground, "Thêm", actionIntent) // Nút action
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true);                       // Tự xóa khi bấm

        // Lấy NotificationManager và hiển thị
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (manager != null) {
            // Android 8+ cần channel, nhưng builder sẽ dùng default channel nếu chưa tạo
            // Khuyến nghị: tạo channel trong Application.onCreate()
            manager.notify((int) System.currentTimeMillis(), builder.build());
        }
    }
}

Bước 4: AndroidManifest.xml (cần quyền VIBRATE)

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

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

    <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>
        <!-- Firebase Messaging Service (nếu dùng FCM) -->
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
    </application>
</manifest>

Giải thích các thành phần

  • BigTextStyle: Mở rộng nội dung hiển thị nhiều dòng. Còn có BigPictureStyle (ảnh lớn), InboxStyle (danh sách), MessagingStyle (chat).
  • addAction(): Thêm nút bấm trực tiếp trên notification (tối đa 3 nút hiển thị). Cần PendingIntent riêng cho mỗi action.
  • PendingIntent.FLAG_IMMUTABLE: Bắt buộc từ Android 12 (API 31) để ngăn chặn sửa đổi intent bởi app khác.
  • setPriority(HIGH): Kết hợp với Channel IMPORTANCE_HIGH để kích hoạt heads-up.
  • Rung & Âm thanh: Trên Android 8+, cấu hình qua NotificationChannel (xem bài trước). Trên Android 7-, dùng builder.setVibrate() và builder.setSound().

Mở rộng: Thêm RemoteInput cho Quick Reply

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

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

builder.addAction(replyAction);

Trong Activity nhận: Bundle remoteInput = RemoteInput.getResultsFromIntent(intent); String reply = remoteInput.getCharSequence("reply_key").toString();