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

앱을 열지 않고 Android 알림 액션 구현하는 방법

앱을 열지 않고 Android 알림 액션 구현하기

이 튜토리얼에서는 사용자가 앱을 직접 실행하지 않고도 알림 자체에서 동작을 수행하도록 Android 알림 액션을 구현하는 방법을 소개합니다. 핵심 아이디어는 BroadcastReceiverPendingIntent를 조합하는 것입니다. 알림에 추가된 버튼(예: '취소')을 누르면 브로드캐스트가 발생하고, 리시버가 이를 받아 알림을 제거하는 식으로 동작합니다.

전체 흐름은 다음과 같습니다.

  • 알림 생성 시 PendingIntent.getBroadcast()로 브로드캐스트 인텐트를 만들어 액션 버튼에 연결합니다.
  • 사용자가 알림의 버튼을 탭하면 시스템이 BroadcastReceiver를 호출합니다.
  • 리시버는 인텐트에 담긴 알림 ID를 꺼내 해당 알림을 취소(cancel)합니다.

그럼 단계별로 살펴보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project로 이동해 새 프로젝트를 만들고, 필요한 모든 정보를 입력해 프로젝트를 생성합니다.

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

메인 화면에는 알림을 생성하는 버튼 하나만 배치합니다. 아래 코드를 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:onClick="createNotification"
        android:text="create notification"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

3단계 — 메인 액티비티 작성 (src/MainActivity.java)

버튼이 클릭되면 createNotification() 메서드가 호출되어 알림을 생성합니다. 여기서 주목할 부분은 두 가지입니다.

  • btPendingIntent: 알림의 '취소' 액션 버튼에 연결되는 브로드캐스트 PendingIntent입니다.
  • getDeleteIntent(): 사용자가 알림을 스와이프로 지울 때도 리시버가 호출되도록 설정하는 삭제 인텐트입니다.

또한 Android 8.0(API 26, 오레오) 이상에서는 반드시 알림 채널(NotificationChannel)을 생성해야 하므로 SDK 버전을 확인한 후 채널을 등록합니다.

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.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) {
        int NOTIFICATION_ID = (int) System.currentTimeMillis();
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);

        Intent buttonIntent = new Intent(this, NotificationBroadcastReceiver.class);
        buttonIntent.putExtra("notificationId", NOTIFICATION_ID);
        PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent, 0);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), default_notification_channel_id);
        mBuilder.setContentTitle("My Notification");
        mBuilder.setContentIntent(pendingIntent);
        mBuilder.addAction(R.drawable.ic_launcher_foreground, "Cancel", btPendingIntent);
        mBuilder.setContentText("Notification Listener Service Example");
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);
        mBuilder.setDeleteIntent(getDeleteIntent());

        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(NOTIFICATION_ID, mBuilder.build());
    }

    protected PendingIntent getDeleteIntent() {
        Intent intent = new Intent(MainActivity.this, NotificationBroadcastReceiver.class);
        intent.setAction("notification_cancelled");
        return PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    }
}

4단계 — 브로드캐스트 리시버 작성 (src/NotificationBroadcastReceiver.java)

리시버는 인텐트로 전달받은 notificationId를 읽어 해당 알림을 취소합니다. 이 덕분에 앱을 열지 않고도 알림의 '취소' 버튼만으로 알림을 제거할 수 있습니다.

package app.tutorialspoint.com.notifyme;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class NotificationBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        int notificationId = intent.getIntExtra("notificationId", 0);
        // 알림을 취소하려는 경우
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(notificationId);
    }
}

5단계 — 매니페스트 설정 (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" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

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

        <receiver
            android:name=".NotificationBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
        </receiver>

        <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 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요. 기기의 기본 화면이 표시되면 'create notification' 버튼을 눌러 알림을 생성한 후, 알림의 '취소' 버튼을 탭했을 때 앱을 열지 않고도 알림이 사라지는지 확인하면 됩니다.