안녕하세요.
오늘은 Android Notification을 만들어보는 예제를 소개합니다.
안드로이드 서비스에서는 현재 서비스가 동작중임을 나타내는 Notification을 띄워야합니다.
안드로이드 오레오 이상부터는 포어그라운드서비스 동작중에 Notification을 무조건 띄워야합니다.
* https://developer.android.com/about/versions/oreo/android-8.0-changes?hl=ko
NotificationBuilder를 사용해서 Android Service에서 Notification을 생성할 수 있습니다.
다음과 같은 처리를 하고 있는 소스코드를 작성해보겠습니다.
* 액티비티 혹은 프레그먼트에서 서비스 실행 (+ 안드로이드 오레오 이상 예외처리)
* 서비스에서 NotificationBuilder 생성
* 안드로이드 오레오일경우 NotificationChannel 생성
* 포어그라운드 서비스 시작
아래의 소스코드는 액티비티 혹은 프레그먼트에서 서비스 실행하는 코드입니다.
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.sample.databinding.MyFragmentBinding
class MyFragment : Fragment() {
companion object {
private const val TAG = "MyFragment"
}
private var _binding: MyFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = MyFragmentBinding.inflate(inflater, container, false)
val root: View = binding.root
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
startMyService();
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun startMyService() {
Intent(context, MyService::class.java).also {
Log.d(TAG, "startMyService: Intent: $it")
// Check Android Policy
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Over Android Oreo -> ForegroundService
context.startForegroundService(it)
} else {
// Less than Android Oreo
context.startService(it)
}
}
}
}
다음은 서비스 코드입니다.
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.annotation.Nullable
import androidx.core.app.NotificationCompat
class MyService : Service() {
companion object {
private const val TAG = "MyService"
}
private val FOREGROUND_ID: Int = 290348
private val foregroundNotificationBuilder: NotificationCompat.Builder
get() = NotificationCompat.Builder(this, applicationContext.packageName).
setSmallIcon(R.mipmap.ic_launcher_round).
setContentTitle("title").
setContentText("content text").
setPriority(NotificationCompat.PRIORITY_HIGH)
override fun onCreate() {
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForegroundService()
return START_STICKY
}
@Nullable
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onDestroy() {
super.onDestroy()
stopForeground(true)
}
private fun createNotificationChannel() {
val channelId = applicationContext.packageName
val channelName = BuildConfig.APPLICATION_ID
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
}
}
private fun startForegroundService() {
val notification = foregroundNotificationBuilder.build()
// when Over android oreo, need to notification channel.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
startForeground(FOREGROUND_ID, notification)
}
}
감사합니다.
참고한 사이트
* https://codechacha.com/ko/invalid-channel-for-service-notification/
안드로이드 - invalid channel for service notificaiton 에러 해결 방법
Android에서 startForeground()로 bacground 서비스를 foreground로 변경할 때 발생하는 "invalid channel for service notification" 에러 해결 방법입니다. 안드로이드 O부터 노티피케이션을 등록할 때 ChannelId를 먼저 등
codechacha.com
* https://github.com/mcomella/NotificationManager
GitHub - mcomella/NotificationManager: Experiments with Android notifications
Experiments with Android notifications. Contribute to mcomella/NotificationManager development by creating an account on GitHub.
github.com
* https://developer.android.com/training/notify-user/expanded?hl=ko
'Development > Android' 카테고리의 다른 글
Android MVVM with Retrofit2 (0) | 2022.01.30 |
---|---|
Gson 라이브러리 사용하기 (0) | 2022.01.25 |
Android에서 설치된 특정 패키지 검색하기 (0) | 2022.01.12 |
Material Design 3 (0) | 2021.12.03 |
안드로이드 액션바 제거하기 (0) | 2021.11.08 |