안드로이드 특정 시간 푸시 알림 | 설정푸시알림 27715 투표 이 답변

당신은 주제를 찾고 있습니까 “안드로이드 특정 시간 푸시 알림 – 설정푸시알림“? 다음 카테고리의 웹사이트 you.maxfit.vn 에서 귀하의 모든 질문에 답변해 드립니다: https://you.maxfit.vn/blog. 바로 아래에서 답을 찾을 수 있습니다. 작성자 safe kids 이(가) 작성한 기사에는 조회수 78회 및 155181 Like 개의 좋아요가 있습니다.

안드로이드 특정 시간 푸시 알림 주제에 대한 동영상 보기

여기에서 이 주제에 대한 비디오를 시청하십시오. 주의 깊게 살펴보고 읽고 있는 내용에 대한 피드백을 제공하세요!

d여기에서 설정푸시알림 – 안드로이드 특정 시간 푸시 알림 주제에 대한 세부정보를 참조하세요

안드로이드 특정 시간 푸시 알림 주제에 대한 자세한 내용은 여기를 참조하세요.

Android | 특정 시간에 푸시알림 보내기 #001 – 알림 설정

진행 중인 프로젝트에서 특정 시간에 맞춰 사용자에게 Notification을 보내야 하는 작업이 있어 정리하였다. 푸시알림 switch 활성화 시 정해진 …

+ 여기에 표시

Source: 8iggy.tistory.com

Date Published: 6/6/2021

View: 6663

[Android Studio] 날짜, 시간 지정 후 Notification(푸시 알림) 받기

[Andro Studio] 날짜, 시간 지정 후 Notification(푸시 알림) 받기. 윌리블리 2020. 5. 27. 19:46. 날짜, 시간을 String으로 지정한 후 정해진 시간에 푸시 알림을 …

+ 더 읽기

Source: always-21.tistory.com

Date Published: 1/12/2021

View: 6905

[안드로이드] Local Notification 매일 특정 시간에 보내기

Set/Cancel Alarm. Cancel 할 경우와 Set 할 경우에 해당한다. 매일 일정 시각에 알람을 반복을 위해서는 alarmManager.setRepeating에서 AlarmManager.

+ 여기에 표시

Source: yejinson97gaegul.tistory.com

Date Published: 1/19/2021

View: 363

안드로이드(android) 특정한 시간에 푸시(푸쉬-notification)가 …

해당 폰에서는 permission을 줬기 때문에 노티피케이션(푸쉬)가 올 때 알람이 진동이 발생한다. 특정하게 알람을 줄 때 안줄때를 Client에서 결정하게 할 …

+ 여기에 자세히 보기

Source: kwongyo.tistory.com

Date Published: 7/23/2021

View: 7755

[안드로이드]정해진 시간에 알람 울리는 방법 Notification …

2020.12.25 – [안드로이드] – [안드로이드]Notification 간단한 알림 띄우기 … 2. AlarmManager를 통해 정해진 시간이 되면 알람으로 알려준다.

+ 여기에 자세히 보기

Source: aries574.tistory.com

Date Published: 7/27/2021

View: 5567

[Android] 안드로이드 푸시 알림 (Notification)

setTimeoutAfter() : 지정한 시간 이후 알림이 취소된다. (화면에서 사라진다); notify() : 생성한 notification을 등록한다. 가 같으면 1개의 …

+ 여기에 더 보기

Source: mrw0119.tistory.com

Date Published: 1/10/2022

View: 7216

[Android] AlarmManager 로 알림(Notification) 구현하기 – 그냥.

-> 네트워크 작업은 동기화 어댑터와 함께 서버에서 직접 사용하는 것이 훨씬 더 유연하고, 만약 정확한 시간에 호출되어 동기화하는 알람이라면 그 앱의 …

+ 더 읽기

Source: hanyeop.tistory.com

Date Published: 2/16/2021

View: 1600

일정관리 앱에 푸시알림 추가하기

일정관리 앱을 만들던 중 일정에 해당하는 날짜의 특정 시간에 푸시알림 기능을 추가하기 위해 AlarmManager,Receiver, Service를 사용하게 되었다.

+ 여기에 표시

Source: funnydev.tistory.com

Date Published: 6/9/2021

View: 9291

특정 시간동안 앱 푸시 알림을 꺼두고 싶어요. – 아지트 도움말 센터

안드로이드 앱에서 방해 금지 모드 설정하기 업무 외 시간에 푸시 알림 수신을 원하지 않는다면 방해금지 모드를 설정해보세요. 설정한 시간동안에는 …

+ 여기에 보기

Source: help.agit.io

Date Published: 2/18/2021

View: 2772

[Android] FCM 푸시 알림(Notification) – 준영;한 개발자

개발 전 미리 FCM을 이용한 푸시 알림에 대해 공부하려고 포스팅을 작성하게 되었다. FCM. Firebase 클라우드 메시징(FCM)은 무료로 메시지를 안정적으로 …

+ 여기에 표시

Source: junyoung-developer.tistory.com

Date Published: 2/3/2022

View: 9864

주제와 관련된 이미지 안드로이드 특정 시간 푸시 알림

주제와 관련된 더 많은 사진을 참조하십시오 설정푸시알림. 댓글에서 더 많은 관련 이미지를 보거나 필요한 경우 더 많은 관련 기사를 볼 수 있습니다.

설정푸시알림
설정푸시알림

주제에 대한 기사 평가 안드로이드 특정 시간 푸시 알림

  • Author: safe kids
  • Views: 조회수 78회
  • Likes: 155181 Like
  • Date Published: 2019. 8. 29.
  • Video Url link: https://www.youtube.com/watch?v=rPcZ8caRaMI

Android | 특정 시간에 푸시알림 보내기 #001 – 알림 설정

Notification 생성하기

읽기 전

불필요한 코드나 잘못 작성된 내용에 대한 지적은 언제나 환영합니다.

개인적으로 사용해보면서 배운 점을 정리한 글입니다.

전체 프로젝트 코드는 깃헙 링크 – MyNotification에 올려두겠습니다. 참고해주세요.

진행 중인 프로젝트에서 특정 시간에 맞춰 사용자에게 Notification을 보내야 하는 작업이 있어 정리하였다. 푸시알림 switch 활성화 시 정해진 시간(오전/오후 8시, 9시)에 Notification을 생성하여 사용자에게 전달하는 기능을 구현해보려 한다. 그리고 네트워크 차단 및 앱을 kill해도 백그라운드를 안정적으로 유지하여 특정 시간에 알림을 보내기위해 WorkManager를 채택하였다.

전체 구조

Notification 설정 및 정의

Notification Channel 생성

