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

안드로이드 알림 클릭 시 액티비티를 시작하는 방법 완벽 가이드

이 튜토리얼에서는 사용자가 알림(Notification)을 클릭했을 때 특정 안드로이드 액티비티를 시작하는 방법을 단계별로 살펴봅니다. 핵심은 PendingIntent를 활용해 알림과 액티비티를 연결하는 것입니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project를 선택하고, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성 (activity_main.xml)

다음 코드를 res/layout/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_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_centerInParent="true"
        android:text="Create Notification" />

</RelativeLayout>

3단계: 메인 액티비티 구현 (MainActivity)

다음 코드를 src/MainActivity에 추가합니다. 이 코드의 핵심 흐름은 다음과 같습니다.

  • Intent 생성: 알림 클릭 시 열리고자 하는 대상 액티비티를 지정합니다.
  • PendingIntent 등록: PendingIntent.getActivity()를 통해 나중에(알림 클릭 시점에) 실행될 인텐트를 시스템에 전달합니다.
  • 알림 빌더 구성: 제목, 본문, 아이콘, 그리고 위에서 만든 PendingIntent를 알림에 설정합니다.
  • 알림 채널 처리: Android 8.0(Oreo) 이상에서는 반드시 알림 채널을 생성해야 하므로 SDK 버전을 확인한 후 채널을 만듭니다.
package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
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로 감싸서 알림에 연결
                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0);

                NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
                mBuilder.setContentTitle("My Notification");
                mBuilder.setContentText("Notification Listener Service Example");
                mBuilder.setTicker("Notification Listener Service Example");
                mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
                mBuilder.setContentIntent(pendingIntent);   // 핵심: 클릭 시 액티비티 실행
                mBuilder.setAutoCancel(true);               // 클릭 후 알림 자동 삭제

                // Android 8.0(O) 이상에서는 알림 채널 필수
                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());
            }
        });
    }
}

주요 포인트 정리

  • FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP 플래그를 사용하면 이미 실행 중인 액티비티가 있을 때 새 인스턴스를 만들지 않고 기존 인스턴스를 재사용합니다.
  • setAutoCancel(true)를 호출하면 사용자가 알림을 탭했을 때 알림이 자동으로 사라집니다.

4단계: 매니페스트 설정 (AndroidManifest.xml)

다음 코드를 AndroidManifest.xml에 추가합니다. 진동 권한과 함께 MainActivity가 런처 액티비티로 등록되어 있는지 확인하세요.

<?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>

    </application>
</manifest>

앱 실행 및 결과 확인

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

안드로이드 알림 클릭 시 액티비티를 시작하는 방법 완벽 가이드

Create Notification 버튼을 누르면 상태바에 알림이 생성되고, 해당 알림을 탭하면 설정된 PendingIntent에 의해 MainActivity가 다시 시작되는 것을 확인할 수 있습니다.

안드로이드 알림 클릭 시 액티비티를 시작하는 방법 완벽 가이드