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

안드로이드에서 액티비티와 서비스 간 통신하는 방법

이 튜토리얼에서는 안드로이드(Android)에서 액티비티(Activity)서비스(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/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="74dp"
        android:text="Start Service" />
    <Button
        android:id="@+id/buttonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Stop Service" />
</RelativeLayout>

3단계 — MainActivity 작성

src/MainActivity.java에 다음 코드를 추가합니다. 버튼 클릭 이벤트를 처리해 startService()로 서비스를 시작하거나 stopService()로 종료합니다.

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button buttonStart, buttonStop;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonStart = findViewById(R.id.buttonStart);
        buttonStop = findViewById(R.id.buttonStop);
        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
    }
    public void onClick(View src) {
        switch (src.getId()) {
            case R.id.buttonStart:
                startService(new Intent(this, MyService.class));
            break;
            case R.id.buttonStop:
                stopService(new Intent(this, MyService.class));
            break;
        }
    }
}

4단계 — MyService 클래스 작성

새로운 서비스 클래스인 MyService를 생성하고 MyService.java에 아래 코드를 작성합니다. 이 서비스는 MediaPlayer로 음악 파일을 재생하며, 생성·시작·종료 시점마다 토스트(Toast) 메시지로 상태를 알려줍니다.

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class MyService extends Service {
    MediaPlayer myPlayer;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "Service Created",
        Toast.LENGTH_LONG).show();
        myPlayer = MediaPlayer.create(this, R.raw.song);
        myPlayer.setLooping(false);
    }
    @Override
    public void onStart(Intent intent, int startId) {
        Toast.makeText(this, "Service Started",
        Toast.LENGTH_LONG).show();
        myPlayer.start();
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Stopped",
        Toast.LENGTH_LONG).show();
        myPlayer.stop();
    }
}

참고: onStart(Intent, int)는 현재 지원이 중단(deprecated)된 메서드입니다. 최신 안드로이드 버전에서는 onStartCommand(Intent, int, int)를 대신 사용하는 것이 좋습니다.

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>

앱 실행 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면 앱이 설치되고 기본 화면이 표시됩니다.

Start Service 버튼을 누르면 "Service Created", "Service Started" 토스트가 차례로 표시되며 음악이 재생되고, Stop Service 버튼을 누르면 "Service Stopped" 토스트와 함께 재생이 중지됩니다.

안드로이드에서 액티비티와 서비스 간 통신하는 방법

안드로이드에서 액티비티와 서비스 간 통신하는 방법