클리엘
CLIEL LAB
클리엘
전체 방문자
131,483
오늘
133
어제
331
  • 분류 전체보기 (442) N
    • Mobile (47)
      • Kotlin (47)
    • Web (84)
      • NestJS (9)
      • HTML5 & CSS3 (38)
      • Javascript (20)
      • TypeScript (6)
      • JQuery (11)
    • .NET (233) N
      • C# (57) N
      • ASP.NET Core (31)
      • Windows API for .NET (128)
    • Server (50)
      • SQL Server (8)
      • MariaDB (18)
      • Windows Server (5)
      • node.js (19)
    • System (12)
      • 작업LOG (12)
    • Review (11)
    • ETC (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • 블로그 정리

인기 글

  • [C#] C#과 .NET6 시작하기 - 3.⋯
    2022.06.24
    [C#] C#과 .NET6 시작하기 - 3.⋯
  • [C#] C# 개요 - 3. 기타 Consol⋯
    2022.06.24
    [C#] C# 개요 - 3. 기타 Consol⋯
  • [C#] 인터페이스(Interface)와⋯
    2022.06.24
    [C#] 인터페이스(Interface)와⋯
  • [C#] 예외처리
    2022.06.24
    [C#] 예외처리
  • [C#] C#과 OOP(Object-Oriented⋯
    2022.06.24
    [C#] C#과 OOP(Object-Oriented⋯

태그

  • node.js
  • c#
  • .NET
  • android
  • 메서드
  • JavaScript
  • asp.net core
  • CSS3
  • jQuery
  • Kotlin
  • Windows API
  • TypeScript
  • android studio
  • 변수
  • asp.net core web api
  • CentOS
  • MariaDB
  • EF-Core
  • NestJS
  • HTML5

최근 댓글

  • 흠... CACLS는 더이상 사용하지⋯
    클리엘
  • 안녕하세요! 아래 명령 하고부⋯
    방문자
  • 죄송합니다. 관련글을 작성한지⋯
    클리엘
  • 네 맞습니다. 본문에서는 표기⋯
    클리엘
  • 6000 ms 는 6초아닌가요?
    react

최근 글

  • [C#] LINQ(Language INtegrated⋯
    2022.07.05
    [C#] LINQ(Language INtegrated⋯
  • [C#] LINQ(Language INtegrated⋯
    2022.07.05
  • [C#] LINQ(Language INtegrated⋯
    2022.07.05
    [C#] LINQ(Language INtegrated⋯
  • [.NET] 닷넷 Type 사용하기 - 8⋯
    2022.06.26
    [.NET] 닷넷 Type 사용하기 - 8⋯
  • [.NET] 닷넷 Type 사용하기 - 7⋯
    2022.06.26

티스토리

hELLO · Designed By 정상우.
클리엘

CLIEL LAB

[Kotlin] 포어그라운드(Foreground) 서비스
Mobile/Kotlin

[Kotlin] 포어그라운드(Foreground) 서비스

2021. 1. 8. 11:00
728x90

일반적으로 서비스는 백그라운드(Background)로 동작합니다. 하지만 필요에 따라서는 이 서비스를 포어그라운드(Foreground)로도 실행할 수 있습니다. 포어그라운드라면 서비스가 동작하는 것 자체를 사용자에게 표시해야 하는데 이때는 휴대폰의 상단 상태바를 활용하게 됩니다.

 

우선 서비스를 포어그라운드로 동작시키려면 해당 권한을 명시해야 합니다. app -> manifests -> AndroidManifest.xml파일에 다음과 같은 태그를 추가해 주세요.

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

그다음 app -> java -> [패키 지명]에서 마우스 오른쪽 버튼을 눌러 New -> Service -> Service를 선택합니다. 화면상의 Class Name은 MyService정도로 하고 Finish를 눌러줍니다.

 

파일이 생성되면 onBind() 메서드를 아래와 같이 수정합니다.

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

그리고 상태바에 알림을 표시할 메서드를 작성합니다. 알림은 채널단위로 동작하기에 사용할 채널 변수(SC)를 설정하고 설정한 채널로 알림이 표시되도록 하는 것입니다.

class MyService : Service() {
    val SC = "myService"

    fun Notification() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val nc = NotificationChannel(SC, "My Service Channel", NotificationManager.IMPORTANCE_DEFAULT)
            val nm = getSystemService(NotificationManager::class.java)

            nm.createNotificationChannel(nc)
        } else {
            Toast.makeText(this, "알림을 실행할 수 없음", Toast.LENGTH_LONG).show()
        }
    }

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

위에서 알림 채널을 생성하였으면 onStartCommand()를 오버라이드 하여 Notification() 메서드를 호출해 채널을 만들고, 알림 제목과 아이콘을 지정하여 알림을 생성한 뒤 startForeground() 메서드로 알림을 표시하도록 합니다. 이때 NotificationCompat의 setContentTitle에서는 알림의 제목을, setSmallIcon에서는 알림의 아이콘을 지정하고 있는데 이러한 설정은 생략이 가능합니다.

class MyService : Service() {
    val SC = "myService"

    fun Notification() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val nc = NotificationChannel(SC, "My Service Channel", NotificationManager.IMPORTANCE_DEFAULT)
            val nm = getSystemService(NotificationManager::class.java)

            nm.createNotificationChannel(nc)
        } else {
            Toast.makeText(this, "알림을 실행할 수 없음", Toast.LENGTH_LONG).show()
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Notification()

        val nc: Notification = NotificationCompat.Builder(this, SC).setContentTitle("myNotify").setSmallIcon(R.mipmap.ic_launcher_round).build()
        startForeground(1, nc)

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

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

이번에는 MainActivity.kt에서 서비스를 실행하는 ServiceStart()와 서비스를 중지하는 ServiceStop() 메서드를 작성합니다. 특히 ServiceStart() 메서드에 주목해 주세요. 서비스를 포어그라운드로 동작시키려면 ContextCompat.startForegroundService() 메서드를 사용해야 합니다.

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

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

그런 다음 MainActivity 디자인 화면에서 다음과 같이 버튼 2개를 만들고 각각 ID를 btnServiceStart와 btnServiceStop으로 지정합니다. 그리고 btnServiceStart 버튼의 onClick속성에는 ServiceStart() 메서드를 btnServiceStop 버튼의 onClick속성에는 ServiceStop() 메서드를 지정합니다. 그러면 각 버튼을 클릭할 때마다 해당 메서드를 호출하게 됩니다. 이러한 방법이 가능한 이유는 위에서 ServiceStart()와 ServiceStop() 메서드를 만들 때 매개변수로 View를 지정했기 때문입니다.

 

앱을 동작시켜 '서비스실행'버튼을 누르면 상태바에 설정한 알림이 표시되는 걸 확인할 수 있습니다.

 

728x90
저작자표시비영리변경금지

'Mobile > Kotlin' 카테고리의 다른 글

[Kotlin] HttpURLConnection  (2) 2021.01.12
[Kotlin] 컨텐트 리졸버(Content Resolver)  (0) 2021.01.11
[Kotlin] 포어그라운드(Foreground) 서비스  (0) 2021.01.08
[Kotlin] 서비스(Service)  (0) 2021.01.07
[Kotlin] AsyncTask  (0) 2021.01.06
[Kotlin] 프로세스(Process)와 스레드(Thread)  (0) 2021.01.05
    'Mobile/Kotlin' 카테고리의 다른 글
    • [Kotlin] HttpURLConnection
    • [Kotlin] 컨텐트 리졸버(Content Resolver)
    • [Kotlin] 서비스(Service)
    • [Kotlin] AsyncTask
    클리엘
    클리엘
    누구냐 넌?
    댓글쓰기
    다음 글
    [Kotlin] 컨텐트 리졸버(Content Resolver)
    이전 글
    [Kotlin] 서비스(Service)
    • 이전
    • 1
    • ···
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • ···
    • 442
    • 다음

    티스토리툴바