안드로이드 오레오 이전까지는 채널 생성을 하지 않아도 Notification을 띄울 수 있었지만 이후부턴 Channel을 생성한 뒤 Channel ID를 부여해야 한다. 앱에 대해 단 한번만 생성하면 되고 이후 재호출 해도 같은 Paramerter에 대해 어떠한 동작을 하지 않으므로 재호출해도 된다고 공식문서에 쓰여있다. 그래서 Application을 상속받는 클래스에서 호출하게 하였다.

NotificationHelper.class – 채널 생성

// 한번 실행 시 이후 재호출해도 동작 안함 public static void createNotificationChannel(Context context) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // NotificationChannel 초기화 NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT); // Configure the notification channel notificationChannel.setDescription(“푸시알림”); notificationChannel.enableLights(true); // 화면활성화 설정 notificationChannel.setVibrationPattern(new long[]{0, 1000, 500}); // 진동패턴 설정 notificationChannel.enableVibration(true); // 진동 설정 notificationManager.createNotificationChannel(notificationChannel); // channel 생성 } } catch (NullPointerException nullException) { // notificationManager null 오류 raise Toast.makeText(context, “푸시 알림 채널 생성에 실패했습니다. 앱을 재실행하거나 재설치해주세요.”, Toast.LENGTH_SHORT).show(); nullException.printStackTrace(); } }

InitApplication.class – 채널 생성 메소드 호출

public class InitApplication extends Application { private Context mContext; @Override public void onCreate() { super.onCreate(); NotificationHelper.createNotificationChannel(getApplicationContext()); } }

AndroidManifest.xml – InitApplication.class 등록

name에 등록하여 앱 시작 시 InitApplication 클래스를 거치도록 하였다.

Notification 생성 및 동작 정의

일반적으로 푸시알림을 클릭할 때 로그인 절차가 필요 없다면 해당 액티비티를 활성화하여 사용자에게 정보를 제공하겠지만 로그인 절차가 필요하다면 앱을 launch하여 의도된 페이지까지 유도하는 방식이 바람직하다고 생각한다. 그리고 앱을 kill하지 않고 단지 home을 눌러 대기열에 내려둔 상태라면 재시작이 아니라 대기열에 있는 app을 화면으로 끌어올려 로드하는 방식으로 구현하였다. 두 가지의 푸시알림을 별도로 생성하기 위해 Notification code를 다르게 설정하였다.

NotificationHelper.class – 푸시알림 생성 및 동작 정의

