Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 알림 클릭 시 새 인텐트 생성 없이 기존 액티비티 재개하는 방법

이 튜토리얼에서는 안드로이드에서 알림(Notification)을 탭했을 때 새로운 액티비티 인스턴스를 생성하는 대신, 이미 실행 중인 기존 액티비티를 재개(resume)하도록 처리하는 방법을 소개합니다.

핵심은 인텐트에 FLAG_ACTIVITY_CLEAR_TOPFLAG_ACTIVITY_SINGLE_TOP 플래그를 함께 설정하는 것입니다. 이 조합을 사용하면 알림을 클릭해도 같은 액티비티가 중복으로 실행되지 않고, 이미 존재하는 인스턴스가 화면 앞으로 전환됩니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project 메뉴로 이동한 뒤, 필요한 모든 정보를 입력하여 새 프로젝트를 생성합니다.

2단계 — 레이아웃 파일 작성 (res/layout/activity_main.xml)

아래 코드를 res/layout/activity_main.xml에 추가합니다. 화면 중앙에 '알림 생성' 버튼 하나를 배치하는 간단한 구성입니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="알림 생성"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

3단계 — MainActivity.java 작성

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.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent notificationIntent = new Intent(MainActivity.this,
                        MainActivity.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                PendingIntent resultIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0);
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("테스트")
                        .setContentIntent(resultIntent)
                        .setStyle(new NotificationCompat.InboxStyle())
                        .setContentText("안녕하세요! 첫 번째 푸시 알림입니다");
                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 notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
                    mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
                    assert mNotificationManager != null;
                    mNotificationManager.createNotificationChannel(notificationChannel);
                }
                assert mNotificationManager != null;
                mNotificationManager.notify((int) System.currentTimeMillis(),
                        mBuilder.build());
            }
        });
    }
}

이 코드에서 가장 중요한 부분은 다음 줄입니다.

notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  • FLAG_ACTIVITY_CLEAR_TOP: 대상 액티비티가 이미 태스크 스택에 존재할 경우, 그 위에 쌓여 있던 액티비티들을 모두 제거하고 해당 액티비티를 맨 앞으로 가져옵니다.
  • FLAG_ACTIVITY_SINGLE_TOP: 해당 액티비티가 이미 스택의 최상단에 있다면 새 인스턴스를 만들지 않고 기존 인스턴스를 재사용합니다(이때 onNewIntent()가 호출됩니다).

참고로 Android 12(API 31) 이상을 타깃으로 하는 경우에는 PendingIntent 생성 시 반드시 PendingIntent.FLAG_IMMUTABLE 또는 PendingIntent.FLAG_MUTABLE을 지정해야 하므로, 아래와 같이 작성하는 것이 좋습니다.

PendingIntent resultIntent = PendingIntent.getActivity(
        MainActivity.this,
        0,
        notificationIntent,
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);

또한 이 예제는 구버전 support 라이브러리(android.support.*)를 기준으로 작성되었으며, 최신 프로젝트에서는 AndroidX(androidx.appcompat, androidx.constraintlayout 등)를 사용한다는 점도 함께 기억해 두세요.

4단계 — AndroidManifest.xml 설정

마지막으로 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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 옵션 목록에서 자신의 모바일 기기를 선택하세요. 그러면 아래와 같은 기본 화면이 기기에 표시됩니다.

안드로이드 알림 클릭 시 새 인텐트 생성 없이 기존 액티비티 재개하는 방법

'알림 생성' 버튼을 누르면 상태 바에 알림이 나타납니다. 이후 홈 버튼으로 앱을 백그라운드로 보낸 상태에서 해당 알림을 탭해 보세요. 새로운 액티비티 인스턴스가 생성되지 않고 기존 MainActivity가 그대로 화면 앞으로 재개되는 것을 확인할 수 있습니다.