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

안드로이드 알림 클릭 시 액티비티로 매개변수 전달하는 방법

개요

이 튜토리얼에서는 안드로이드(Android)에서 알림(Notification)을 탭했을 때 액티비티(Activity)로 매개변수를 전달하는 방법을 단계별로 살펴봅니다. 핵심 원리는 간단합니다. 알림 클릭 시 실행될 Intent에 putExtra()로 데이터를 담고, 이를 PendingIntent로 감싸 알림에 연결한 뒤, 액티비티 쪽에서는 onNewIntent()를 통해 전달된 데이터를 꺼내 사용하는 것입니다.

1단계 — 새 프로젝트 만들기

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

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

메인 레이아웃에는 알림에서 전달받은 메시지를 표시할 TextView와, 알림을 생성하는 Button을 배치합니다. 아래 코드를 추가하세요.

<?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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvNotify"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnNotify"
        android:layout_margin="16dp" />

    <Button
        android:id="@+id/btnNotify"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:onClick="createNotification"
        android:text="알림 생성" />
</RelativeLayout>

3단계 — MainActivity.java 구현

이제 알림을 생성하는 로직과, 알림 클릭 시 전달된 데이터를 처리하는 코드를 MainActivity에 추가합니다.

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

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

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle extras = intent.getExtras();
        if (extras != null) {
            if (extras.containsKey("NotificationMessage")) {
                String msg = extras.getString("NotificationMessage");
                TextView tvNotify = findViewById(R.id.tvNotify);
                tvNotify.setText(msg);
            }
        }
    }

    public void createNotification(View view) {
        Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
        notificationIntent.putExtra("NotificationMessage", "알림에서 전달된 메시지입니다");
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        notificationIntent.setAction(Intent.ACTION_MAIN);
        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("테스트")
                .setContentText("안녕하세요! 첫 번째 푸시 알림입니다")
                .setContentIntent(resultIntent);

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

코드 핵심 포인트

  • putExtra()로 데이터 담기: 알림 클릭 시 열릴 Intent에 "NotificationMessage"라는 키로 문자열을 저장하여 함께 전달합니다.
  • FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP: 액티비티가 이미 실행 중이라면 새 인스턴스를 만들지 않고 기존 인스턴스를 재사용하며, 이때 onNewIntent()가 호출되어 전달된 데이터를 받을 수 있습니다.
  • onNewIntent()에서 extras 읽기: 최초 진입 시에는 onCreate()에서 getIntent()로 데이터를 확인하고, 이후 알림 클릭 시에는 onNewIntent()를 통해 메시지를 받아 TextView에 표시합니다.
  • 알림 채널(NotificationChannel): Android 8.0(오레오, API 26) 이상에서는 반드시 알림 채널을 생성해야 알림이 정상적으로 표시됩니다.

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>

앱 실행하고 결과 확인하기

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

버튼을 눌러 알림을 생성한 후, 상단 알림창을 내려 해당 알림을 탭해 보세요. "알림에서 전달된 메시지입니다"라는 문구가 화면의 TextView에 나타나는 것을 확인할 수 있습니다. 이로써 알림 클릭 → 액티비티 매개변수 전달이 정상적으로 동작하는 것입니다.