private static final Integer WORK_A_NOTIFICATION_CODE = 0; private static final Integer WORK_B_NOTIFICATION_CODE = 1; public void createNotification(String workName) { // 클릭 시 MainActivity 호출 Intent intent = new Intent(mContext, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); // 대기열에 이미 있다면 MainActivity가 아닌 앱 활성화 intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); // Notificatoin을 이루는 공통 부분 정의 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID); notificationBuilder.setSmallIcon(R.drawable.smile) // 기본 제공되는 이미지 .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setAutoCancel(true); // 클릭 시 Notification 제거 // A이벤트 알림을 생성한다면 if (workName.equals(WORK_A_NAME)) { // Notification 클릭 시 동작할 Intent 입력, 중복 방지를 위해 FLAG_CANCEL_CURRENT로 설정, CODE를 다르게하면 개별 생성 // Code가 같으면 같은 알림으로 인식하여 갱신작업 진행 PendingIntent pendingIntent = PendingIntent.getActivity(mContext, WORK_A_NOTIFICATION_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT); // Notification 제목, 컨텐츠 설정 notificationBuilder.setContentTitle(“WorkerA Notification”).setContentText(“set a Notification contents”) .setContentIntent(pendingIntent); if (notificationManager != null) { notificationManager.notify(WORK_A_NOTIFICATION_CODE, notificationBuilder.build()); } } else if (workName.equals(WORK_B_NAME)) { PendingIntent pendingIntent = PendingIntent.getActivity(mContext, WORK_B_NOTIFICATION_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT); notificationBuilder.setContentTitle(“WorkerB Notification”).setContentText(“set a Notification contents”) .setContentIntent(pendingIntent); if (notificationManager != null) { notificationManager.notify(WORK_B_NOTIFICATION_CODE, notificationBuilder.build()); } } }

이제 Notification 관련 정의는 끝났으니 사용자가 특정 액션을 취했을 때 푸시알림을 생성하게끔 연결하면 된다.

참고자료

[Android Studio] 날짜, 시간 지정 후 Notification(푸시 알림) 받기

날짜, 시간을 String으로 지정한 후 정해진 시간에 푸시 알림을 받아보겠습니다.

1. Manifest에 다음과 같은 소스를 추가해줍니다.

AndroidManifest.xml

2. MainActivity.class

package com.example.alarmtest; //패키지명 import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; public class MainActivity extends AppCompatActivity { private AlarmManager alarmManager; private GregorianCalendar mCalender; private NotificationManager notificationManager; NotificationCompat.Builder builder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); mCalender = new GregorianCalendar(); Log.v(“HelloAlarmActivity”, mCalender.getTime().toString()); setContentView(R.layout.activity_main); //접수일 알람 버튼 Button button = (Button) findViewById(R.id.btnNoti); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setAlarm(); } }); } private void setAlarm() { //AlarmReceiver에 값 전달 Intent receiverIntent = new Intent(MainActivity.this, AlarmRecevier.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, receiverIntent, 0); String from = “2020-05-27 10:31:00”; //임의로 날짜와 시간을 지정 //날짜 포맷을 바꿔주는 소스코드 SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”); Date datetime = null; try { datetime = dateFormat.parse(from); } catch (ParseException e) { e.printStackTrace(); } Calendar calendar = Calendar.getInstance(); calendar.setTime(datetime); alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),pendingIntent); } }

3.

package com.example.alarmtest; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import androidx.core.app.NotificationCompat; public class AlarmRecevier extends BroadcastReceiver { public AlarmRecevier(){ } NotificationManager manager; NotificationCompat.Builder builder; //오레오 이상은 반드시 채널을 설정해줘야 Notification이 작동함 private static String CHANNEL_ID = “channel1”; private static String CHANNEL_NAME = “Channel1”; @Override public void onReceive(Context context, Intent intent) { AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); builder = null; manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ manager.createNotificationChannel( new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT) ); builder = new NotificationCompat.Builder(context, CHANNEL_ID); } else { builder = new NotificationCompat.Builder(context); } //알림창 클릭 시 activity 화면 부름 Intent intent2 = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context,101,intent2, PendingIntent.FLAG_UPDATE_CURRENT); //알림창 제목 builder.setContentTitle(“알람”); //알림창 아이콘 builder.setSmallIcon(R.drawable.ic_launcher_background); //알림창 터치시 자동 삭제 builder.setAutoCancel(true); builder.setContentIntent(pendingIntent); Notification notification = builder.build(); manager.notify(1,notification); } }

4. 실행화면

2020-05-27 10:31:00에 알람이 울렸습니다

[안드로이드] Local Notification 매일 특정 시간에 보내기

반응형

[안드로이드] Local Notification 매일 특정 시간에 보내기

Gradle 설정

dependencies { //androidx implementation ‘androidx.core:core-ktx:1.7.0’ // 노티피케이션을 위한 패키지 …. }

Manifest 설정

Manifest에 AlarmReceiver 를 등록한다.

안드로이드는 부팅이 끝나면 ‘BOOT_COMPLETED’ 인 intent를 브로드캐스트 한다.

PendingIntent를 이용해 Notification을 사용할 경우, 재부팅 후에는 해당 설정이 증발한다. 따라서, 재부팅 후에도 PendingIntent 가 남아있도록 하려면, Manifest에 부팅 시, BroadCast 를 실행하도록 BOOT_COMPLETED 설정이 필요하다.

Application

Application 에 alarmManager 를 등록하였지만, MainActivity 등, 실제 사용하는 곳에서 선언하여도 무방하다.

internal var alarmManager: AlarmManager? = null class SampleApplication : Application() { …

MainActivity

MainActivity 에서 alarmManager를 할당한다.

override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) … alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager? }

AlarmReceiver

Oreo 이후에는 NotificationChannel 을 생성해야한다.

import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import com.sample.sampleapp.presentation.MainActivity class AlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager createNotificationChannel(context) deliverNotification(context) } private fun createNotificationChannel(context: Context){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel( CHANNEL_ID, // 채널의 아이디 CHANNEL_NAME, // 채널의 이름 NotificationManager.IMPORTANCE_HIGH /* 1. IMPORTANCE_HIGH = 알림음이 울리고 헤드업 알림으로 표시 2. IMPORTANCE_DEFAULT = 알림음 울림 3. IMPORTANCE_LOW = 알림음 없음 4. IMPORTANCE_MIN = 알림음 없고 상태줄 표시 X */ ) notificationChannel.enableLights(true) // 불빛 notificationChannel.lightColor = R.color.accentNormal // 색상 notificationChannel.enableVibration(true) // 진동 여부 notificationChannel.description = context.getString(R.string.app_name) // 채널 정보 notificationManager?.createNotificationChannel( notificationChannel) } } private fun deliverNotification(context: Context){ val contentIntent = Intent(context, MainActivity::class.java) val contentPendingIntent = PendingIntent.getActivity( context, NOTIFICATION_ID, // requestCode contentIntent, // 알림 클릭 시 이동할 인텐트 PendingIntent.FLAG_UPDATE_CURRENT /* 1. FLAG_UPDATE_CURRENT : 현재 PendingIntent를 유지하고, 대신 인텐트의 extra data는 새로 전달된 Intent로 교체 2. FLAG_CANCEL_CURRENT : 현재 인텐트가 이미 등록되어있다면 삭제, 다시 등록 3. FLAG_NO_CREATE : 이미 등록된 인텐트가 있다면, null 4. FLAG_ONE_SHOT : 한번 사용되면, 그 다음에 다시 사용하지 않음 */ ) val builder = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_launcher_foreground) // 아이콘 .setContentTitle(“알람이개굴”) // 제목 .setContentText(“알람 내용이개굴”) // 내용 .setContentIntent(contentPendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH) .setAutoCancel(true) .setDefaults(NotificationCompat.DEFAULT_ALL) notificationManager?.notify(NOTIFICATION_ID, builder.build()) } companion object { private const val NOTIFICATION_ID = 0 private const val CHANNEL_ID = “channel_id” private const val CHANNEL_NAME = “ChannelName” } }

Set/Cancel Alarm

Cancel 할 경우와 Set 할 경우에 해당한다.

매일 일정 시각에 알람을 반복을 위해서는 alarmManager.setRepeating에서 AlarmManager.INTERVAL_DAY 를 설정한다.

private fun cancelAlarm() { val receiverIntent = Intent(getApplication(), AlarmReceiver::class.java) val pendingIntent = PendingIntent.getBroadcast(getApplication(), 0, receiverIntent, 0) alarmManager?.cancel(pendingIntent) } private fun setAlarm(hour: Int, minute: Int) { //옵션값에 따라서, 푸시 설정이 되지 않을 수 있도록 함 if (!pushAvailable.value) return //AlarmReceiver에 값 전달 val receiverIntent = Intent(getApplication(), AlarmReceiver::class.java) val pendingIntent = PendingIntent.getBroadcast(getApplication(), 0, receiverIntent, 0) //alarm 등록 전, 이전 push cancel alarmManager?.cancel(pendingIntent) // Set the alarm to start at time and minute val calendar: Calendar = Calendar.getInstance().apply { timeInMillis = System.currentTimeMillis() set(Calendar.HOUR_OF_DAY, hour) set(Calendar.MINUTE, minute) set(Calendar.SECOND, 0) } if (calendar.time < Date()) { //설정한 시간에 따라, 알람이 설정이 안될 수 있으므로 달 첫번째 부터의 시간을 설정 calendar.add(Calendar.DAY_OF_MONTH, 1) } alarmManager?.setRepeating( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent ) } 참고 링크 반응형

안드로이드(android) 특정한 시간에 푸시(푸쉬-notification)가 날라오도록 해보자!

이번 포스팅은 특정한 시간이 되면 푸쉬 알람이 올 수 있도록 구현하는 방법입니다.

먼저 프로젝트를 하나 생성해야한다.

Application name은 Alarmtest라 작성했지만, 사용자가 편한 앱 이름을 설정해주면 된다.

다음은 Manifest이다.

< manifest xmlns: android = "http://schemas.android.com/apk/res/android" package= "com.example.kwongyo.alarmtest" >

< uses-permission android :name= "android.permission.INTERNET" />

< uses-permission android :name= "android.permission.VIBRATE" />

< uses-permission android :name= "android.permission.WAKE_LOCK" />

< application android :allowBackup= "true" android :icon= "@mipmap/ic_launcher" android :label= "@string/app_name" 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" />

< activity android :name= ".Main2Activity" android :label= "@string/title_activity_main2" android :theme= "@style/AppTheme.NoActionBar" >

< receiver android :name= ".BroadcastD" >

은 안드로이드에서 서버가 있거나 테스트 할 경우 인터넷을 사용해야 한다. 인터넷 사용 환경에서 (인터넷을 사용하겠다는 권한을 주는것) 작성한다.

노티피케이션을 사용할 때 진동을 줄지 안 줄지 설정하는 것이다. 해당 폰에서는 permission을 줬기 때문에 노티피케이션(푸쉬)가 올 때 알람이 진동이 발생한다.

특정하게 알람을 줄 때 안줄때를 Client에서 결정하게 할 작정이라면, Java코드에서 notification.defaults=Notification.DEFAULT_ALL 혹은 Notification.DEFAULT_VIBRATE를 직접 주면 됩니다.

다음 권한은 안드로이드가 화면이 어두워져 있을 때 ( 잠금상태 일 때 ) 화면을 깨울때 주는 권한이다.

다음은 MainActivity입니다.

import android.app.AlarmManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

private static int ONE_MINUTE = 5626 ;

@Override

protected void onCreate(Bundle savedInstanceState) {

super .onCreate(savedInstanceState);

setContentView(R.layout. activity_main );

new AlarmHATT(getApplicationContext()).Alarm();

}

public class AlarmHATT {

private Context context ;

public AlarmHATT(Context context) {

this . context =context;

}

public void Alarm() {

AlarmManager am = (AlarmManager)getSystemService(Context. ALARM_SERVICE );

Intent intent = new Intent(MainActivity. this , BroadcastD. class );

PendingIntent sender = PendingIntent. getBroadcast (MainActivity. this , 0 , intent, 0 );

Calendar calendar = Calendar. getInstance ();

//알람시간 calendar에 set해주기

calendar.set(calendar.get(Calendar. YEAR ), calendar.get(Calendar. MONTH ), calendar.get(Calendar. DATE ), 23 , 12 , 0 );

//알람 예약

am.set(AlarmManager. RTC_WAKEUP , calendar.getTimeInMillis(), sender);

}

}

}

나중에 분리할 수 있는 코드로 작성하기 위해서 AlarmHATT와 MainActivity와 다른 클래스로 작성했습니다.( 실제로 개발한 HATT-스케쥴러 앱은 코드가 MVC패턴이 적용되어 분리되어 있습니다.)

AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE); AlarmManager는 device에 미래에 대한 알림같은 행위를 등록할 때 사용합니다. Intent intent = new Intent(MainActivity.this, BroadcastD.class); 알람이 발생했을 경우, BradcastD에게 방송을 해주기 위해서 명시적으로 알려줍니다.

PendingIntent sender = PendingIntent. getBroadcast (MainActivity. this , 0 , intent, 0 ); MainActivity.this => PendingIntent를 부르려는 컨텍스트 int requestCode =>Private request code 인데 현재는 사용하지 않아서 0으로 Intent intent => 앞으로 불려질 Intent int flags => Intent에 대한 조건설정 플래그 FLAG_ONE_SHOT : 한번만 사용하고 다음에 이 PendingIntent가 불려지면 fail 하겠다. FLAG_NO_CREATE : PendingIntent를 생성하지 않는다. PendingIntent가 실행중인것을 체크하기위함 FLAG_CANCEL_CURRENT : 이미 실행중인 PendingIntent가 있다면 이를 취소하고 새로 만듬 FLAG_UPDATE_CURRENT : 이미 실행중인 PendingIntent가 있다면 새로 만들지않고 extra data 만 교체하겠다.

calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 23, 12, 0); calendar에 시간을 set 해주는데요, year,month,date를 다 set 하고, 당장 test할 시간에 푸쉬를 받을 미래의 시간(약 1분정도)를 기재해 줍니다.

am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender); RTC_WAKEUP과 RTC가 있는데요. AlarmManager.RTC – 실제 시간을 기준으로 합니다. AlarmManager.RTC_WAKEUP – RTC와 동일하며, 대기 상태일 경우 단말기를 활성 상태로 전환한 후 작업을 수행합니다.

