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

Cách mở Activity cuối cùng khi bấm vào thông báo Android

Giới thiệu

Khi ứng dụng đã mở sẵn nhiều Activity (A → B → C), bấm thông báo nên quay lại Activity đang hiển thị (C) thay vì khởi tạo mới. Sử dụng kết hợp FLAG_ACTIVITY_CLEAR_TOP và FLAG_ACTIVITY_SINGLE_TOP.

Cơ chế hoạt động

FlagTác dụng
CLEAR_TOPNếu Activity đích đã có trong stack, xóa mọi Activity phía trên nó
SINGLE_TOPNếu Activity đích đang ở đỉnh stack, không tạo instance mới, gọi onNewIntent()

Kết hợp cả hai: Quay về instance hiện có của Activity đích, xóa các Activity khác phía trên.

Code mẫu

MainActivity.java

package com.example.resumeactivity;

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

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

        findViewById(R.id.btnNotify).setOnClickListener(v -> {
            // Intent trỏ về MainActivity (hoặc Activity cuối cùng bạn muốn resume)
            Intent intent = new Intent(this, MainActivity.class);
            
            // ==== KEY: Kết hợp 2 flag này ====
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            
            // Thêm data để Activity biết là từ notification
            intent.putExtra("from_notification", true);
            intent.putExtra("timestamp", System.currentTimeMillis());

            PendingIntent pendingIntent = PendingIntent.getActivity(
                    this, 0, intent, 
                    PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
                    .setSmallIcon(R.drawable.ic_launcher_foreground)
                    .setContentTitle("Quay lại app")
                    .setContentText("Mở Activity cuối cùng đang chạy")
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true);

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

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

            manager.notify(1001, builder.build()); // ID cố định để update được
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // Xử lý khi Activity đã chạy và được đưa lên top
        if (intent.getBooleanExtra("from_notification", false)) {
            long time = intent.getLongExtra("timestamp", 0);
            // Cập nhật UI, scroll đến tin nhắn mới, v.v.
            // Toast.makeText(this, "Resumed from notification: " + time, Toast.LENGTH_SHORT).show();
        }
    }
}

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/btnNotify"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Gửi thông báo resume"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Kịch bản thực tế: Chat App

  1. User đang xem màn hình ChatDetail (Activity C).
  2. Server đẩy tin nhắn mới → tạo thông báo.
  3. User bấm thông báo → quay về ChatDetail (C), không tạo mới, gọi onNewIntent().
  4. Trong onNewIntent(), load tin nhắn mới, scroll xuống cuối.

Lưu ý quan trọng

  • launchMode trong Manifest: Nếu Activity đặt android:launchMode="singleTop" hoặc singleTask, hành vi có thể khác. Khuyến nghị dùng flag trong Intent như trên.
  • PendingIntent.FLAG_UPDATE_CURRENT: Cần thiết để cập nhật extra data mới cho mỗi thông báo.
  • Task Affinity: Nếu app có nhiều task, hãy cân nhắc FLAG_ACTIVITY_NEW_TASK.