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

안드로이드 알림(Notification)에 정확히 3개의 작업 버튼을 표시하는 방법

이 예제는 안드로이드에서 알림(Notification)에 정확히 3개의 작업(Action) 버튼을 표시하는 방법과 함께, 액티비티가 알림을 통해 호출되었는지 판별하는 방법까지 다룹니다. 핵심은 알림 클릭 시 실행되는 PendingIntent에 식별용 데이터를 담아 전달하고, addAction() 메서드를 세 번 호출해 원하는 개수만큼 버튼을 추가하는 것입니다.

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단계 — 메인 액티비티 구현 (src/MainActivity.java)

핵심 로직이 담긴 부분입니다. 아래 코드를 추가합니다.

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) {
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        // 알림에서 실행되었음을 표시하는 플래그를 Extra로 전달합니다.
        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);

        // addAction()을 세 번 호출해 정확히 3개의 작업 버튼을 추가합니다.
        mBuilder.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action, "Action1", pendingIntent).build());
        mBuilder.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action, "Action2", pendingIntent).build());
        mBuilder.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action, "Action3", pendingIntent).build());

        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(오레오, API 26) 이상에서는 알림 채널 생성이 필수입니다.
        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());
    }
}

주요 포인트 정리

  • 3개의 작업 버튼 추가: mBuilder.addAction()을 세 번 호출하여 Action1, Action2, Action3 버튼을 알림에 표시합니다. 필요에 따라 호출 횟수를 조절해 버튼 개수를 바꿀 수 있습니다.
  • 알림 호출 여부 확인: 인텐트에 putExtra("fromNotification", true)로 플래그를 담고, onCreate()에서 getIntent().getExtras()로 이 값을 읽어 알림을 통해 실행되었는지 로그로 확인합니다.
  • 인텐트 플래그: FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP을 지정해 이미 실행 중인 액티비티가 있다면 새로 만들지 않고 재사용하도록 합니다.
  • 알림 채널: Android 8.0(오레오)부터는 NotificationChannel을 생성하지 않으면 알림이 표시되지 않으므로, SDK 버전을 체크해 분기 처리합니다.
  • 자동 취소: setAutoCancel(true)로 설정해 알림을 탭하면 알림창에서 자동으로 사라지게 합니다.

4단계 — 매니페스트 설정 (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 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기에 아래와 같은 기본 화면이 표시됩니다.

안드로이드 알림(Notification)에 정확히 3개의 작업 버튼을 표시하는 방법