Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 안드로이드 앱 부팅 시 서비스 자동 시작 구현하기


이 튜토리얼에서는 Kotlin을 사용하여 안드로이드 기기가 부팅(재시작)될 때 서비스(Service)를 자동으로 시작하는 방법을 단계별로 살펴봅니다. 핵심은 부팅 완료 브로드캐스트를 수신하는 BroadcastReceiver와 백그라운드에서 동작하는 Service를 함께 활용하는 것입니다.

1단계 — 새 프로젝트 만들기

Android Studio에서 File → New Project를 선택한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

2단계 — 메인 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello World"
        android:textColor="@android:color/background_dark"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

3단계 — 서비스 클래스 작성

새 Kotlin 클래스를 만들고 RunServiceOnBoot.kt에 다음 코드를 추가합니다. 이 서비스는 Handler를 이용해 5초(runTime = 5000) 간격으로 작업을 반복 실행하며, START_STICKY를 반환해 시스템에 의해 강제 종료되더라도 가능한 한 다시 시작되도록 설정합니다.

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.util.Log
import android.widget.Toast
class RunServiceOnBoot : Service() {
    private val TAG = "MyService"
    private lateinit var handler: Handler
    private lateinit var runnable: Runnable
    private val runTime = 5000
    override fun onCreate() {
        super.onCreate()
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show()
        Log.i(TAG, "onCreate")
        handler = Handler()
        runnable = Runnable { handler.postDelayed(runnable, runTime.toLong()) }
        handler.post(runnable)
    }
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
    override fun onDestroy() {
        handler.removeCallbacks(runnable)
        super.onDestroy()
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }
    override fun onStart(intent: Intent?, startId: Int) {
        super.onStart(intent, startId)
        Log.i(TAG, "onStart")
    }
}

4단계 — 부팅 수신 리시버 작성

새 Kotlin 클래스를 만들고 StartAppOnBoot.kt에 다음 코드를 추가합니다. 이 BroadcastReceiver는 기기 부팅이 완료되면 시스템이 발송하는 ACTION_BOOT_COMPLETED 브로드캐스트를 감지하여 메인 액티비티를 실행합니다. 백그라운드에서 액티비티를 띄우려면 FLAG_ACTIVITY_NEW_TASK 플래그가 반드시 필요합니다.

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class StartAppOnBoot : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (Intent.ACTION_BOOT_COMPLETED == intent!!.action) {
            val i = Intent(context, MainActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context!!.startActivity(i)
        }
    }
}

5단계 — MainActivity 작성

src/MainActivity.kt에 다음 코드를 추가합니다. 액티비티가 생성되는 시점에 RunServiceOnBoot 서비스를 시작합니다.

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val intent1 = Intent(this@MainActivity, RunServiceOnBoot::class.java)
        startService(intent1)
    }
}

6단계 — 매니페스트 설정

AndroidManifest.xml에 다음 코드를 추가합니다. 가장 중요한 부분은 RECEIVE_BOOT_COMPLETED 권한 선언과 리시버의 intent-filter 등록입니다. QUICKBOOT_POWERON 액션까지 함께 추가하면 일부 제조사 기기의 빠른 부팅 환경에서도 정상적으로 동작합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.q9">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".StartAppOnBoot">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
           </intent-filter>
        </receiver>
    <service android:name=".RunServiceOnBoot" />
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 실행(Run) 아이콘 Kotlin으로 안드로이드 앱 부팅 시 서비스 자동 시작 구현하기 을 클릭하고 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기 화면에 앱의 기본 화면이 표시됩니다.

Kotlin으로 안드로이드 앱 부팅 시 서비스 자동 시작 구현하기

참고: 정확한 결과를 확인하려면 에뮬레이터보다 실제 기기에서 직접 테스트하는 것이 좋습니다. 또한 안드로이드 10(API 29) 이상에서는 백그라운드에서 액티비티를 시작하는 동작이 제한되므로, 최신 OS 버전에서는 부팅 시 서비스 자동 시작 로직 위주로 검증하는 것을 권장합니다.