본문 바로가기
실시간TV∴영화∴드라마∴예능

안드로이드: 서비스 Service 예제

반응형

안드로이드: 서비스 Service 예제

 

액티비티등 사용자 인터페이스가 없어도 백그라운드에서 실행되는 동작이 필요할 때가 있습니다.  예를 들면 배경음악이라든지 안드로이드 사용량 모니터링이라든지, 주기적으로 특정 웹사이트에서 데이터를 읽어 온다든지...     이러한 기능을 안드로이드에서는 Service (서비스) 를 통해서 제공합니다.   

참고: 안드로이드 4대 컴포넌트
1. 액티비티 (Activity) 
2. 서비스 (Service)
3. 방송 수신자 (Broadcast Receiver)
4. 콘텐츠 제공자 (Contents Provider) 

 

갖고 계신 안드로이드 폰에서 실행되는 서비스를 확인해볼수 있습니다.

[환경설정] - [애플리케이션 관리자] 에서 [실행중] 을 선택하면 현재 실행중인 서비스들을 볼수 있습니다.  생각보다 많은 서비스들이 실행중인 것을 알수 있습니다.

 

이번예제에서는 안드로이드 4대 컴포넌트중 하나인 Service 를 구현해 보겠습니다.

기본적인 순서는 다음과 같습니다.

 

1. 사용할 Service (*.java)를 만든다

2. AndroidManifest.xml 에 Service를 등록한다

3. Service 를 시작하도록 호출한다

 

실행하면 [서비스 시작하기] 버튼을 누르면 배경음악을 재생하는 서비스가 시작되고 [서비스 종료하기] 버튼을 누르면 종료가 됩니다.

 

1. 사용할 Service (*.java)를 만들기

 

[MyService.java] 작성

 

- Service 를 상속 
   여기서 구현해야 하는 중요 메소드는

  onStartCommand() :   다른 컴포넌트에서 startService()를 호출하여서 서비스가 시작되면 이 메소드가 호출됩니다.  작업이 완료되었을 경우 stopSelf() 나 stopService() 를 호출하여 서비스를 종료하여야 합니다.  그렇지 않으면 무한 실행됩니다.

 

// 서비스 클래스를 구현하려면, Service 를 상속받는다
public class MyService extends Service {
    MediaPlayer mp; // 음악 재생을 위한 객체

    @Override
    public IBinder onBind(Intent intent) {
        // Service 객체와 (화면단 Activity 사이에서)
        // 통신(데이터를 주고받을) 때 사용하는 메서드
        // 데이터를 전달할 필요가 없으면 return null;
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        // 서비스에서 가장 먼저 호출됨(최초에 한번만)
        Log.d("test", "서비스의 onCreate");
        mp = MediaPlayer.create(this, R.raw.chacha);
        mp.setLooping(false); // 반복재생
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 서비스가 호출될 때마다 실행
        Log.d("test", "서비스의 onStartCommand");
        mp.start(); // 노래 시작
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 서비스가 종료될 때 실행
        mp.stop(); // 음악 종료
        Log.d("test", "서비스의 onDestroy");
    }
}

 

2. AndroidManifest.xml 에 Service를 등록한다

 

    <application> 안에 넣어주고 name 프러퍼티는 클래스 이름을 등록합니다

 

[AndroidManifest.xml] 작성

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    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="MyService"></service>
</application>

 

3. Service 를 시작하도록 호출한다

 

[액티비티] 작성

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="22dp"
        android:text="서비스"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="16dp"
        android:text="서비스 시작하기" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="30dp"
        android:text="서비스 종료하기" />

</RelativeLayout>

 

[MainActivity] 작성

 

인텐트를 사용하여 서비스를 가동 / 중단합니다.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 서비스 Service - 안드로이드의 4대 컴포넌트 중 하나
        //     화면이 없이 동작함
        // 보통 Activity 에서 호출되어 시작함

        // 1. 사용할 Service (*.java)를 만든다
        // 2. AndroidManifest.xml 에 Service를 등록한다
        // 3. Service 를 시작하도록 호출한다

        Button b1 = (Button) findViewById(R.id.button1);
        Button b2 = (Button) findViewById(R.id.button2);

        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // 서비스 시작하기
                Log.d("test", "액티비티-서비스 시작버튼클릭");
                Intent intent = new Intent(
                        getApplicationContext(),//현재제어권자
                        MyService.class); // 이동할 컴포넌트
                startService(intent); // 서비스 시작
            }
        });

        b2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // 서비스 종료하기
                Log.d("test", "액티비티-서비스 종료버튼클릭");
                Intent intent = new Intent(
                        getApplicationContext(),//현재제어권자
                        MyService.class); // 이동할 컴포넌트
                stopService(intent); // 서비스 종료
            }
        });
    } // end of onCreate
} // end of class

[배경음악 첨부]

 

 

[실행화면]

[서비스 시작하기] 버튼을 누르면 배경음악을 연주하는 MyService 서비스 객체의 onStartCommand 호출

[서비스 종료하기] 버튼을 누르면 onDestroy() 호출

 

반응형

댓글


Copyright ⓒ SmartWeb All rights reserved.