tgyuuAn / BaekyoungE

자연어 처리 기반 진로 상담 chat bot 어플리케이션
5 stars 0 forks source link

[FEATURE]: FCM으로 백그라운드에서 알림을 받을 수 있도록 연결, Firebase Cloud Functions 로직 작성 #55

Closed tgyuuAn closed 1 day ago

tgyuuAn commented 1 week ago

작업 사항

새로운 메시지가 도착했을경우 noti를 주는 기능

image

Todo

기타사항

Firebase Cloud Message 알림 공식 문서 레퍼런스

Firebase Cloud Functions - FCM 레퍼런스 1 Firebase Cloud Functions - FCM 레퍼런스 2

tgyuuAn commented 1 week ago

알림 권한 설정 화면으로 이동하는 로직

startActivity(
    Intent(ACTION_APP_NOTIFICATION_SETTINGS)
        .putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)

나는 오래오 이상의 버전만 minSDK로 설정해서 상관없지만,

더 이전의 버전을 호환하고 싶으면

fun presentNotificationSetting(context: Context) {
    val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        notificationSettingOreo(context)
    } else {
        notificationSettingOreoLess(context)
    }
    try {
        context.startActivity(intent)
    }catch (e: ActivityNotFoundException) {
        e.printStackTrace()
    }
}

@RequiresApi(Build.VERSION_CODES.O)
fun notificationSettingOreo(context: Context): Intent {
    return Intent().also { intent ->
        intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
        intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    }
}

fun notificationSettingOreoLess(context: Context): Intent {
    return Intent().also { intent ->
        intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
        intent.putExtra("app_package", context.packageName)
        intent.putExtra("app_uid", context.applicationInfo?.uid)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    }
}

처럼 분기를 나눠주어야 함.

레퍼런스




추가적으로, 안드로이드 13(티라미수) 이상 부터는 알림에 대한 권한을 얻어와야 함!

    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission(),
    ) { isGranted: Boolean ->
        if (!isGranted) {
            showPermissionDeniedSnackbar = true
        }
    }

    private fun askNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) !=
                PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }
tgyuuAn commented 1 week ago

스낵바에 Action 버튼 만들고, Action 설정하기

if (showPermissionDeniedSnackbar) {
    coroutineScope.launch {
        val result = snackbarHostState.showSnackbar(
            message = "더 나은 서비스를 위해 알림 권한을 설정해 주세요.",
            actionLabel = "설정",
            duration = SnackbarDuration.Short,
        )

        if (result == SnackbarResult.ActionPerformed) {
            startActivity(
                Intent(ACTION_APP_NOTIFICATION_SETTINGS)
                    .putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
            )
        }
    }
}

스낵바 만들 때, actionLabel설정하면 버튼이 생김.

이 때 클릭할 때 액션은 해당 showSnackBar 함수를 실행했을 때의 결과를 아래 if문 혹은 when에서 분기로 나눠주면 된다.

레퍼런스

tgyuuAn commented 6 days ago

아니 Notification Icon이 자꾸 작게 나오는데요?

image

레퍼런스

...

안드로이드 5.0(롤리팝) 부터 공식적으로 유채색 알림 아이콘을 지원하지 않습니다.

일부 기종에 따라 유채색을 지원하는 경우도 있으나, 최신 기기일수록 지원하는 경우가 드뭅니다.

따라서 앱 알림 아이콘을 사용하고자 하실 땐 배경이 투명이며 흰색으로 된 아이콘을 올려 주셔야 합니다.

투명 배경에 흰색 아이콘을 사용하고, 백그라운드 색상을 지정해주어야한다..

tgyuuAn commented 1 day ago

Firebase Cloud Functions 은 Node.js 코드인데 어떻게 짜셨어요 ?

-> Chat GPT 4.0 과 함께했습니다.

image




ES Lint에서 계속 걸리는데요?

package.json 파일 에서,

Easy fix. Inside your package.json change

"lint": "eslint .""lint": "eslint", 로 바꿔서 해결해주면 끝.

레퍼런스




image

성공!!!!!!