이 튜토리얼에서는 Android에서 액티비티가 알림(Notification)을 통해 실행되었는지 확인하는 방법을 단계별로 살펴봅니다.
핵심 원리는 간단합니다. 알림을 생성할 때 PendingIntent에 담기는 Intent에 커스텀 플래그(Extra)를 추가하고, 액티비티의 onCreate() 메서드에서 해당 값을 확인하면 됩니다. 이를 통해 사용자가 알림을 탭해서 들어왔는지, 아니면 일반적인 방법으로 앱을 실행했는지 구분할 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio를 열고 File → New Project를 선택한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.
2단계 — 레이아웃 파일 작성
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.java 파일에 아래 코드를 추가합니다. 이 코드가 이 예제의 핵심 부분입니다.
주목할 부분은 두 곳입니다. 첫째, createNotification() 메서드에서 Intent에 putExtra("fromNotification", true)로 알림 발신 여부를 표시합니다. 둘째, onCreate()에서 getIntent().getExtras()를 통해 이 값을 읽어 알림으로부터 호출되었는지 판단합니다.
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.util.Log;
import android.view.View;
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);
// 인텐트에 Extra 값이 있는지 확인하여 알림 경유 여부 판단
if (getIntent().getExtras() != null) {
Bundle b = getIntent().getExtras();
boolean cameFromNotification = b.getBoolean("fromNotification");
Log.i("Came from notification", String.valueOf(cameFromNotification));
}
}
public void createNotification(View view) {
// 알림 탭 시 열릴 인텐트에 출처 표시용 Extra 추가
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.putExtra("fromNotification", true);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(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.setContentIntent(pendingIntent);
mBuilder.setContentText("Notification Listener Service Example");
mBuilder.setTicker("Notification Listener Service Example");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true);
// Android 8.0(Oreo) 이상에서는 알림 채널 생성 필수
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());
}
}동작 원리 정리
- 알림 생성 시: 알림을 눌렀을 때 열릴 Intent에
fromNotification = true라는 Extra를 넣어 PendingIntent로 감쌉니다. - 액티비티 진입 시: onCreate()에서 getIntent()의 Extras에 해당 키가 존재하는지 확인합니다.
- 판단 결과: 값이 true이면 알림을 통해 호출된 것이고, Extra가 없으면 일반 실행(런처 아이콘 클릭 등)입니다.
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">
<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 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 연결된 모바일 기기를 선택하면, 기본 화면이 기기에 표시됩니다.
버튼을 눌러 알림을 생성한 후, 상단 바를 내려 해당 알림을 탭하면 Logcat에 Came from notification: true가 출력되는 것을 확인할 수 있습니다. 반면 앱 아이콘으로 직접 실행하면 이 로그가 출력되지 않거나 false로 표시됩니다.

