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

Android IntentService에서 UI를 업데이트하는 방법


IntentService란 무엇일까요?

본격적인 예제에 들어가기 전에, Android에서 IntentService가 무엇인지 먼저 이해할 필요가 있습니다. IntentService는 백그라운드 작업을 비동기적으로 처리하는 특수한 형태의 Service입니다. 액티비티에서 startService()를 호출하더라도 요청마다 새로운 인스턴스를 생성하지 않고, 모든 요청은 단일 워커 스레드에서 순차적으로 실행됩니다.

또한 IntentService는 onHandleIntent() 내의 작업이 모두 끝나면 자동으로 스스로를 종료(self-stop)하기 때문에, 개발자가 별도로 서비스를 멈추지 않아도 됩니다. 물론 필요하다면 stopSelf()를 호출하여 직접 종료할 수도 있습니다.

핵심 문제는 IntentService가 메인(UI) 스레드가 아닌 별도의 스레드에서 동작한다는 점입니다. 따라서 서비스 내부에서 직접 TextView 등 UI 요소를 변경할 수 없으며, 이번 글에서는 BroadcastReceiver를 활용해 IntentService에서 UI를 안전하게 업데이트하는 방법을 다룹니다.

전체 구현 예제

이번 예제는 IntentService에서 데이터를 받아 화면의 TextView를 갱신하는 과정을 단계별로 보여줍니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project를 선택하고, 프로젝트 생성에 필요한 정보를 모두 입력하여 새 프로젝트를 만듭니다.

2단계 — 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 하나가 배치되어 있습니다. 사용자가 IntentService로부터 데이터를 전달받으면 이 TextView의 텍스트가 갱신됩니다.

3단계 — src/MainActivity.java 작성

메인 액티비티에 다음 코드를 추가합니다.

package com.example.andy.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s1 = intent.getStringExtra("DATAPASSED");
text.setText(s1);
}
};

@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.andy.myapplication");
registerReceiver(broadcastReceiver, intentFilter);
}

@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));
}
});
}

@Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}
}

위 코드에서는 서비스 클래스를 시작하고, 동적으로 등록된 브로드캐스트 리시버(BroadcastReceiver)를 통해 결과를 수신하도록 구성했습니다. 핵심 부분만 정리하면 다음과 같습니다.

@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.andy.myapplication");
registerReceiver(broadcastReceiver, intentFilter);
}

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s1 = intent.getStringExtra("DATAPASSED");
text.setText(s1);
}
};

@Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}

여기서 주목할 점은 리시버를 onStart()에서 등록하고 onStop()에서 해제한다는 것입니다. 이렇게 하면 액티비티가 화면에 보이는 동안에만 브로드캐스트를 수신하므로, 존재하지 않는 UI를 참조하는 오류(메모리 누수)를 예방할 수 있습니다.

서비스 클래스(service.class) 작성

이제 IntentService를 상속받는 서비스 클래스를 만들고 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
public class service extends IntentService {
public service() {
super(service.class.getSimpleName());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
Intent intent1 = new Intent();
intent1.setAction("com.example.andy.myapplication");
intent1.putExtra("DATAPASSED", "Tutorialspoint.com");
sendBroadcast(intent1);
}
}

onHandleIntent() 내부에서 액션 이름과 함께 전달할 데이터(DATAPASSED)를 담은 인텐트를 생성한 뒤 sendBroadcast()로 전송합니다. 이 브로드캐스트를 메인 액티비티의 리시버가 받으면, 메인 스레드에서 안전하게 TextView의 내용이 갱신됩니다.

4단계 — AndroidManifest.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>

서비스는 반드시 매니페스트에 <service> 태그로 선언해야 정상적으로 동작합니다. 또한 백그라운드 작업 중 기기가 잠들지 않도록 WAKE_LOCK 권한을 함께 추가했습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요.

Android IntentService에서 UI를 업데이트하는 방법

앱이 실행되면 위와 같은 기본 화면이 나타납니다. 화면의 "Start Service" 텍스트를 클릭하면 서비스가 시작되고, IntentService에서 전송한 브로드캐스트를 통해 TextView가 아래와 같이 갱신됩니다.

Android IntentService에서 UI를 업데이트하는 방법

참고: 최신 Android 개발 환경이라면?

IntentServiceAPI 레벨 30부터 공식적으로 지원 중단(deprecated)되었습니다. 최신 프로젝트에서는 WorkManager나 Kotlin Coroutines(코루틴) 기반의 백그라운드 처리 방식을 사용하는 것이 권장됩니다. 다만 브로드캐스트를 통한 UI 갱신 패턴 자체는 지금도 그대로 유효하므로, 개념 학습 차원에서 충분히 유용한 예제입니다.