Apple 정품 아이폰 16 Pro 자급제, 화이트 티타늄, 256GB






블로그 내에서 다른 포스팅 검색하기기
검색어를 입력해주세요

목차

  1. 포그라운드 서비스란?
  2. 백그라운드 서비스와의 차이점
  3. 포그라운드 서비스 생성 및 실행 예제
  4. REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 설정하여 서비스 종료 방지

 

 

안드로이드 개발자 페이지에서 확인할 수 있는 포그라운드 서비스에 대한 설명

 

 

 

 

1. 포그라운드 서비스란?

포그라운드 서비스는 안드로이드 앱에서 백그라운드에서 지속적으로 동작해야 하면서 사용자에게 중요한 작업을 수행하는 서비스입니다.

포그라운드 서비스는 사용자가 앱을 사용하고 있을 때도 알림과 함께 계속해서 동작하므로 사용자에게 알리지 않고는 종료되지 않습니다.

 

주로 음악 재생, 위치 추적, 네트워크 요청 등 사용자가 인지해야 할 중요한 작업을 백그라운드에서 수행할 때 사용됩니다.

 

 

우리가 프로그래밍을 하다보면 절대 꺼지지 말아야할 서비스들이 존재한다.

 

 

 

2. 백그라운드 서비스와의 차이점

백그라운드 서비스와 포그라운드 서비스는 모두 백그라운드에서 동작하는 서비스입니다.

하지만 포그라운드 서비스는 사용자에게 중요한 작업을 알리기 위해 알림을 보여주고, 사용자가 인지하지 않아도 종료되지 않습니다.

 

반면에 백그라운드 서비스는 사용자에게 알림 없이 조용히 동작하며, 안드로이드 시스템이 자원 부족 상태일 때 종료될 수 있습니다.

 

 

백그라운드 서비스와 포그라운드 서비스는 동일하다. 하지만 사용자에게 자신을 알리냐 알리지 않냐의 차이점이 크기도 하다. (https://my-lingo.com/enko/wp-content/uploads/2022/12/I2825.png)

 

 

 

 

3. 포그라운드 서비스 생성 및 실행 예제

아래는 포그라운드 서비스를 생성하고 실행하는 예제입니다.

 

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

public class MyForegroundService extends Service {

    private static final int NOTIFICATION_ID = 1;
    private static final String CHANNEL_ID = "my_foreground_service_channel";

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("포그라운드 서비스 실행 중")
                .setContentText("서비스가 실행 중입니다.")
                .setSmallIcon(R.drawable.ic_notification_icon)
                .build();

        startForeground(NOTIFICATION_ID, notification);

        // 포그라운드 서비스에서 수행할 작업을 여기에 구현

        return START_STICKY;
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }
}

 

 

 

 

 

4. REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 설정하여 서비스 종료 방지

포그라운드 서비스가 중요한 작업을 수행하다가 배터리 최적화로 인해 종료되는 것을 방지하기 위해 REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 권한을 설정할 수 있습니다.

 

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

 

그리고 서비스 시작 시 다음과 같이 배터리 최적화를 무시하는 옵션을 추가하여 서비스가 종료되지 않도록 설정할 수 있습니다.

 

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    Intent intent = new Intent();
    String packageName = getPackageName();
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    if (!powerManager.isIgnoringBatteryOptimizations(packageName)) {
        intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + packageName));
        startActivity(intent);
    }
}
반응형


살구엉덩이님의
글이 좋았다면 응원을 보내주세요!