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

Android에서 상태 표시줄 알림 가로채는 방법 – NotificationListenerService 완벽 가이드

이 튜토리얼에서는 Android 앱에서 NotificationListenerService를 활용해 상태 표시줄에 게시되는 알림을 가로채고, 알림이 추가되거나 제거될 때 이를 실시간으로 감지하는 방법을 단계별로 살펴봅니다.

알림 리스너 서비스는 다른 앱에서 발생한 알림 이벤트(게시, 제거)를 수신할 수 있는 강력한 기능으로, 알림 관리 앱이나 자동화 도구를 만들 때 유용하게 활용됩니다.

Step 1 – 새 프로젝트 생성

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

Step 2 – MyListener 인터페이스 작성

src/MyListener.java 파일에 아래 코드를 추가합니다. 이 인터페이스는 서비스와 액티비티 간에 패키지 이름 정보를 전달하는 콜백 역할을 합니다.

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

Step 3 – NotificationService 클래스 작성

src/NotificationService.java 파일에 아래 코드를 추가합니다. NotificationListenerService를 상속받아 알림이 게시되거나 제거될 때 로그를 출력하고, 리스너를 통해 UI에 정보를 전달합니다.

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

Step 4 – 메뉴 리소스 추가

res/menu/menu_main.xml 파일에 아래 코드를 추가합니다. 이 메뉴 항목은 나중에 알림 접근 권한 설정 화면으로 이동하는 데 사용됩니다.

<?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>

Step 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>

Step 6 – MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 버튼 클릭 시 알림 채널을 생성하고 알림을 게시하며, 메뉴에서 설정 항목을 선택하면 알림 접근 권한 화면으로 이동합니다.

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

Step 7 – AndroidManifest.xml 설정

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>

앱 실행 및 테스트

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

Android에서 상태 표시줄 알림 가로채는 방법 – NotificationListenerService 완벽 가이드

권한 설정 안내

앱이 정상적으로 알림을 감지하려면 먼저 알림 접근 권한을 허용해야 합니다. 앱 우측 상단 메뉴에서 Settings를 선택하면 시스템의 '알림 접근' 설정 화면으로 이동하며, 해당 앱의 권한을 켜면 됩니다. 이후 알림을 생성하면 TextView에 어떤 패키지의 알림이 게시(Post)되었는지, 또는 제거(Remove)되었는지가 실시간으로 표시됩니다.