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

안드로이드에서 알림 발생을 감지하는 방법 – NotificationListenerService 구현 가이드

안드로이드 앱을 개발하다 보면 다른 앱에서 발생한 알림(Notification)을 감지해야 하는 경우가 있습니다. 예를 들어 메시지가 도착했을 때 자동으로 특정 작업을 수행하거나, 알림 내용을 분석하는 기능을 만들 때가 그렇습니다.

이번 튜토리얼에서는 안드로이드의 NotificationListenerService를 활용해 알림이 발생했을 때 이를 감지(수신 대기)하는 방법을 단계별로 살펴보겠습니다. 먼저 알림을 생성하는 기본 앱을 만들고, 이후 리스너 서비스를 통해 해당 알림을 감지하는 구조를 이해할 수 있습니다.

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.java 파일에 아래 코드를 작성합니다. 여기서는 NotificationCompat.Builder를 사용해 알림을 만들고, 안드로이드 8.0(오레오, API 26) 이상에서는 반드시 알림 채널(NotificationChannel)을 생성해야 한다는 점에 유의하세요.

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
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);
    }

    public void createNotification(View view) {
        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.setAutoCancel(true);

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

코드 핵심 포인트:

  • setContentTitle / setContentText: 알림의 제목과 본문 텍스트를 설정합니다.
  • setAutoCancel(true): 사용자가 알림을 탭하면 자동으로 삭제됩니다.
  • 알림 채널 처리: API 26 이상에서는 채널을 지정하지 않으면 알림이 표시되지 않으므로 버전 체크가 필수입니다.
  • notify() 호출: 고유 ID로 알림을 발생시키며, 여기서는 현재 시간을 ID로 사용했습니다.

4단계: AndroidManifest.xml 설정하기

진동 권한(VIBRATE)을 포함한 매니페스트 설정입니다. 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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 연결된 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 알림 발생을 감지하는 방법 – NotificationListenerService 구현 가이드

화면 중앙의 Create Notification 버튼을 누르면 다음과 같이 알림이 정상적으로 생성되는 것을 확인할 수 있습니다.

안드로이드에서 알림 발생을 감지하는 방법 – NotificationListenerService 구현 가이드

마무리 및 다음 단계

여기까지 진행하면 알림을 생성하는 쪽의 준비가 완료된 것입니다. 실제로 알림을 감지하려면 이어서 NotificationListenerService를 상속받는 서비스 클래스를 구현하고, 매니페스트에 서비스를 등록한 후 사용자에게 알림 접근 권한을 요청해야 합니다. 이 과정을 거치면 다른 앱에서 발생하는 모든 알림의 제목, 내용, 패키지 정보 등을 실시간으로 읽어올 수 있어, 알림 관리 앱이나 자동화 도구 개발에 활용할 수 있습니다.