on
[패스트캠퍼스 챌린지 20일차] Android alarm앱 마무리
[패스트캠퍼스 챌린지 20일차] Android alarm앱 마무리
class AlarmReceiver:BroadcastReceiver() { companion object{ const val NOTIFICATION_ID = 100 const val NOTIFICATION_CHANNEL_ID = "1000" } override fun onReceive(context: Context, intent: Intent?) { createNotificationChannel(context) notifyNotification(context) } private fun createNotificationChannel(context: Context) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ val notificationChannel = NotificationChannel( NOTIFICATION_CHANNEL_ID, "기상 알람", NotificationManager.IMPORTANCE_HIGH ) NotificationManagerCompat.from(context).createNotificationChannel(notificationChannel) } } private fun notifyNotification(context: Context){ with(NotificationManagerCompat.from(context)){ val build = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID) .setContentTitle("알람") .setContentText("일어날 시간입니다.") .setSmallIcon(R.drawable.ic_alarm) .setPriority(NotificationCompat.PRIORITY_HIGH) notify(NOTIFICATION_ID, build.build()) } } }
전달받은 알람이 휴대폰에 보여지기 위해서 notification channel을 생성하고 notify 해주는 기능을 담은 AlarmReceiver 클래스를 작성하였습니다.
private fun fetchDataFromSharedPreferences(): AlarmDisplayModel { val sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) val timeDBValue = sharedPreferences.getString(ALARM_KEY, "9:30") ?: "9:30" val onOffDBValue = sharedPreferences.getBoolean(ON_OFF_KEY, false) val alarmData = timeDBValue.split(":") val alarmModel = AlarmDisplayModel( hour = alarmData[0].toInt(), minute = alarmData[1].toInt(), onOff = onOffDBValue ) val pendingIntent = PendingIntent.getBroadcast(this, ALARM_REQUEST_CODE, Intent(this, AlarmReceiver::class.java), PendingIntent.FLAG_NO_CREATE) if((pendingIntent == null) and alarmModel.onOff){ //알람은 꺼져있는데 데이터가 켜져있는 경우 alarmModel.onOff = false }else if((pendingIntent != null) and alarmModel.onOff.not()){ //알람은 켜져있는데 데이터가 꺼져있는경우 //알람을 취소함 pendingIntent.cancel() } return alarmModel }
패스트캠퍼스 바로가기 -> https://bit.ly/3FVdhDa
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
from http://doooongdong.tistory.com/30 by ccl(A) rewrite - 2021-11-20 18:28:15