해당 코드는 RTC_WAKE을 줬습니다. 하지만 이 글을 읽으시는 분들은 이런 생각을 하겠지…(“왜 퍼미션 줬는데 저렇게 코딩했지?”) 답변->퍼미션을 줘서 RTC를 줘도 상관 없습니다.

BroadcastD.class

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

/**

* Created by GHKwon on 2016-02-17.

*/

public class BroadcastD extends BroadcastReceiver {

String INTENT_ACTION = Intent. ACTION_BOOT_COMPLETED ;

@Override

public void onReceive(Context context, Intent intent) { //알람 시간이 되었을때 onReceive를 호출함

//NotificationManager 안드로이드 상태바에 메세지를 던지기위한 서비스 불러오고

NotificationManager notificationmanager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE );

PendingIntent pendingIntent = PendingIntent. getActivity (context, 0 , new Intent(context, MainActivity. class ), PendingIntent. FLAG_UPDATE_CURRENT );

Notification.Builder builder = new Notification.Builder(context);

builder.setSmallIcon(R.drawable. on ).setTicker( “HETT” ).setWhen(System. currentTimeMillis ())

.setNumber( 1 ).setContentTitle( “푸쉬 제목” ).setContentText( “푸쉬내용” )

.setDefaults(Notification. DEFAULT_SOUND | Notification. DEFAULT_VIBRATE ).setContentIntent(pendingIntent).setAutoCancel( true );

notificationmanager.notify( 1 , builder.build());

}

}

해당 코드는 안드로이드 4.1버전 이상(젤리빈? 명칭이 헷갈리네요) 부터 사용이 가능합니다.

해당 코드는 이전에 작성한 포스팅을 참고하시면 될 것 같습니다.

http://kwongyo.tistory.com/4

감사합니다.

참고

http://westwoodforever.blogspot.kr/2013/06/android-javalangsecurityexception.html

http://www.androidside.com/bbs/board.php?bo_table=b49&wr_id=57389

[안드로이드]정해진 시간에 알람 울리는 방법 Notification TimePicker

반응형

2020.12.25 – [안드로이드] – [안드로이드]Notification 간단한 알림 띄우기

2020.12.28 – [안드로이드] – [안드로이드]Notification 알림창에 액션기능 추가하기

이번 시간에는 사용자가 정한 시간에 알람이 울리는 앱을 만들어 보려고 합니다.

1.TimePicker를 통해서 시계를 띄우고 알람 시간을 정한다.

2. AlarmManager를 통해 정해진 시간이 되면 알람으로 알려준다.

1. 메인화면(activity_main.xml)

화면구성은 사용자가 선택한 시간을 보여줄 TextView, 시계를 보여주는 TimePicker를 띄어줄 버튼,

알람을 취소할 버튼 이렇게 되어있습니다.

2. 알람기능 (NotificationHelper.java)

