(다음 포스팅을 참고 했습니다. -> https://parkho79.tistory.com/12)

 

 

백그라운드 상태에서 (앱이 완전히 종료된 상태)

서비스를 실행할 수 있는 이벤트를 주었더니 다음과 같은 에러문이 나왔다.

Caused by: java.lang.IllegalStateException: Not allowed to start service Intent

 

찾아보니, Android O 버전 이상부터는 백그라운드 실행이 제한되었다고 한다.

그래서 Foreground service 를 사용해야한다.

 

관련 Android Developers 문서는 다음과 같다.

https://developer.android.com/about/versions/oreo/background?hl=ko#services

 

백그라운드 실행 제한  |  Android 개발자  |  Android Developers

Android 8.0 이상을 대상으로 하는 앱에 대한 새로운 백그라운드 제한.

developer.android.com

 

서비스를 호출해야한다면, 다음과 같이 코드를 변경해야한다.

1. 서비스 호출

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService(new Intent(context, TestService.class));
} else {
    context.startService(new Intent(context, TestService.class));
}

2. 서비스 실행

public class TestService extends Service
{
    @Override
    public void onCreate() {
        super.onCreate();
 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            final String strId = getString(R.string.noti_channel_id);
            final String strTitle = getString(R.string.app_name);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channel = notificationManager.getNotificationChannel(strId);
            if (channel == null) {
                channel = new NotificationChannel(strId, strTitle, NotificationManager.IMPORTANCE_HIGH);
                notificationManager.createNotificationChannel(channel);
            }
 
            Notification notification = new NotificationCompat.Builder(this, strId).build();
            startForeground(1, notification);
        }
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true);
        }
    }
}

 

 

+ Recent posts