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

안드로이드에서 새로운 알림(Notification)을 감지하는 방법 — 단계별 완전 가이드

개요

이 튜토리얼에서는 NotificationListenerService를 활용하여 안드로이드 기기에서 발생하는 새로운 알림을 실시간으로 감지하는 방법을 단계별로 알아봅니다. 예제 앱은 스스로 알림을 하나 생성한 뒤, 해당 알림이 게시(post)되거나 제거(remove)될 때 이를 감지하여 화면에 패키지 이름을 출력합니다.

1단계: 새 프로젝트 생성

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

2단계: 리스너 인터페이스 작성 — src/MyListener.java

서비스에서 감지한 알림 이벤트를 액티비티로 전달하기 위한 콜백 인터페이스입니다. 아래 코드를 MyListener.java 파일에 추가하세요.

public interface MyListener {
    void setValue(String packageName);
}

3단계: 알림 리스너 서비스 구현 — src/NotificationService.java

NotificationListenerService를 상속받아, 알림이 게시되거나 제거될 때 호출되는 콜백(onNotificationPosted, onNotificationRemoved)을 처리합니다. 감지된 알림의 ID, 티커 텍스트, 패키지 이름을 로그로 남기고 리스너를 통해 전달합니다.

package app.tutorialspoint.com.notifyme;
import android.content.Context;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
public class NotificationService extends NotificationListenerService {
    private String TAG = this.getClass().getSimpleName();
    Context context;
    static MyListener myListener;
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.i(TAG, "********** onNotificationPosted");
        Log.i(TAG, "ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
        myListener.setValue("Post: " + sbn.getPackageName());
    }
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.i(TAG, "********** onNotificationRemoved");
        Log.i(TAG, "ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
        myListener.setValue("Remove: " + sbn.getPackageName());
    }
    public void setListener(MyListener myListener) {
        NotificationService.myListener = myListener;
    }
}

4단계: 메뉴 리소스 추가 — res/menu/menu_main.xml

옵션 메뉴에서 '설정(Settings)' 항목을 선택하면 알림 접근 권한 설정 화면으로 이동할 수 있도록 메뉴를 정의합니다.

<?xml version="1.0" encoding="utf-8"?>
<menu 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"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="Settings"
        app:showAsAction="never" />
</menu>

5단계: 레이아웃 작성 — res/layout/activity_main.xml

상단에는 알림을 생성하는 버튼을, 하단에는 감지 결과를 표시할 TextView를 스크롤뷰와 함께 배치합니다.

<?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_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:text="Create Notification" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btnCreateNotification"
        android:layout_alignStart="@+id/btnCreateNotification"
        android:layout_alignEnd="@+id/btnCreateNotification"
        android:layout_alignParentBottom="true">
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="NotificationListenerService Example"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </ScrollView>
</RelativeLayout>

6단계: 메인 액티비티 구현 — src/MainActivity.java

버튼 클릭 시 알림을 생성하고, 서비스로부터 전달받은 알림 정보를 화면에 출력합니다. Android 8.0(오레오, API 26) 이상에서는 반드시 알림 채널(Notification Channel)을 생성해야 하므로 버전 분기 처리도 포함되어 있습니다.

package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements MyListener {
    private TextView txtView;
    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);
        new NotificationService().setListener(this);
        txtView = findViewById(R.id.textView);
        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                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());
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu); //Menu Resource, Menu
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    @Override
    public void setValue(String packageName) {
        txtView.append("\n" + packageName);
    }
}

7단계: 매니페스트 설정 — AndroidManifest.xml

알림 감지 서비스를 등록하고 BIND_NOTIFICATION_LISTENER_SERVICE 권한을 선언합니다. 이 선언이 누락되면 시스템이 서비스를 바인딩하지 못해 알림을 전혀 감지할 수 없으므로 반드시 포함해야 합니다.

<?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>
        <service
            android:name=".NotificationService"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>
    </application>
</manifest>

알림 접근 권한 허용하기

앱이 다른 앱의 알림을 읽으려면 사용자의 명시적인 동의가 필요합니다. 앱 실행 후 옵션 메뉴의 Settings 항목을 탭하면 ACTION_NOTIFICATION_LISTENER_SETTINGS 화면이 열리며, 여기에서 본 앱의 알림 접근 허용(Notification Access)을 켜주세요. 권한이 허용되어야만 onNotificationPosted 콜백이 정상적으로 동작합니다.

앱 실행 및 결과 확인

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

안드로이드에서 새로운 알림(Notification)을 감지하는 방법 — 단계별 완전 가이드

Create Notification 버튼을 누르면 알림이 생성되고, 화면의 TextView에 Post: app.tutorialspoint.com.notifyme 형태로 감지 결과가 실시간으로 추가됩니다. 알림을 삭제하면 Remove: 로그가 함께 기록되는 것도 확인할 수 있습니다.