import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.content.ContextWrapper; import android.os.Build; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; public class NotificationHelper extends ContextWrapper { public static final String channeID = “channelID”; public static final String channeNm = “channelNm”; private NotificationManager notiManager; public NotificationHelper(Context base) { super(base); //안드로이드 버전이 오레오거나 이상이면 채널생성성 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ createChannels(); } } @RequiresApi(api = Build.VERSION_CODES.O) public void createChannels(){ NotificationChannel channel1 = new NotificationChannel(channeID, channeNm, NotificationManager.IMPORTANCE_DEFAULT); channel1.enableLights(true); channel1.enableVibration(true); channel1.setLightColor(R.color.design_default_color_on_primary); channel1.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); getManager().createNotificationChannel(channel1); } public NotificationManager getManager(){ if(notiManager == null){ notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } return notiManager; } public NotificationCompat.Builder getChannelNotification(){ return new NotificationCompat.Builder(getApplicationContext(), channeID) .setContentTitle(“알람”) .setContentText(“알람매니저 실행중”) .setSmallIcon(R.drawable.ic_launcher_background); } }

3. 시계 (TimePickerFragment.java)

import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.text.format.DateFormat; import androidx.fragment.app.DialogFragment; import java.util.Calendar; public class TimePickerFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, DateFormat.is24HourFormat(getActivity())); } }

4. 전달기능 (AlertReceiver.java)

import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import androidx.core.app.NotificationCompat; public class AlertReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NotificationHelper notificationHelper = new NotificationHelper(context); NotificationCompat.Builder nb = notificationHelper.getChannelNotification(); notificationHelper.getManager().notify(1, nb.build()); } }

5. BroadcastReceiver 정의해주기

AndroidManifest.xml

receiver 태그에 방금 만든 AlertReceiver 파일을 등록합니다.

6. 메인코드(MainActivity.java)

import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.DialogFragment; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.TimePicker; import java.text.DateFormat; import java.util.Calendar; public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener{ public static final String TAG = “MAIN”; private TextView time_text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); time_text = findViewById(R.id.time_text); Button time_btn = findViewById(R.id.time_btn); //시간 설정 time_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DialogFragment timePicker = new TimePickerFragment(); timePicker.show(getSupportFragmentManager(), “time picker”); } }); //알람 취소 Button alarm_cancel_btn = findViewById(R.id.alarm_cancel_btn); alarm_cancel_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cancelAlarm(); } }); } /** * 시간을 정하면 호출되는 메소드 * @param view 화면 * @param hourOfDay 시간 * @param minute 분 */ @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Log.d(TAG, “## onTimeSet ## “); Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, hourOfDay); c.set(Calendar.MINUTE, minute); c.set(Calendar.SECOND, 0); //화면에 시간지정 updateTimeText(c); //알람설정정 startAlarm(c); } /** * 화면에 사용자가 선택한 시간을 보여주는 메소드 * @param c 시간 */ private void updateTimeText(Calendar c){ Log.d(TAG, “## updateTimeText ## “); String timeText = “알람시간: “; timeText += DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime()); time_text.setText(timeText); } /** * 알람 시작 * @param c 시간 */ private void startAlarm(Calendar c){ Log.d(TAG, “## startAlarm ## “); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, AlertReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0); if(c.before(Calendar.getInstance())){ c.add(Calendar.DATE, 1); } //RTC_WAKE : 지정된 시간에 기기의 절전 모드를 해제하여 대기 중인 인텐트를 실행 alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent); } /** * 알람 취소 */ private void cancelAlarm(){ Log.d(TAG, “## cancelAlarm ## “); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, AlertReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0); alarmManager.cancel(pendingIntent); time_text.setText(“알람 취소”); } }

7. 실행화면

2021.01.23 – [안드로이드] – [안드로이드] 안드로이드 스튜디오 기본 색상 코드에서 가져오는 방법

2021.01.19 – [안드로이드] – [안드로이드] DrawerLayout Navigaion 쉽게 만들어보기

맘에 드셨다면 공감부탁드려요 문의 댓글 환영합니다.

반응형

[Android] 안드로이드 푸시 알림 (Notification)

1. Head Up Notification

Android O (API26)부터는 Notification을 하려면 Channel을 먼저 생성해주어야 한다.

Channel Id : 고유한 ID여야 하고 길면 잘릴 수 있다.

Importance : 헤드업 알림되어야 한다면 IMPORTANCE_HIGH로 설정하고, 아니면 IMPORTANCE_DEFAULT로 설정한다.

채널이 생성되었다면, 해당 채널로 Notification을 생성한다.

setPriority() : 헤드업 알림을 위해서는 PRIORITY_HIGH로 설정한다.

setSmallIcon() : 알림시 보여지는 아이콘. 반드시 필요

setContentTitle() : 제목 텍스트. (생략 가능)

setContentText() : 본문 텍스트. (생략 가능)

setDefaults() : 알림시 효과음, 진동 여부. (Android M(갤s6)에서는 이 값이 설정되어야 헤드업 알림된다.)

setStyle() : text는 한줄이 넘어가면 짤린다. 모든 텍스트를 보여주기 위해서는 BigText로 설정해야 한다.

setTimeoutAfter() : 지정한 시간 이후 알림이 취소된다. (화면에서 사라진다)

notify() : 생성한 notification을 등록한다. id가 같으면 1개의 notification만 보여지고 다르면 여러개가 보여진다.

2. Clickable Notification

우선 Intent를 생성하고, Notification 클릭시에 실행할 activity를 지정한다.

그리고 Notification에 PendingIntent를 지정하면 해당 Notification은 클릭이 가능해진다.

setContentIntent() : notification 클릭시 실행될 PendingIntent를 지정한다.

setAutoCancel() : true이면 알림 클릭시 화면에서 사라진다. 만약 PendingIntent가 지정되지 않았다면, 알림이 클릭되지 않으므로 setAutoCancel은 동작하지 않는다.

FLAG_UPDATE_CURRENT : PendingIntent가 이미 존재할 경우, Extra Data를 모두 대체

FLAG_CANCEL_CURRENT : PendingIntent가 이미 존재할 경우, 기존 PendingIntent를 cancel하고 다시 생성

[Android] AlarmManager 로 알림(Notification) 구현하기

AlarmManager 를 사용하면 어플리케이션이 사용중이지 않을 때에도,

시간 기반 작업을 생성할 수 있다.

하지만 효율성의 문제로 여러가지 권장사항이 존재한다.

1️⃣ 네트워크 작업보다 로컬 작업을 위해 AlarmManager를 사용해야함

-> 네트워크 작업은 동기화 어댑터와 함께 서버에서 직접 사용하는 것이 훨씬 더 유연하고, 만약 정확한 시간에 호출되어 동기화하는 알람이라면 그 앱의 모든 유저들을 동기화 하게 되어 서버의 과부하가 발생한다.

