[Android/Kotlin] 안드로이드 스튜디오 알림 안뜸 해결

2023. 11. 5. 22:52·App&Web/Android

결론

문제는 알림 권한 설정을 추가하지 않았기 때문이다.

1. 아래의 코드를 AndroidManifest.xml에 추가하도록 하자.

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

2. 그 다음 설정>앱>작업 중인 앱으로 가서 알림을 키면 된다.

 

계기

 

동아리 과제 중 Foreground를 사용해 보는 것이 있었다.

 

 

기본 코드

 

AndroudManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">
        <service
            android:name=".Foreground"
            android:enabled="true"
            android:exported="true"></service>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

 

Foreground.kt

package com.example.myapplication

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlin.concurrent.thread

class Foreground : Service() {

    val CHANNEL_ID = "FGS153"
    val NOTI_ID = 153

    fun createNotificationChannel(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val serviceChannel = NotificationChannel(CHANNEL_ID, "FOREGROUND", NotificationManager.IMPORTANCE_HIGH)
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(serviceChannel)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("Foreground Service", "Service started") // 이 부분을 추가합니다.
        createNotificationChannel()
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service")
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .build()

        startForeground(NOTI_ID, notification)

        return super.onStartCommand(intent, flags, startId)
    }

    fun runBackground(){
        thread(start=true){
            for(i in 0..100){
                Thread.sleep(1000)
                Log.d("서비스", "COUNT===?$i")
            }
        }
    }

    override fun onBind(intent: Intent): IBinder {
        return Binder()
    }
}

 

 

ManActivity.kt

package com.example.myapplication

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun serviceStart(view: View){
        val intent = Intent(this, Foreground::class.java)
        ContextCompat.startForegroundService(this, intent)
    }

    fun serviceStop(view: View){
        val intent = Intent(this, Foreground::class.java)
        stopService(intent)
    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="serviceStop"
        android:text="서비스 종료"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/button" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="serviceStart"
        android:text="서비스 시작"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button2"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

문제 및 해결

위 코드처럼 작성하고 실행하니 아래와 같은 에러가 떳다.

 

??? 버전은 높이라고??? 그럼 버전을 높이자!

compileSdk 34

gradle에서 33을 34로 바꾸고 다시 실행해봤다.

 

다행히도 이번엔 실행이 되었다. 기억하기로 내가 작성한 코드가 오레오 이상부터 가능하다고 했었는데 이 부분을 까먹고 그냥 33버전으로 설정해서 오류가 났던 것 같다. 

 

그리고 신나게 서비스 시작(알림 띄우는 버튼)을 눌렀더니...

아무런 변화가 없다...

 

어쩔 수 없다.

GPT에게 질문을 했다.

위의 코드들을 전부 보내며 왜 안뜨는지 알려달라고 했는데

로그를 찍어보라고 했다.

그래서 로그를 넣어보았다.

잘 찍힌다..

 

그래서 GPT가 한 조언을 더 찾아보니

 

앱 설정 권한을 확인하라고 해서 혹시나 싶어서 확인했더니 

???????????????????????????????????????????????

???????????????????????????????????????????????

???????????????????????????????????????????????

???????????????????????????????????????????????

???????????????????????????????????????????????

???????????????????????????????????????????????

알림 키려고 해도 저 버튼 자체가 클릭이 안되었다.

 

이후 앱 알림 권한 관련 구글링을 해보니

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

이 코드를 추가해야 했다.

 

위 코드를 추가하고 다시 설정을 보니

 

클릭이 된다!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 

이러고 다시 알림 뜨게 하는 버튼을 클릭하니

잘 뜬다!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 

 

 

*이렇게 혼자 북치고 장구쳤는데 다음날 모바일 수업에서 알림 기능을 배웠다...... 허무

'App&Web > Android' 카테고리의 다른 글

[Android/Kotlin] 주간 달력 만들기  (0) 2024.02.21
[Android/Kotlin] fragment에서 fragment로 이동  (0) 2024.02.21
[Android/Kotlin] 안드로이드 spinner(스피너) 배경색 적용  (0) 2024.02.21
[Android/Kotlin] 뷰바인딩  (0) 2023.09.27
[Android/Kotlin] SQLite  (0) 2023.09.25
'App&Web/Android' 카테고리의 다른 글
  • [Android/Kotlin] fragment에서 fragment로 이동
  • [Android/Kotlin] 안드로이드 spinner(스피너) 배경색 적용
  • [Android/Kotlin] 뷰바인딩
  • [Android/Kotlin] SQLite
2월2
2월2
  • 2월2
    서벅돌의 성장일기
    2월2
  • 전체
    오늘
    어제
    • 분류 전체보기 (120)
      • TIL (2)
      • Server (28)
        • spring (7)
        • node.js (16)
        • 기타 (5)
      • App&Web (17)
        • Web (1)
        • Android (16)
        • iOS (0)
      • 공부 (59)
        • 깃&깃허브 (3)
        • 파이썬 (17)
        • 유니티 (4)
        • 자료구조 | 알고리즘 (15)
        • 자바 (3)
        • 운영체제 (8)
        • AI와 데이터 (9)
      • 대외활동 (12)
        • NPC 동아리 (1)
        • UMC 동아리 (11)
      • 대학교 (1)
        • 교직 (1)
      • 기타 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글 관리
  • 링크

  • 공지사항

    • Notice
  • 인기 글

  • 태그

    mysql
    java
    Unity
    자바
    코틀린
    유니티
    kotlin
    Python
    Lua
    C
    파이썬
    안드로이드
    루아
    Android
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
2월2
[Android/Kotlin] 안드로이드 스튜디오 알림 안뜸 해결
상단으로

티스토리툴바