Service
Service는 "백그라운드에서 오래 실행되는 작업을 수행할 수 있는 애플리케이션 구성 요소이며 사용자 인터페이스를 제공하지 않습니다. 다른 애플리케이션 구성 요소가 서비스를 시작할 수 있으며, 이는 사용자가 다른 애플리케이션으로 전환하더라도 백그라운드에서 계속해서 실행됩니다. 이외에도, 구성 요소를 서비스에 바인딩하여 서비스와 상호작용할 수 있으며, 심지어는 프로세스 간 통신(IPC)도 수행할 수 있습니다. 예를 들어 한 서비스는 네트워크 트랜잭션을 처리하고, 음악을 재생하고 파일 I/O를 수행하거나 콘텐츠 제공자와 상호작용할 수 있으며 이 모든 것을 백그라운드에서 수행할 수 있습니다."라고 안드로이드 공식 문서에 명시되어 있습니다.
Service Callback method
onStartCommand()
: 다른 구성 요소가 서비스를 시작하도록 요청하는 경우 호출됩니다. startService()를 사용합니다.
이 메서드가 실행되면 서비스가 시작되고 백그라운드에서 무한히 실행될 수 있습니다.
onBind()
: 다른 구성 요소가 해당 서비스에 바인딩되고자 하는 경우 이 메서드가 호출됩니다. 항상 구현해야 하는 메서드이지만 바인딩을 허용하지 않으려면 null을 반환해야 합니다.
onCreate()
: 서비스가 처음 생성되었을 때(onStartCommand() 또는 onBind()를 호출 하기 전) 이 메서드가 호출됩니다.
onDestroy()
: 서비스를 더 이상 사용하지 않고 소멸시킬 때 호출되고, 각종 리소스를 정리합니다.
서비스가 수신하는 마지막 호출입니다.
Service Lifecycle
왼쪽 다이어그램은 서비스가 startService()로 생성된 경우의 수명주기를 나타내며, 오른쪽 다이어그램은 서비스가 bindService()로 생성된 경우의 수명주기입니다.
그림에서는 2가지로 나누어서 나타냈지만 모든 서비스는 클라이언트와 바인딩되도록 허용할 수 있다는 점을 명심해야 합니다. 액티비티와 마찬가지로 onCreate()에서 초기 설정, onDestroy()에서 남은 리소스들을 릴리스합니다.
Service 음악 재생 예제
AndroidManifest.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service">
<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/Theme.Service">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
// Service 선언
<service android:name="MyService"></service>
</application>
</manifest>
|
cs |
MainActivity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package com.example.service;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_startService;
Button btn_stopService;
btn_startService = findViewById(R.id.btn_startService);
btn_stopService = findViewById(R.id.btn_stopService);
// 서비스 시작하기
btn_startService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("test", "startService");
Intent intent = new Intent(
getApplicationContext(),
MyService.class);
startService(intent);
}
});
// 서비스 정지하기
btn_stopService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("test", "stopService");
Intent intent = new Intent(
getApplicationContext(),
MyService.class);
stopService(intent);
}
});
}
}
|
cs |
MyService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class MyService extends Service {
// 음악 재생을 위한 객체
MediaPlayer mp;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
// 서비스에서 가장 먼저 호출됨(최초에 한번만)
@Override
public void onCreate() {
super.onCreate();
Log.d("test", "Service onCreate");
mp = MediaPlayer.create(this, R.raw.song);
mp.setLooping(true); // 반복재생
}
// onStartCommand : 서비스가 호출될 때마다 실행
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("test", "Service onStartCommand");
// 노래 시작
mp.start();
return super.onStartCommand(intent, flags, startId);
}
// 서비스가 종료될 때 실행
@Override
public void onDestroy() {
super.onDestroy();
// 음악 종료
mp.stop();
Log.d("test", "Service onDestroy");
}
}
|
cs |
main_activity.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Service"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.433" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Service 시작"
android:id="@+id/btn_startService"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.531" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Service 정지"
android:id="@+id/btn_stopService"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.619" />
</androidx.constraintlayout.widget.ConstraintLayout>
|
cs |
실행 화면
Service 시작 -> Service 정지
참고 문서
- developer.android.com/guide/components/services?hl=ko
소스 코드
'안드로이드' 카테고리의 다른 글
[안드로이드] ANR(Application Not Responding) (0) | 2021.01.19 |
---|---|
[안드로이드] Glide 라이브러리 (0) | 2021.01.18 |
[안드로이드] Fragment Lifecycle (0) | 2021.01.12 |
[안드로이드] Activity Lifecycle(활동 수명 주기) (0) | 2021.01.06 |
[안드로이드] Android Jetpack (0) | 2020.12.31 |