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

Android에서 알림(Notification)을 탭해 액티비티 실행하기 — PendingIntent 활용 가이드

Android에서 알림을 탭해 액티비티 시작하기

앱이 백그라운드에 있을 때 사용자에게 정보를 전달하고, 알림을 탭하면 원하는 화면으로 이동하게 만드는 것은 모바일 앱 개발의 핵심 기능 중 하나입니다. 이 튜토리얼에서는 PendingIntent를 활용해 알림(Notification)을 탭했을 때 액티비티(Activity)가 실행되도록 구현하는 방법을 단계별로 살펴봅니다.

1단계 — 새 프로젝트 생성

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

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

화면 중앙에 'Create notification' 버튼 하나를 배치하는 간단한 레이아웃입니다. 아래 코드를 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="Create notification"
        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 작성

버튼을 클릭하면 알림이 생성되며, 이 알림에는 MainActivity를 여는 PendingIntent가 설정됩니다. 핵심 동작은 다음과 같습니다.

  • PendingIntent.getActivity() : 알림이 탭되었을 때 실행할 인텐트를 감싸는 객체를 생성합니다.
  • NotificationChannel : Android 8.0(오레오, API 26)부터는 모든 알림이 반드시 채널에 할당되어야 하므로, OS 버전을 확인한 뒤 채널을 생성합니다.
  • IMPORTANCE_HIGH : 알림 중요도를 높게 설정해 헤드업(head-up) 형태로 표시되도록 합니다.
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 intent = new Intent(MainActivity.this, MainActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentIntent(contentIntent)
                        .setContentTitle("Test")
                        .setContentText("Hello! This is my first push notification");

                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());
            }
        });
    }
}

4단계 — AndroidManifest.xml 설정

MainActivity가 런처(LAUNCHER) 액티비티로 등록되어 있는지 확인합니다. 알림 탭 시 이 액티비티가 다시 실행됩니다.

<?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 아이콘을 클릭하고, 목록에서 실행할 기기를 선택하세요. 앱이 설치되면 기본 화면이 표시됩니다.

Android에서 알림(Notification)을 탭해 액티비티 실행하기 — PendingIntent 활용 가이드

Android에서 알림(Notification)을 탭해 액티비티 실행하기 — PendingIntent 활용 가이드

Android에서 알림(Notification)을 탭해 액티비티 실행하기 — PendingIntent 활용 가이드

'Create notification' 버튼을 누르면 알림이 발생하고, 상단 바를 내려 해당 알림을 탭하면 MainActivity가 다시 실행되는 것을 확인할 수 있습니다.

참고 사항

위 예제는 이전 버전의 서포트 라이브러리(android.support)를 기준으로 작성되었습니다. 최신 AndroidX 기반 프로젝트에서는 androidx.core.app.NotificationCompat, androidx.appcompat.app.AppCompatActivity를 사용하고, ConstraintLayout 역시 androidx.constraintlayout.widget.ConstraintLayout으로 임포트하면 동일하게 동작합니다.