Android Service


안드로이드에서 서비스(Service)는 백그라운드에서 실행되는 컴포넌트로, 사용자가 앱과 상호작용하지 않는 동안에도 작업을 수행할 수 있습니다. 서비스는 일반적으로 네트워크 요청, 파일 I/O, 데이터베이스 작업과 같은 장기 실행 작업을 수행하는 데 사용됩니다. IntentService는 백그라운드에서 인텐트(intent)를 처리하는 특수한 유형의 서비스입니다.

1. 서비스(Service)

서비스는 안드로이드 애플리케이션에서 장기 실행 작업을 수행하기 위한 기본적인 백그라운드 컴포넌트입니다.

주요 특성:

  • 생명주기 메서드: onCreate(), onStartCommand(), onDestroy()
  • 두 가지 유형:
  • Started Service: startService()를 통해 시작되고, 작업이 완료될 때까지 계속 실행됩니다.
  • Bound Service: bindService()를 통해 다른 컴포넌트에 바인딩되어 실행됩니다.

간단한 예제:

이 예제는 서비스가 시작되고 로그 메시지를 출력하는 간단한 MyService를 구현합니다.

1. 서비스 클래스 정의 (MyService.java):

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    private static final String TAG = "MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service Created");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service Started");
        // 여기에 작업을 추가
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service Destroyed");
    }

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

2. AndroidManifest.xml에 서비스 등록:

<service android:name=".MyService"/>

3. 서비스 시작과 종료 (MainActivity.java):

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 서비스 시작
        Intent intent = new Intent(this, MyService.class);
        startService(intent);

        // 서비스 종료
        // stopService(intent);
    }
}

2. IntentService

IntentServiceService를 상속받아 백그라운드에서 작업을 처리하고, 작업이 완료되면 자동으로 종료됩니다.

주요 특성:

  • 자동 종료: 작업이 완료되면 IntentService는 자동으로 종료됩니다.
  • 작업 큐: 여러 인텐트를 순차적으로 처리합니다.
  • 백그라운드 스레드: 모든 작업이 별도의 백그라운드 스레드에서 수행됩니다.

간단한 예제:

이 예제는 IntentService를 사용하여 간단한 백그라운드 작업을 수행합니다.

1. IntentService 클래스 정의 (MyIntentService.java):

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.Nullable;

public class MyIntentService extends IntentService {
    private static final String TAG = "MyIntentService";

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            Log.d(TAG, "IntentService Started");
            // 여기에 작업을 추가
            Log.d(TAG, "Task Completed");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "IntentService Destroyed");
    }
}

2. AndroidManifest.xml에 IntentService 등록:

<service android:name=".MyIntentService"/>

3. IntentService 시작 (MainActivity.java):

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // IntentService 시작
        Intent intent = new Intent(this, MyIntentService.class);
        startService(intent);
    }
}

요약

  • 서비스: 백그라운드에서 장기 실행 작업을 수행할 때 사용. startService()를 통해 시작되고 수동으로 종료해야 합니다.
  • IntentService: 백그라운드 작업을 순차적으로 처리하고 자동으로 종료되는 특수한 서비스. onHandleIntent() 메서드 내에서 작업을 처리합니다.

이 두 가지 서비스를 사용하여 안드로이드 애플리케이션에서 효율적으로 백그라운드 작업을 처리할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *