Android

안드로이드 스튜디오) 앱이 활성 상태일 때 계속 실행되는 포그라운드 서비스

567Rabbit 2024. 7. 2. 17:48

 

포그라운드 서비스란?

 

- 포그라운드 서비스는 애플리케이션에서 사용자 경험을 개선하고, 중요한 작업을 안정적으로 처리할 수 있는 중요한 도구

- 포그라운드 서비스는 사용자가 앱을 사용하고 있을 때도 알림을 통해 활성 상태임을 보여주기 때문에, 사용자는 언제든지 이 서비스를 중지하거나 상태를 확인할 수 있다.

- 이러한 특성 때문에 안드로이드 시스템은 포그라운드 서비스를 다른 백그라운드 서비스보다 우선적으로 다루며, 필요한 리소스와 권한을 제공한다.

 

 

포그라운드 서비스 사용 예시

 

음악 재생: 음악 앱에서는 포그라운드 서비스를 사용하여 사용자가 앱을 종료하더라도 음악을 계속 재생할 수 있다. 이 서비스는 알림을 통해 사용자에게 현재 재생 중인 음악을 보여주며, 음악 제어 기능도 제공할 수 있다.

 

위치 추적: 위치 기반 앱에서는 포그라운드 서비스를 사용하여 사용자의 위치를 지속적으로 추적할 수 있다. 이는 사용자에게 중요한 기능이며, 앱이 백그라운드에서도 정확한 위치 업데이트를 제공할 수 있다. 예) 내비게이션 앱, 운동 추적 앱

 

네트워크 요청 처리: 네트워크 요청이 긴 시간 동안 필요한 경우, 포그라운드 서비스를 사용하여 안정적으로 처리할 수 있다. 예) 파일 다운로드, 데이터 동기화, 뉴스 알림 등

 

 

 

 

환경설정하기

 

 

 

 

 

 

 

TrackingService.java

 

package com.~.tmap.services;
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;

import com.~.tmap.R;


public class TrackingService 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); // 포그라운드 서비스 종료
    }
}