본문 바로가기
프로그램 개발해서 돈벌기/Android

[Java] 안드로이드 서비스에서 Local Notification 보내기

by ubmuhan 2023. 6. 26.
반응형

build.gradle 종속성에 추가

dependencies {
    implementation 'com.android.support:support-compat:28.0.0'
}
 

 

Notification 채널 생성: Android 8.0 (API 레벨 26)부터 알림 채널을 사용해야 합니다. Application 클래스 또는 액티비티에서 아래의 코드를 사용하여 채널을 생성합니다.

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

public class NotificationUtils {
    public static final String CHANNEL_ID = "my_channel_id";

    public static void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "My Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = context.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }
}

 

Local Notification 보내기

private void sendToMeNotification(String strInfo) {
    // 알림 채널 생성
    NotificationUtils.createNotificationChannel(this);

    // 알림 인텐트 생성
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(
            this,
            0,
            notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE
    );

    // 알림 빌더 생성
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NotificationUtils.CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("알림")
            .setContentText(strInfo)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    // 알림 매니저를 통해 알림 보내기
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(NOTIFICATION_ID, builder.build());
}

 

 

사용법

sendToMeNotification("알림을 보냅니다.");

 

 

 

반응형

댓글