Android IntentService란 무엇인가?
본격적인 예제를 살펴보기에 앞서, Android에서 IntentService가 어떤 역할을 하는지 먼저 이해할 필요가 있습니다. IntentService는 백그라운드 작업을 비동기적으로 처리하는 서비스 컴포넌트입니다. 액티비티에서 startService()를 호출하더라도 요청마다 새 인스턴스를 생성하지 않으며, 모든 요청은 단일 워커 스레드에서 순차적으로 처리됩니다. 작업이 완료되면 서비스는 자동으로 종료되고, 필요하다면 stopSelf() 메서드를 호출해 직접 중단시킬 수도 있습니다.
이 글에서는 IntentService에서 인텐트(Intent)를 공유하는 방법을 단계별로 알아보겠습니다.
1단계: 새 프로젝트 생성
Android Studio를 실행한 후 File ⇒ New Project를 선택하고, 프로젝트 생성에 필요한 세부 정보를 모두 입력하여 새 프로젝트를 만듭니다.
2단계: 레이아웃 파일(activity_main.xml) 작성
res/layout/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를 클릭하면 Android OS의 기본 공유 다이얼로그가 열리도록 구현할 것입니다.
3단계: MainActivity.java 코드 추가
src/MainActivity.java 파일에 다음 코드를 작성합니다.
package com.example.andy.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, service.class));
}
});
}
}
서비스 클래스(service.java) 생성
service.class라는 이름의 클래스 파일을 만들고 아래 코드를 추가합니다.
package com.example.andy.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
public class service extends IntentService {
public static volatile boolean shouldStop = false;
public service() {
super(service.class.getSimpleName());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Tutorialspoint.com");
startActivity(Intent.createChooser(sharingIntent, "Sharing"));
if(shouldStop) {
stopSelf();
return;
}
}
}
여기서 핵심은 onHandleIntent() 내부에서 ACTION_SEND 타입의 공유 인텐트를 생성하고, Intent.createChooser()를 통해 시스템 기본 공유 다이얼로그를 띄우는 부분입니다. 서비스를 중단하려면 서비스 클래스 내에서 다음 코드를 사용합니다.
stopSelf();
4단계: 매니페스트(Manifest.xml) 설정
manifest.xml 파일에 아래 코드를 추가합니다. 서비스 컴포넌트를 반드시 매니페스트에 등록해야 정상적으로 동작합니다.
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.WAKE_LOCK"/>
<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 모바일 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 실행(Run) 아이콘을 클릭하고, 옵션 목록에서 본인의 모바일 기기를 선택하세요. 그러면 모바일 기기에 앱의 기본 화면이 표시됩니다.

위 결과는 애플리케이션의 기본 화면입니다. 사용자가 TextView를 클릭하면 모바일 OS의 기본 공유 다이얼로그가 아래와 같이 나타납니다.

참고: IntentService는 지원이 중단되었습니다
IntentService는 API 레벨 30(Android 11)부터 공식적으로 지원 중단(deprecated)되었다는 점을 유의해야 합니다. 신규 프로젝트에서는 WorkManager 또는 JobIntentService를 사용하는 것이 권장됩니다. 다만, 레거시 코드 유지보수나 학습 목적이라면 위 예제처럼 IntentService를 활용하는 방법도 여전히 유효합니다.