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

안드로이드 서비스에서 Foreground(전경) 시작 구현하는 방법

안드로이드 서비스란?

본격적인 예제에 들어가기 전에, 안드로이드에서 서비스(Service)가 무엇인지 먼저 이해할 필요가 있습니다. 서비스는 UI와 상호작용하지 않은 채 백그라운드에서 작업을 수행하는 컴포넌트로, 액티비티가 종료된 이후에도 계속해서 동작할 수 있습니다.

이 글에서는 서비스를 Foreground(전경) 모드로 시작하는 방법을 단계별 예제와 함께 자세히 설명하겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project를 선택하고, 새 프로젝트를 만들기 위해 필요한 모든 세부 정보를 입력하여 프로젝트를 생성합니다.

2단계: 레이아웃 파일 작성 (res/layout/activity_main.xml)

아래 코드를 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를 클릭하면 startForeground()가 호출되도록 구성할 것입니다.

3단계: 메인 액티비티 작성 (src/MainActivity.java)

아래 코드를 MainActivity.java에 추가합니다.

package com.example.andy.myapplication;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView text = findViewById(R.id.text);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMyServiceRunning(service.class)) {
                    text.setText("Stoped");
                    stopService(new Intent(MainActivity.this, service.class));
                } else {
                    text.setText("Started");
                    startService(new Intent(MainActivity.this, service.class));
                }
            }
        });
    }
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

위 코드는 서비스를 시작하고 중지하는 역할을 합니다. Intent를 사용해 컨텍스트(Context)와 서비스 클래스를 전달하는 방식입니다.

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

패키지 폴더 내에 service.class라는 이름으로 서비스 클래스를 생성하고 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class service extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @TargetApi(Build.VERSION_CODES.O)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Notification Service started by user.", Toast.LENGTH_LONG).show();
        String NOTIFICATION_CHANNEL_ID = "com.example.andy.myapplication";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification notification = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("My Awesome App")
        .setContentIntent(pendingIntent).build();
        startForeground(1337, notification);
        return START_STICKY;
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        Toast.makeText(this, "Notification Service destroyed by user.", Toast.LENGTH_LONG).show();
    }
}

알림 채널과 알림 빌더 설정

위 코드에서는 다음과 같이 알림 채널(Notification Channel)과 알림 빌더(Notification Builder)를 활용했습니다.

String NOTIFICATION_CHANNEL_ID = "com.example.andy.myapplication";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName,  NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this,NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Awesome App")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);

Foreground 시작 및 중지 코드

Foreground 모드를 시작하고 중지하려면 아래 코드를 사용합니다.

startForeground(1337, notification);
stopForeground(true);

참고: 안드로이드 8.0(API 26) 이상에서는 Foreground 서비스를 실행하기 위해 반드시 알림 채널을 생성해야 하며, 그렇지 않으면 startForeground() 호출 시 오류가 발생할 수 있습니다.

4단계: 매니페스트 파일 수정 (manifest.xml)

아래 코드를 AndroidManifest.xml에 추가합니다. 특히 서비스 컴포넌트를 반드시 등록해야 한다는 점에 유의하세요.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.andy.myapplication">
    <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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 모바일 기기를 선택하면 해당 기기에서 앱이 실행됩니다.

안드로이드 서비스에서 Foreground(전경) 시작 구현하는 방법

위 화면은 앱의 초기 화면입니다. 여기서 TextView를 클릭하면 아래와 같이 알림(Notification) 서비스가 시작됩니다.

안드로이드 서비스에서 Foreground(전경) 시작 구현하는 방법

위 결과에서 서비스가 시작된 것을 확인할 수 있습니다. 이후 다시 TextView를 클릭하면 아래와 같이 알림 서비스가 중지됩니다.

안드로이드 서비스에서 Foreground(전경) 시작 구현하는 방법

마무리

이렇게 안드로이드에서 서비스를 Foreground 모드로 시작하는 전체 과정을 살펴보았습니다. 핵심은 알림 채널 생성 → 알림 객체 빌드 → startForeground() 호출의 순서이며, 서비스 종료 시에는 stopForeground(true)를 호출하여 알림과 함께 Foreground 상태를 해제하는 것입니다. 음악 재생, 위치 추적 등 지속적인 백그라운드 작업이 필요한 앱을 개발할 때 이 패턴을 유용하게 활용할 수 있습니다.