안드로이드 백그라운드 음악 서비스란?
예제를 살펴보기 전에, 안드로이드에서 서비스(Service)가 무엇인지 먼저 이해할 필요가 있습니다. 서비스는 UI와 상호작용하지 않은 채 백그라운드에서 작업을 수행하는 컴포넌트로, 액티비티(Activity)가 종료된 이후에도 계속해서 실행됩니다.
이 글에서는 실제 예제를 통해 안드로이드에서 백그라운드 음악 재생 서비스를 구현하는 방법을 단계별로 알아보겠습니다.
1단계: 새 프로젝트 생성
Android Studio를 열고 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.
2단계: 레이아웃 파일 작성 (res/layout/activity_main.xml)
아래 코드를 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를 화면 중앙에 배치했습니다. 사용자가 이 TextView를 클릭하면 음악 서비스가 시작되고, 다시 클릭하면 서비스가 중지됩니다.
3단계: MainActivity 작성 (src/MainActivity.java)
아래 코드를 MainActivity.java에 추가합니다.
package com.example.andy.myapplication;
import android.app.ActivityManager;
import android.content.Context;
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 (isMyServiceRunning(service.class)) {
text.setText("Stoped");
stopService(new Intent(MainActivity.this, service.class));
} else {
text.setText("Started");
startService(new Intent(MainActivity.this, service.class));
}
}
});
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
위 코드는 Intent에 컨텍스트(Context)와 서비스 클래스를 전달하여 서비스를 시작하고 중지하는 역할을 합니다. 또한 isMyServiceRunning() 메서드를 통해 현재 해당 서비스가 실행 중인지 확인한 후, 상태에 따라 시작 또는 중지를 결정합니다.
이제 패키지 폴더 안에 service.java라는 이름의 서비스 클래스를 생성하고 아래 코드를 추가합니다.
package com.example.andy.myapplication;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service {
MediaPlayer musicPlayer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
musicPlayer = MediaPlayer.create(this, R.raw.abc);
musicPlayer.setLooping(false);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Music Service started by user.", Toast.LENGTH_LONG).show();
musicPlayer.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
musicPlayer.stop();
Toast.makeText(this, "Music Service destroyed by user.", Toast.LENGTH_LONG).show();
}
}
위 코드의 핵심 부분을 살펴보면 다음과 같습니다.
- onCreate(): MediaPlayer 객체를 생성하고 raw 폴더의 음원 파일(abc)을 연결한 뒤, 반복 재생 여부를 설정합니다.
- onStartCommand(): 서비스가 시작될 때 호출되며, 토스트 메시지를 표시하고 음악 재생을 시작합니다.
START_STICKY를 반환하여 시스템에 의해 종료되더라도 서비스가 다시 생성되도록 합니다. - onDestroy(): 서비스가 종료될 때 음악 재생을 중지하고 토스트 메시지를 표시합니다.
4단계: 매니페스트 등록 (manifest.xml)
서비스를 사용하려면 반드시 AndroidManifest.xml에 서비스를 선언해야 합니다. 아래와 같이 <service> 태그를 application 태그 안에 추가합니다.
<?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를 클릭하면 음악 서비스가 중지됩니다.
정리
이번 예제를 통해 안드로이드 서비스의 기본 개념과 함께 MediaPlayer를 활용한 백그라운드 음악 재생 구현 방법을 살펴보았습니다. 핵심 포인트는 다음과 같습니다.
- 서비스는 UI 없이 백그라운드에서 작업을 수행하며, 액티비티 종료 후에도 유지됩니다.
- Intent를 통해 서비스를 시작(startService)하고 중지(stopService)할 수 있습니다.
- 서비스는 반드시 AndroidManifest.xml에 선언해야 정상적으로 동작합니다.
이 기반 위에 포그라운드 서비스(Foreground Service), 알림(Notification) 연동, 오디오 포커스 처리 등을 추가하면 더욱 완성도 높은 음악 플레이어 앱을 만들 수 있습니다.