Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 백그라운드 서비스 만드는 방법, 단계별 완벽 가이드

본격적인 예제에 들어가기 전에, 안드로이드에서 서비스(Service)가 무엇인지 먼저 이해할 필요가 있습니다. 서비스는 UI와 상호작용하지 않은 채 백그라운드에서 작업을 수행하는 컴포넌트로, 액티비티가 종료된 이후에도 계속해서 동작합니다. 음악 재생, 파일 다운로드, 네트워크 통신처럼 사용자에게 화면을 보여줄 필요가 없는 작업을 처리할 때 유용하게 활용됩니다.

이 글에서는 안드로이드에서 백그라운드 서비스를 생성하고, 시작하고, 중지하는 방법을 단계별로 알아보겠습니다.

1단계: 새 프로젝트 생성

Android Studio를 열고 File → New Project 메뉴로 이동한 뒤, 프로젝트 생성에 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다.

2단계: 레이아웃 파일(activity_main.xml) 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:app = "https://schemas.android.com/apk/res-auto"
    xmlns:tools = "https://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">
    <TextView
        android:id = "@+id/text"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text = "Start Service"
        android:textSize = "25sp"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintLeft_toLeftOf = "parent"
        app:layout_constraintRight_toRightOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>

위 코드에서는 하나의 TextView를 배치했습니다. 사용자가 이 텍스트뷰를 클릭하면 서비스가 시작되고, 다시 클릭하면 서비스가 중지되도록 구현할 것입니다.

3단계: MainActivity.java 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView text = findViewById(R.id.text);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (text.getText().toString().equals("Started")) {
                    text.setText("Stoped");
                    stopService(new Intent(MainActivity.this,service.class));
                } else {
                    text.setText("Started");
                    startService(new Intent(MainActivity.this,service.class));
                }
            }
        });
    }
}

위 코드의 핵심은 startService()stopService() 메서드입니다. Intent 객체에 현재 컨텍스트와 서비스 클래스 정보를 담아 전달함으로써 서비스를 시작하거나 중지할 수 있습니다.

서비스 클래스(service.java) 작성하기

이제 패키지 폴더 안에 service.java라는 이름의 서비스 클래스를 생성하고 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service {
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
   }
}

서비스 클래스에서는 세 가지 핵심 메서드를 오버라이드했습니다. onBind()는 바인딩이 필요 없는 경우 null을 반환하고, onStartCommand()는 서비스가 시작될 때 호출되며 START_STICKY를 반환해 시스템에 의해 종료되더라도 서비스가 다시 시작되도록 합니다. 마지막으로 onDestroy()는 서비스가 소멸될 때 호출됩니다.

4단계: AndroidManifest.xml에 서비스 등록

manifest.xml 파일에 아래 코드를 추가합니다. 반드시 <application> 태그 안에 <service> 요소를 선언해야 서비스가 정상적으로 동작합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.andy.myapplication">
    <application
        android:allowBackup = "true"
        android:icon = "@mipmap/ic_launcher"
        android:label = "@string/app_name"
        android:roundIcon = "@mipmap/ic_launcher_round"
        android:supportsRtl = "true"
        android:theme = "@style/AppTheme">
        <activity android:name = ".MainActivity">
            <intent-filter>
                <action android:name = "android.intent.action.MAIN" />
                <category android:name = "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name = ".service"/>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면 됩니다.

앱이 실행되면 기기에 초기 화면이 표시됩니다.

안드로이드 백그라운드 서비스 만드는 방법, 단계별 완벽 가이드

초기 화면에서 TextView를 클릭하면 아래와 같이 서비스가 시작됩니다.

안드로이드 백그라운드 서비스 만드는 방법, 단계별 완벽 가이드

서비스가 시작된 상태에서 다시 TextView를 클릭하면 아래와 같이 서비스가 중지됩니다.

안드로이드 백그라운드 서비스 만드는 방법, 단계별 완벽 가이드

마무리

지금까지 안드로이드에서 백그라운드 서비스를 생성하는 전체 과정을 살펴보았습니다. 레이아웃 구성, MainActivity에서의 서비스 시작·중지 처리, Service 클래스 작성, 그리고 매니페스트 등록까지 이 네 단계만 기억하면 어떤 프로젝트에서도 백그라운드 서비스를 손쉽게 구현할 수 있습니다. 참고로 안드로이드 최신 버전(API 26 이상)에서는 배터리 최적화 정책으로 인해 백그라운드 제약이 강화되었으므로, 장기 실행 작업에는 Foreground Service나 WorkManager 사용을 함께 고려하는 것이 좋습니다.