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

Khởi động Activity từ Notification trên Android

Để người dùng bấm vào thông báo (Notification) và mở một Activity cụ thể, bạn cần tạo PendingIntent gắn vào NotificationCompat.Builder qua phương thức setContentIntent().

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 chính (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 thông báo"
        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: Tạo và hiển thị Notification (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 androidx.core.app.NotificationCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    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 -> createNotification());
    }

    private void createNotification() {
        // Intent mở Activity khi bấm notification
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(
            this, 0, intent, 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 test")
            .setContentText("Hello! Đây là push notification đầu tiên của tôi")
            .setContentIntent(contentIntent)
            .setAutoCancel(true); // Tự xóa khi bấm

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

        // Android Oreo (API 26+) bắt buộc có Notification Channel
        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, "Kênh thông báo", importance);
            manager.createNotificationChannel(channel);
            builder.setChannelId(NOTIFICATION_CHANNEL_ID);
        }

        // ID duy nhất cho mỗi notification (dùng timestamp)
        int notificationId = (int) System.currentTimeMillis();
        manager.notify(notificationId, 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="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>

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

  • PendingIntent.getActivity(): Tạo intent chờ đợi, được thực thi khi user tương tác. Flag FLAG_IMMUTABLE bắt buộc từ Android 12 (API 31) để bảo mật.
  • NotificationChannel: Bắt buộc từ Android 8.0 (Oreo). Mỗi kênh có độ quan trọng (importance) quyết định hành vi: âm thanh, rung, hiển thị heads-up...
  • setAutoCancel(true): Tự động xóa notification khi user bấm vào.
  • notificationId: Phải duy nhất nếu muốn hiển thị nhiều notification cùng lúc. Dùng timestamp hoặc counter.

Mở rộng: Truyền dữ liệu qua Notification

Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("notification_id", 123);
intent.putExtra("title", "Tiêu đề bài viết");
PendingIntent pendingIntent = PendingIntent.getActivity(
    this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

Trong DetailActivity, lấy dữ liệu qua getIntent().getExtras().