반응형
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("알림을 보냅니다.");
반응형
'프로그램 개발해서 돈벌기 > Android' 카테고리의 다른 글
안드로이드 13 (Target SDK API 33) 이후부터 포그라운드 서비스 시작 시 자동으로 시작하던 알림(Local Notification)이 동작되지 않는 경우 해결 방법 (0) | 2023.09.20 |
---|---|
[Java] 안드로이드에서 크롬캐스트 연결 시 "전송 대상" 선택 후 앱 죽는 현상에 대한 해결 방법 (0) | 2023.06.27 |
[Java] 안드로이드 Activity와 Forground Service에서 위치 값 가져오기 (0) | 2023.06.26 |
[Java] 안드로이드에서 싱글톤(Singleton) 클래스와 사용법 예제 (0) | 2023.06.26 |
android studio refactor를 이용해서 패키지명을 바꾸었을 때 R 인식을 못하는 이유는? 해결 방법은? (0) | 2023.06.26 |
댓글