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

안드로이드에서 서비스를 항상 백그라운드로 실행하는 방법

안드로이드 백그라운드 서비스란?

서비스(Service)는 사용자 인터페이스 없이 백그라운드에서 오랫동안 작업을 수행할 수 있는 안드로이드의 핵심 컴포넌트입니다. 음악 재생, 위치 추적, 데이터 동기화처럼 화면이 꺼져 있거나 다른 앱을 사용 중일 때도 계속 실행되어야 하는 기능에 활용됩니다. 이 글에서는 앱이 종료되거나 사용자가 작업을 제거한 후에도 서비스가 살아 있도록 만드는 방법을 단계별로 살펴봅니다.

1단계 — 새 프로젝트 생성

안드로이드 스튜디오(Android Studio)에서 File → New Project를 선택하고, 필요한 정보를 모두 입력해 새 프로젝트를 만듭니다.

2단계 — 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 한가운데에 서비스 시작 버튼 하나를 배치한 단순한 레이아웃입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:text="Click here to start background Service"
android:textStyle="bold"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>

3단계 — 서비스 클래스 생성

프로젝트를 마우스 오른쪽 버튼으로 클릭한 뒤 New → Service → Service를 선택해 MyService.java 파일을 생성하고 다음 코드를 입력합니다.

여기서 핵심은 두 가지입니다. 첫째, onStartCommand()에서 START_STICKY를 반환하면 시스템이 서비스를 강제 종료한 후 리소스가 확보되었을 때 서비스를 자동으로 재생성합니다. 둘째, onTaskRemoved()를 오버라이드하여 사용자가 최근 앱 목록에서 앱을 스와이프로 제거하는 순간 서비스를 즉시 다시 시작하도록 처리했습니다.

package app.com.sample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
onTaskRemoved(intent);
Toast.makeText(getApplicationContext(),"This is a Service running in Background",
Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}

4단계 — 메인 액티비티 구현

src/MainActivity.java에 아래 코드를 추가합니다. 버튼을 클릭하면 startService()가 호출되어 MyService가 실행됩니다.

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(getApplicationContext(),MyService.class));
}
});
}
}

5단계 — 매니페스트에 서비스 등록

AndroidManifest.xml에 아래 코드를 추가합니다. 서비스 컴포넌트는 반드시 매니페스트에 선언해야 하며, 누락하면 런타임 오류가 발생합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<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">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

앱 실행 및 결과 확인

실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정하고 진행합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 다음 툴바의 Run 아이콘을 클릭하고, 대상 기기 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기에 아래와 같은 기본 화면이 나타납니다.

안드로이드에서 서비스를 항상 백그라운드로 실행하는 방법

안드로이드에서 서비스를 항상 백그라운드로 실행하는 방법

버튼을 누르면 'This is a Service running in Background'라는 토스트 메시지가 표시되면서 서비스가 백그라운드에서 실행됩니다. 이후 앱을 종료하거나 최근 앱 목록에서 제거해도 서비스는 계속 동작합니다.

참고: 최신 안드로이드 버전에서의 주의점

안드로이드 8.0(오레오)부터는 배터리 효율 정책이 강화되면서 백그라운드 서비스 실행에 제한이 생겼습니다. 장시간 실행이 필요하다면 Foreground Service(포그라운드 서비스)로 전환해 알림과 함께 실행하는 방식이 권장됩니다. 또한 삼성, 샤오미 등 일부 제조사 기기는 자체 절전 기능이 강력하기 때문에, 설정에서 해당 앱의 배터리 최적화를 해제해야 서비스가 안정적으로 유지됩니다.