이 튜토리얼에서는 Android 기기가 부팅을 완료했을 때 앱의 서비스를 자동으로 시작하는 방법을 단계별로 알아봅니다. 이 기능은 백그라운드에서 지속적으로 작업을 수행해야 하는 앱(예: 알림, 모니터링, 동기화 서비스 등)에 매우 유용합니다.
구현 개요
부팅 완료 시 서비스를 실행하려면 BroadcastReceiver를 사용하여 시스템의 부팅 완료 브로드캐스트(BOOT_COMPLETED)를 수신하고, 이를 통해 서비스를 시작하는 구조로 만듭니다. 전체 흐름은 다음과 같습니다.
- 부팅 완료 브로드캐스트를 수신하는 리시버 등록
- 리시버가 서비스를 호출하도록 구현
- 매니페스트에 권한 및 컴포넌트 선언
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:text="Hello World" android:textSize="24sp" android:layout_centerInParent="true" android:textStyle="bold"/> </RelativeLayout>
3단계: 부팅 리시버 클래스 생성
새 Java 클래스인 StartAppOnBoot.java를 생성하고 다음 코드를 추가합니다. 이 클래스는 기기 부팅이 완료되면 시스템이 발송하는 브로드캐스트를 수신하여 메인 액티비티를 실행합니다.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartAppOnBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}4단계: 서비스 클래스 생성
새 서비스 클래스인 RunServiceOnBoot.java를 생성하고 다음 코드를 추가합니다. 이 서비스는 핸들러(Handler)를 사용해 5초 간격으로 반복 작업을 수행하며, START_STICKY를 반환하여 시스템에 의해 종료되더라도 자동으로 재시작됩니다.
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class RunServiceOnBoot extends android.app.Service {
private static String TAG = "MyService";
private Handler handler;
private Runnable runnable;
private final int runTime = 5000;
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onCreate");
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(runnable, runTime);
}
};
handler.post(runnable);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
if (handler != null) {
handler.removeCallbacks(runnable);
}
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG, "onStart");
}
}5단계: MainActivity 작성
src/MainActivity.java에 다음 코드를 추가합니다. 액티비티가 생성될 때 서비스를 직접 시작하도록 구현합니다.
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent1 = new Intent(MainActivity.this, RunServiceOnBoot.class);
startService(intent1);
}
}6단계: AndroidManifest.xml 설정
AndroidManifest.xml에 다음 코드를 추가합니다. 여기서 가장 중요한 부분은 RECEIVE_BOOT_COMPLETED 권한 선언입니다. 이 권한이 없으면 부팅 완료 브로드캐스트를 받을 수 없습니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample"> <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 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바에서 Run 아이콘을 클릭합니다. 목록에서 본인의 모바일 기기를 선택하고, 기기 화면에 아래와 같이 결과가 표시되는지 확인합니다.



참고 사항
일부 제조사 기기(예: Xiaomi, Huawei 등)는 배터리 최적화 정책으로 인해 부팅 시 자동 실행을 차단할 수 있습니다. 이 경우 사용자가 설정에서 해당 앱의 자동 실행 권한을 허용해야 합니다. 또한 Android 10(API 29) 이상에서는 백그라운드 액티비티 시작에 제약이 있으므로, 액티비티 대신 서비스만 시작하는 방식이 더 안정적입니다.