728x90
안드로이드 4대 구성요소 중 하나로 백그라운드 처리를 위해 제공되는 요소이다.
Activity는 화면을 가지고 있어 화면이 보이는 동안 동작하지만 Service는 화면을 가지고 있지 않아 보이지 않는 동안에도 동작하는 것을 의미한다.
Foreground Service
Service는 백그라운드에서 운영되는 실행요소로써 메모리가 부족해지거나 절전 모드가 되는 등 다양한 상황에서 안드로이드 OS에 의해 제거 될 수 있다.
이를 방지하고자 할 때는 Foreground Service로 만들어 사용하면 된다.
Foreground Service외의 서비스는 안드로이드 OS에 의해 모두 제거될 수 있다.
Foreground Service의 목적은 현재 단말기에서 Service를 통해 백그라운드에서 작업 중이라는 것을 사용자에게 알리는 목적으로 사용한다.
package com.example.service
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val serviceIntent = Intent(this,TestService::class.java)
button.setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent)
} else {
startService(serviceIntent)
}
}
button2.setOnClickListener {
stopService(serviceIntent)
}
}
}
서비스
package com.example.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.IBinder
import android.os.SystemClock
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlin.concurrent.thread
class TestService : Service() {
var isRunning = false
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
// 서비스가 가동될 떄 호출되는 메서드
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("test", "서비스 가동")
// 안드로이드 8.0 이상부터
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel("service","service",NotificationManager.IMPORTANCE_HIGH)
channel.enableLights(true)
channel.lightColor = Color.RED
channel.enableVibration(true)
manager.createNotificationChannel(channel)
val builder = NotificationCompat.Builder(this,"service")
builder.setSmallIcon(android.R.drawable.ic_menu_search)
builder.setContentTitle("서비스 가동")
builder.setContentText("서비스가 가동 중입니다")
val notification = builder.build()
// 알림 메세지룰 Foreground 서비스를 위해 표시한다
startForeground(10,notification)
}
isRunning = true
thread {
while (isRunning) {
SystemClock.sleep(500)
val now = System.currentTimeMillis()
Log.d("test","Service : $now")
}
}
isRunning = true
return super.onStartCommand(intent, flags, startId)
}
// 서비스가 중지되고 소멸될때 호출되는 메서드
override fun onDestroy() {
super.onDestroy()
Log.d("test","서비스 중지")
isRunning = false
}
}
권한 추가
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.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.Service"
tools:targetApi="31">
<service
android:name=".TestService"
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>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
</manifest>
728x90
'안드로이드 > Service' 카테고리의 다른 글
안드로이드 IPC (0) | 2022.06.16 |
---|---|
안드로이드 시스템 메시지 (0) | 2022.06.16 |
안드로이드 Broad Cast Receiver (0) | 2022.06.16 |