본문 바로가기
안드로이드/개발자 일상

안드로이드 Service ( 자동 종료되지 않는 서비스 주의점 )

by 차누감 2020. 4. 24.

Android 8.0(API 레벨 26)는 사용자 환경을 개선하기 위해 백그라운드에서 실행되면서 앱의 동작을 제한합니다.

(자세한 사항은 아래 안드로이드 개발자 사이트를 참고 바랍니다.)

https://developer.android.com/about/versions/oreo/background

 

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

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

developer.android.com

또한 알아두어야 할 점은 

서비스를 지속적으로 실행할 때는 여러 가지 제한이 있습니다.

 

배터리 최적화 모드 해제- 플러그를 뽑거나, 화면을 꺼두거나, 같은 자리에 계속 있을 경우 잠자기 모드 실행되므로, 만약 지속적인 휴대폰 기능을 원하신 다면 고려해야 합니다.

2020/04/22 - [안드로이드/개발자 일상] - 안드로이드 배터리 최적화 풀기 ( 잠자기 모드 해제 )

 

26 API 이상부터 서비스 실행 메소드 - startForegroundService() 사용. ( 이전은 startService 사용해도 무관합니다. )

 

시스템이 서비스를 생성한 후 - 앱은 5초 이내에 해당 서비스의 startForeground() 메서드를 호출하여 새 서비스의 알림을 사용자에게 표시해야 합니다.

그리고 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> 권한이 필요합니다.

 

예시 코드) 서비스 내에서 startForegroundService()

더보기
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
 void startForegroundService() {
 
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        pendingIntent = PendingIntent.getActivity(this0, notificationIntent, 0);
        
        if (Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "snwodeer_service_channel";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "SnowDeer Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT);
 
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                    .createNotificationChannel(channel);
 
            builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(this);
        }
 
        builder.setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("앱")
                .setContentIntent(pendingIntent);
 
        startForeground(1builder.build());
 
    }// startForegroundService()..
 
 

 

참고: Android 9(API 레벨 28) 이상을 대상으로 하고 포그라운드 서비스를 사용하는 앱은 FOREGROUND_SERVICE 권한을 요청해야 합니다. 

 

위치 권한 ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION 권한을 요청한다면,

Android 10에 ACCESS_BACKGROUND_LOCATION 권한이 도입되었습니다.

댓글