2️⃣ 불필요하게 기기의 절전모드를 해제하면 안됨

-> 시스템의 리소스가 빨리 소모되어 배터리 효율이 저하함.

3️⃣ 알람 트리거를 필요한 수준보다 정밀하게 설정하면 안됨

-> 정밀하게 설정하는 setRepeating() 대신 setInexactRepeating() 을 사용하면 여러 앱의 반복 알람을 동기화하고 동시에 실행하기 때문에 시스템이 절전모드를 해제해야하는 횟수가 줄어들어 배터리 효율이 좋아지기 때문.

4️⃣ Real time보다 Elapsed time 사용

-> Real time(실제시간)은 UTC 시간을 사용하기 때문에 사용자가 설정한 시간대, 언어의 영향을 받아 오동작할 가능성이 있기 때문에 가능하다면 Elapsed time(기기 부팅 후 경과시간)을 사용해야함

https://developer.android.com/training/scheduling/alarms?hl=ko

위 개발자 문서에서 더 자세한 내용을 확인할 수 있다.

사용해보기

1️⃣ 일회성 알람

BroadcastReceiver 추가

New -> Other -> BroadcastReceiver 를 클릭하여 추가해준다.

class MyReceiver : BroadcastReceiver() { lateinit var notificationManager: NotificationManager override fun onReceive(context: Context, intent: Intent) { notificationManager = context.getSystemService( Context.NOTIFICATION_SERVICE) as NotificationManager createNotificationChannel() deliverNotification(context) }

클래스에서 lateinit으로 notificationManager를 선언해주고

Broadcast가 수신되면 자동으로 호출되는 메서드인 onReceive 에서 초기화해준다.

또한 Notification 을 띄우기 위한 Channel 등록을 위한 createNotificationChannel 메소드와

Notification 등록을 위한 deliverNotification 메소드를 구현해준다.

상수 클래스

class Constant { companion object { // 아이디 선언 const val NOTIFICATION_ID = 0 const val CHANNEL_ID = “notification_channel” // 알림 시간 설정 const val ALARM_TIMER = 5 } }

다른 클래스에서 사용할 상수들을

따로 정리하여 저장해놓았다.

createNotificationChannel

오레오 버전 이상에서는

노티피케이션을 띄우기 위하여 의무적으로 채널을 등록해야 한다.

// Notification 을 띄우기 위한 Channel 등록 fun createNotificationChannel(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel( CHANNEL_ID, // 채널의 아이디 “채널 이름입니다.”, // 채널의 이름 NotificationManager.IMPORTANCE_HIGH /* 1. IMPORTANCE_HIGH = 알림음이 울리고 헤드업 알림으로 표시 2. IMPORTANCE_DEFAULT = 알림음 울림 3. IMPORTANCE_LOW = 알림음 없음 4. IMPORTANCE_MIN = 알림음 없고 상태줄 표시 X */ ) notificationChannel.enableLights(true) // 불빛 notificationChannel.lightColor = Color.RED // 색상 notificationChannel.enableVibration(true) // 진동 여부 notificationChannel.description = “채널의 상세정보입니다.” // 채널 정보 notificationManager.createNotificationChannel( notificationChannel) } }

채널을 등록해주고

deliverNotification

// Notification 등록 private fun deliverNotification(context: Context){ val contentIntent = Intent(context, MainActivity::class.java) val contentPendingIntent = PendingIntent.getActivity( context, NOTIFICATION_ID, // requestCode contentIntent, // 알림 클릭 시 이동할 인텐트 PendingIntent.FLAG_UPDATE_CURRENT /* 1. FLAG_UPDATE_CURRENT : 현재 PendingIntent를 유지하고, 대신 인텐트의 extra data는 새로 전달된 Intent로 교체 2. FLAG_CANCEL_CURRENT : 현재 인텐트가 이미 등록되어있다면 삭제, 다시 등록 3. FLAG_NO_CREATE : 이미 등록된 인텐트가 있다면, null 4. FLAG_ONE_SHOT : 한번 사용되면, 그 다음에 다시 사용하지 않음 */ ) val builder = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_alarm) // 아이콘 .setContentTitle(“타이틀 입니다.”) // 제목 .setContentText(“내용 입니다.”) // 내용 .setContentIntent(contentPendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH) .setAutoCancel(true) .setDefaults(NotificationCompat.DEFAULT_ALL) notificationManager.notify(NOTIFICATION_ID, builder.build()) }

노티피케이션을 등록해준다.

메인액티비티

class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 뷰바인딩 binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager val intent = Intent(this,MyReceiver::class.java) val pendingIntent = PendingIntent.getBroadcast( this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT ) // 토글버튼 활성화 시 알림을 생성하고 토스트 메세지로 출력 binding.toggleButton.setOnCheckedChangeListener { _, check -> val toastMessage = if (check) { val triggerTime = (SystemClock.elapsedRealtime() // 기기가 부팅된 후 경과한 시간 사용 + ALARM_TIMER * 1000) // ms 이기 때문에 초단위로 변환 (*1000) alarmManager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pendingIntent ) // set : 일회성 알림 “$ALARM_TIMER 초 후에 알림이 발생합니다.” } else { alarmManager.cancel(pendingIntent) “알림 예약을 취소하였습니다.” } /* 1. ELAPSED_REALTIME : ELAPSED_REALTIME 사용. 절전모드에 있을 때는 알람을 발생시키지 않고 해제되면 발생시킴. 2. ELAPSED_REALTIME_WAKEUP : ELAPSED_REALTIME 사용. 절전모드일 때도 알람을 발생시킴. 3. RTC : Real Time Clock 사용. 절전모드일 때는 알람을 발생시키지 않음. 4. RTC_WAKEUP : Real Time Clock 사용. 절전모드 일 때도 알람을 발생시킴. */ Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show() } } }

토글버튼 활성화 시

정한 시간 뒤에 알림이 발생한다는 토스트가 뜨고,

알림이 발생한다.

노티피케이션의 속성으로 들어가면 세부내용을 볼 수 있다.

정확한 시간에 알람 발생 시키기

// 토글버튼 활성화 시 알림을 생성하고 토스트 메세지로 출력 binding.toggleButton.setOnCheckedChangeListener { _, check -> val toastMessage = if (check) { val triggerTime = (SystemClock.elapsedRealtime() // 기기가 부팅된 후 경과한 시간 사용 + ALARM_TIMER * 1000) // ms 이기 때문에 초단위로 변환 (*1000) alarmManager.setExact( AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pendingIntent ) // set : 일회성 알림 “$ALARM_TIMER 초 후에 알림이 발생합니다.” } else { alarmManager.cancel(pendingIntent) “알림 예약을 취소하였습니다.” }

set을 사용하면, 비교적 정확하지 않은 시간에 알람이 발생한다.

alarmManager에서

set이 아닌 setExact를 사용하면 정확한 시간에 알람이 발생한다.

절전모드 일 때 동작

setAndAllowWhileIdle : set()과 동일 하지만 절전모드에서도 동작

: 하지만 절전모드에서도 동작 setExactAndAllowWhileIdle : setExact()과 동일하지만 절전모드에서도 동작

2️⃣ 반복 알람

binding.toggleButton2.setOnCheckedChangeListener { _, check -> val toastMessage = if (check) { val repeatInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES /* 1. INTERVAL_FIFTEEN_MINUTES : 15분 2. INTERVAL_HALF_HOUR : 30분 3. INTERVAL_HOUR : 1시간 4. INTERVAL_HALF_DAY : 12시간 5. INTERVAL_DAY : 1일 */ val triggerTime = (SystemClock.elapsedRealtime() + repeatInterval) alarmManager.setInexactRepeating( AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, repeatInterval, pendingIntent ) // setInexactRepeating : 반복 알림 “${repeatInterval/60000}분 마다 알림이 발생합니다.” } else { alarmManager.cancel(pendingIntent) “알림 예약을 취소하였습니다.” } Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show() }

setInexactRepeating 를 사용하여

반복되는 알람을 설정할 수 있다.

하지만 반복주기는 정해진 5가지의 주기로밖에 설정할 수 없다.

원하는 시간주기에 알람 발생 시키기

binding.toggleButton2.setOnCheckedChangeListener { _, check -> val toastMessage = if (check) { val repeatInterval : Long = ALARM_TIMER * 1000L val triggerTime = (SystemClock.elapsedRealtime() + repeatInterval) alarmManager.setRepeating( AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, repeatInterval, pendingIntent ) “${repeatInterval/1000}초 마다 알림이 발생합니다.” } else { alarmManager.cancel(pendingIntent) “알림 예약을 취소하였습니다.” } Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show() }

setRepeating 를 사용하면

주기도 맘대로 정할 수 있다.

3️⃣ Real Time 사용하기, 부팅

// realtime binding.toggleButton3.setOnCheckedChangeListener { _, check -> val toastMessage = if (check) { val repeatInterval : Long = ALARM_TIMER * 1000L val calendar = Calendar.getInstance().apply { timeInMillis = System.currentTimeMillis() set(Calendar.HOUR_OF_DAY,5) set(Calendar.MINUTE,30) } alarmManager.setRepeating( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, repeatInterval, pendingIntent) “알림이 발생합니다.” } else { alarmManager.cancel(pendingIntent) “알림 예약을 취소하였습니다.” } Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show() }

원하는 날짜에도 알림을 발생시킬 수 있습니다.

기기가 다시 시작되면 알람 시작

class BootReceiver : BroadcastReceiver() { companion object { const val TAG = “BootReceiver” } override fun onReceive(context: Context, intent: Intent) { Log.d(TAG, “Received intent : $intent”) if (intent.action == “android.intent.action.BOOT_COMPLETED”) { // Register alarm } } }

부트리시버를 만들어

부팅시 알림을 다시 호출해줍니다.

https://github.com/HanYeop/AndroidStudio-Practice2/tree/master/AlarmEx

참고

https://codechacha.com/ko/android-alarmmanager/

https://developer.android.com/training/scheduling/alarms?hl=ko

반응형

일정관리 앱에 푸시알림 추가하기

일정관리 앱을 만들던 중 일정에 해당하는 날짜의 특정 시간에 푸시알림 기능을 추가하기 위해 AlarmManager,Receiver, Service를 사용하게 되었다.

1. 설정

1. 첫 번째 퍼미션은 인터넷 사용권한. 2. 두 번째 퍼미션은 진동을 위한 권한. 3. 세 번째 퍼미션은 잠들어있는(?) 휴대폰을 깨우기 위한 권한 4. 네 번째 퍼미션은 핸드폰을 껏다가 킨 후에도 알림이 적용될 수 있도록하는 권한

사용할 Receiver와 Service를 등록해준다.

2. 핵심 코드

calendar파라미터는 해당 일정의 날짜와 알림을 울릴 시간정보를 받아오고 AlarmManager에 시간정보와 호출할 receiver를 가진 PendingIntent를 등록한다. AlarmManager에 등록된 시간이 되면 onReceive()가 실행되어 Service를 호출 onStartCommand에서 바로 실행하는 것이 아닌 알람기능을 수행하는 코드를 다른 스레드로 구성했다.

코드 실행결과 정해진 시간에 푸시알림이 도착하는 것을 확인했다. 하지만 기기가 Doze모드에 있을 때도 알림이 도착하는지는 좀 더 테스트해봐야 알 것 같다. 알림이 도착하는 것을 확인하기 위해 시간을 정해놓고 기다리기를 반복하다보니

개발 시간이 너무 많이 늘어나는 것 같다…

[Android] FCM 푸시 알림(Notification)

728×90

앞으로 개발하게 될 프로젝트에서 반복적이지만 간단한 푸시 알림 서비스를 사용하게 될 것 같아

개발 전 미리 FCM을 이용한 푸시 알림에 대해 공부하려고 포스팅을 작성하게 되었다.

FCM

Firebase 클라우드 메시징(FCM)은 무료로 메시지를 안정적으로 전송할 수 있는 교차 플랫폼 메시징 솔루션입니다.

알림 메시지 / 데이터 메시지 전송

다양한 메시지 타겟팅 : 단일 기기, 기기 그룹, 주제를 구독한 기기 등 3가지 방식으로 앱에 메시지를 배포할 수 있음

클라이언트 앱에서 메시지 전송 : FCM의 신뢰성 높고 배터리 효율적인 연결 채널을 사용하여 메시지를 보낼 수 있음

FCM vs. AlarmManager vs. WorkManager

FCM : 네트워크 기반의 푸시 알람 서비스

👍 네트워크만 연결되어 있다면 원하는 기능을 서버에서 구현한 뒤, 배포하면 되므로 많이 이용하고 있음

☝️ 오프라인 환경에서도 사용자에게 알람을 보내고 싶다면?…

AlarmManager : 시스템 알람 서비스

👍 앱 외부에서 작동하기 때문에 앱이 실행 중이 아닐 때도 이벤트를 트리거할 수 있음

☝️ Doze 모드에서는 알람이 울리지 않는다…

WorkManager : 백그라운드 작업 라이브러리

👍 Doze 모드, 배터리 세이버 등의 제안 사항 속에서 안전하게 백그라운드 작업을 할 수 있음

☝️ …없다?

FCM이 메세지를 보내는 과정

FCM 서버에 Token 요청 & 획득 앱 서버에 Token 저장 (서버가 FCM 서버에 메시지 전송을 요청할 때 어디로 보낼지 구분하는 용도) Token을 활용하여 메세지 전송 요청 (앱 서버 ———– Token & 메세지 데이터 ———–> FCM 서버) 메세지 전송 (FCM 서버는 요청받은 메세지를 Token에 해당하는 디바이스에 전송) 메세지 수신

기존 Firebase의 프로젝트 설정과 동일하므로 앞의 과정은 생략한다.

build.gradle

dependencies { … implementation ‘com.google.firebase:firebase-messaging-ktx’ }

AndroidManifest.xml

네트워크 기반의 서비스이기 때문에 인터넷 퍼미션 을 추가함

아래의 구현한 서비스를 등록하기 위해

메세지를 수신하기 위해

MessagingService.kt

class MessagingService : FirebaseMessagingService() { // 수신한 메세지 처리 override fun onMessageReceived(remoteMsg: RemoteMessage) { super.onMessageReceived(remoteMsg) if (remoteMsg.notification != null) showNotification(remoteMsg.notification?.title, remoteMsg.notification!!.body!!) } // Token 처리 override fun onNewToken(token: String) { super.onNewToken(token) } private fun showNotification(title: String?, body: String) { … } }

onNewToken() : FCM 서버에 등록되었을 때 호출됨

onMessageReceived() : FCM 서버에 메세지를 전송하면 자동으로 호출되며, 메서드 내의 메세지를 처리할 수 있음

테스트는 Firebase Console에서 할 수 있음

알림 제목, 알림 텍스트는 onMessageReceived의 파라미터인 RemoteMessage 에 전달되어 get으로 사용할 수 있음

‘다음’ 버튼을 눌러 현재 앱을 선택하고 ‘검토’ 버튼을 눌러 바로 메세지를 보낼 수 있음

테스트 푸시 알람

Notification

이 포스팅에서는 기본 알림만 다룬다.

공식 문서 : 기본 알림 이미지

알림 콘텐츠

NotificationCompat.Builder 객체를 사용하여 알림 콘텐츠와 채널을 설정함

setSmallIcon() : 아이콘

setContentTitle() : 알림 제목 텍스트

setContentText() : 알림 본문 텍스트

setPriority() : 알림의 우선순위 (Android 8.0 이상에서는 채널 중요도 를 대신 설정해야 함)

setStyle() : 알림을 더 길게 설정하려면 스타일 템플릿을 추가하여 확장 가능한 알림으로 설정

이때 생성자에서 채널 ID를 제공해야 함 (Android 8.0 이상에서는 호환성을 유지하기 위해 필요함)

var builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(textTitle) .setContentText(textContent) .setPriority(NotificationCompat.PRIORITY_DEFAULT)

채널 만들기

Android 8.0 이상(SDK_INT >= VERSION_CODES.O)에서 알림을 제공하기 위한 방법

→ NotificationChannel 인스턴스를 createNotificationChannel()에 전달하여 앱의 알림 채널을 시스템에 등록

채널 ID

채널 이름

채널 중요도 : NotificationManager에서 상수 지원

private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = getString(R.string.channel_name) val descriptionText = getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, name, importance).apply { description = descriptionText } // Register the channel with the system val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } }

알림 탭 설정

모든 알림은 앱에서 알림에 관련된 Activity를 열려면 탭에 응답해야 함

→ PendingIntent 객체로 정의된 콘텐츠 인텐트를 지정하여 setContentIntent()에 전달해야 함

어떤 화면으로 이동할 것인지 Intent 생성 PendingIntent를 위에서 생성한 Intent 인스턴스를 매개변수로 하여 생성 NotificationCompat.Builder에 setContentIntent(pendingIntent)로 PendingIntent 추가

val intent = Intent(this, AlertDetails::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0) val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(“My notification”) .setContentText(“Hello World!”) .setPriority(NotificationCompat.PRIORITY_DEFAULT) // Set the intent that will fire when the user taps the notification .setContentIntent(pendingIntent) .setAutoCancel(true)

*Intent 생성 시, flag를 설정하면 사용자가 알림을 통해 앱을 연 뒤에 예상되는 탐색 환경 유지에 도움이 됨

알림의 응답에만 존재하는 Activity → 앱의 기존 작업 및 백 스택에 추가되는 대신 새 작업을 시작

앱의 일반 앱 흐름에 존재하는 Activity → 백 스택이 생성되어 뒤로 및 위로 버튼에 대한 사용자의 기대가 유지

*setAutoCancel()은 사용자가 알림을 탭하면 자동으로 알림을 삭제함 (NotificationCompat.Builder에 추가)

알림 표시

NotificationManagerCompat.notify()를 호출하여 아래 2개의 값을 전달

알림의 고유 ID

NotificationCompat.Builder.build()의 결과

with(NotificationManagerCompat.from(this)) { notify(notificationId, builder.build()) }

MessagingService.kt

private fun showNotification(title: String?, body: String) { val intent = Intent(this, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT) val channelId = “book_channel” val notificationBuilder = NotificationCompat.Builder(this, channelId) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setContentIntent(pendingIntent) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(channelId, “book channel”, NotificationManager.IMPORTANCE_DEFAULT) notificationManager.createNotificationChannel(channel) } notificationManager.notify(0, notificationBuilder.build()) }

아직 프로젝트 개발 설계가 이루어지지는 않았지만, 고민을 해보니 개발할 서비스에서 굳이 FCM을 사용할 필요가 없다고 느껴졌다.

개인한테 사용을 독려하기 위한 알람이기 때문에 오히려 WorkManager을 이용해서 주기적으로 알람을 보내는게 더 낫지 않을까? 🤔

reference >

728×90

키워드에 대한 정보 안드로이드 특정 시간 푸시 알림

다음은 Bing에서 안드로이드 특정 시간 푸시 알림 주제에 대한 검색 결과입니다. 필요한 경우 더 읽을 수 있습니다.

이 기사는 인터넷의 다양한 출처에서 편집되었습니다. 이 기사가 유용했기를 바랍니다. 이 기사가 유용하다고 생각되면 공유하십시오. 매우 감사합니다!

사람들이 주제에 대해 자주 검색하는 키워드 설정푸시알림

  • 동영상
  • 공유
  • 카메라폰
  • 동영상폰
  • 무료
  • 올리기

설정푸시알림


YouTube에서 안드로이드 특정 시간 푸시 알림 주제의 다른 동영상 보기

주제에 대한 기사를 시청해 주셔서 감사합니다 설정푸시알림 | 안드로이드 특정 시간 푸시 알림, 이 기사가 유용하다고 생각되면 공유하십시오, 매우 감사합니다.

Leave a Comment