마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

코틀린으로 노피티케이션 써서 파이어베이스로 값 옮기기

0 추천

코틀린을 공부중인 학생입니다

노피티케이션으로 팝업창이 뜰때 체크박스의 값이 파이어베이스로 넘어가게 설계하고 싶은데

잘 안됩니다... 아래가 코드의 일부입니다

어떻게 수정을 해야 제가 원하는대로 코드를 짤 수 있을까요?

 

private fun notifyNotification(context: Context) {

    with(NotificationManagerCompat.from(context)) {

       val build = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
            .setContentTitle("알람")
            .setContentText("일어날 시간입니다.")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setPriority(NotificationCompat.PRIORITY_HIGH)

            val firebaseDatabase = FirebaseDatabase.getInstance()
            val databaseReference = firebaseDatabase.reference

           CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
               if (isChecked) {
                    when (buttonView.id) {
                        R.id.checkBox -> {
                            databaseReference.child("check").push().setValue("c")
                        }
                        R.id.checkBox2 -> {
                            databaseReference.child("check").push().setValue("d")
                        }
                        R.id.checkBox3 -> {
                            databaseReference.child("check").push().setValue("e")
                        }
                    }
                } else {
                    when (buttonView.id) {
                        R.id.checkBox -> {
                            databaseReference.child("check").push().setValue("")
                        }
                        R.id.checkBox2 -> {
                            databaseReference.child("check").push().setValue("")
                        }
                        R.id.checkBox3 -> {
                            databaseReference.child("check").push().setValue("")
                        }
                }
            }

            notify(NOTIFICATION_ID, build.build())


        }
 }
}

우선 앱 자체는 알람을 울려주는 앱이고 알람이 울리긴하나 값이 넘어가진 않습니다...

 

요거는 혹시 몰라서 첨부하는 알람리시버 쪽 코딩 전문입니다...


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_launcher_foreground)
            .setPriority(NotificationCompat.PRIORITY_HIGH)

            val firebaseDatabase = FirebaseDatabase.getInstance()
            val databaseReference = firebaseDatabase.reference

           CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
               if (isChecked) {
                    when (buttonView.id) {
                        R.id.checkBox -> {
                            databaseReference.child("check").push().setValue("c")
                        }
                        R.id.checkBox2 -> {
                            databaseReference.child("check").push().setValue("d")
                        }
                        R.id.checkBox3 -> {
                            databaseReference.child("check").push().setValue("e")
                        }
                    }
                } else {
                    when (buttonView.id) {
                        R.id.checkBox -> {
                            databaseReference.child("check").push().setValue("")
                        }
                        R.id.checkBox2 -> {
                            databaseReference.child("check").push().setValue("")
                        }
                        R.id.checkBox3 -> {
                            databaseReference.child("check").push().setValue("")
                        }
                }
            }

            notify(NOTIFICATION_ID, build.build())


        }
 }
}

 

임재재 (120 포인트) 님이 2021년 9월 13일 질문
안되는 부분이 Notification 만드는 부분인가요, Notification click하는 부분인가요, 아니면 Firebase를 갱신하는 부분인가요?  

private fun notifyNotification(context: Context)  에서 CompoundButton을 어떻게 접근하는지 궁금하네요. 저렇게 접근이 가능한가요?
노피티케이션 파트는 괜찮습니다 val firebaseDatabase = FirebaseDatabase.getInstance()

이 밑줄부터 작동을 하지 않는 것 같습니다 아마 파이어베이스를 갱신하는 부분이 안되는 것 같아요.

 

제가 원하는 것은

1. 알람 시간에 맞춰서 값이 파이어베이스로 넘어간다 (실시간 데이터)

2. 알람 시간이 되면 팝업이 작동해 클릭하면 파이어베이스로 값이 넘어간다. (실시간데이터)

 

이 둘중 하나인데 이를 해결하기 위해선 어떻게 해야할까요 ㅠㅠ? 다른 쪽 코드가 필요할까요?

주변에 프로그래밍을 하는 분이 없어 독학으로 하려니 관련된 자료가 전무해서 주먹구구식으로 여기까지 오긴햇지만 여기부터 막혀서 일주일째 진전이 없습니다..
private fun notifyNotification(context: Context)  에서 CompoundButton을 어떻게 접근하는지 궁금하네요. AlaramReceiver안에서 저렇게 접근이 가능한가요?

notifyNotification를 디버깅 해보세요.   CompoundButton 에 클릭이벤트를 사용하지 마시고 firebase 호출하는 코드를 직접 호출해 보세요. 된다면, CompoundButton의 클릭이벤트가 문제인 거겠죠.
접근이 불가능한 영역인가요? 수정하면서 경고 문구가 뜨지 않아서 몰랐습니다 ㅠㅠ... 나름 찾아보고 끼워 맞추어 보았는데 CompoundButton 접근이 문제였을까요?
체크박스에 있는 값을 넘겨주어야 해서 CompoundButton를 쓰는게 올바르다고 판단했었습니다
제 질문은 Reciever안에서 CompoundButton에 어떻게 접근하고 있는지에 대한 겁니다. CompoundButton을 어디에서 초기화 하나요?
CompoundButton 자체를 처음 써봐서 초기화 해주어야 하는지 몰랐습니다 다시 생각해 보겠습니다...!
제가 질문을 드린 이유는 CompoundButton 클릭이벤트가 제대로 호출이 되는지 확인해보기 위한 겁니다. 버튼 클릭이벤트가 정상적으로 호출된다면 Firebase에 데이터를 저장하는 코드가 문제일테니까요. 문제의 범위를 좁히면 해결책을 찾기도 더 쉬워질 겁니다.
감사합니다 어찌저찌 대충 해결 했습니다 ㅠㅠ 덕분에 해결책의 실마리를 찾을 수 있었습니다!

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...