«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

올해는 머신러닝이다.

Android에서 BOOT_COMPLETED 등의 브로드캐스트 받는 방법 본문

스터디/Android

Android에서 BOOT_COMPLETED 등의 브로드캐스트 받는 방법

행복한 수지아빠 2025. 2. 18. 09:33

Android 13 이상에서는 보안 강화로 인해 BOOT_COMPLETED 등의 브로드캐스트를 받으려면 추가적인 설정이 필요합니다. 다음과 같은 방법을 시도해보세요.

1. 권한 선언 (AndroidManifest.xml)

먼저, AndroidManifest.xml에 RECEIVE_BOOT_COMPLETED 권한을 선언해야 합니다.

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

2. BroadcastReceiver 등록

BOOT_COMPLETED 이벤트를 수신할 BroadcastReceiver를 등록합니다.

<receiver android:name=".BootReceiver"
    android:enabled="true"
    android:exported="false"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

Android 12 이상에서는 android:exported="true"를 사용하면 보안상 문제가 될 수 있으므로 false로 설정해야 합니다.

3. BootReceiver 클래스 구현

BroadcastReceiver를 구현하여 부팅 후 실행할 동작을 정의합니다.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Log.d("BootReceiver", "Device Booted!");
            
            // 예제: 서비스 시작 (백그라운드 작업 필요 시)
            Intent serviceIntent = new Intent(context, MyBackgroundService.class);
            context.startForegroundService(serviceIntent);
        }
    }
}

4. Foreground Service 사용 (Android 13 이상 필수)

Android 13 이상에서는 백그라운드에서 실행되는 앱이 제한되므로 Foreground Service를 활용해야 합니다.
예제:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

public class MyBackgroundService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("MyBackgroundService", "Service Started!");

        // Foreground Service 실행
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "boot_channel")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Boot Completed")
                .setContentText("Background Service is running")
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        startForeground(1, builder.build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("MyBackgroundService", "Service Running...");
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

5. 앱 실행 후 사용자가 직접 실행 허용 (Android 13 이상)

Android 13부터 BOOT_COMPLETED 브로드캐스트를 받으려면 사용자가 앱을 한 번 실행해야 합니다. 처음 설치 후 앱이 실행되지 않은 상태에서는 이벤트를 받을 수 없습니다.

6. 대체 방법: WorkManager 활용

부팅 시 작업을 예약하려면 WorkManager를 활용하는 것도 방법입니다.

import android.content.Context;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import android.util.Log;

public class BootWorker extends Worker {
    public BootWorker(Context context, WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {
        Log.d("BootWorker", "Boot Task Executed!");
        return Result.success();
    }
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            WorkManager.getInstance(context).enqueue(
                new OneTimeWorkRequest.Builder(BootWorker.class).build()
            );
        }
    }
}

결론

  1. AndroidManifest.xml에 RECEIVE_BOOT_COMPLETED 권한 선언
  2. BOOT_COMPLETED 브로드캐스트를 받을 수 있도록 BroadcastReceiver 등록
  3. Android 13 이상에서는 Foreground Service 또는 WorkManager를 사용해야 함
  4. 앱이 한 번 실행된 후에야 브로드캐스트 수신 가능 (설치 후 바로는 불가)

이 방법들을 적용하면 Permission Denial 문제를 해결할 수 있습니다. 🚀