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

Android에서 서비스(Service)가 실행 중인지 확인하는 방법

예제를 살펴보기에 앞서, 안드로이드에서 서비스(Service)가 무엇인지 간단히 짚고 넘어가겠습니다. 서비스는 UI와 상호작용하지 않은 채 백그라운드에서 작업을 수행하는 컴포넌트로, 액티비티가 종료된 후에도 계속해서 동작할 수 있습니다.

이 글에서는 안드로이드에서 특정 서비스가 현재 실행 중인지 확인하는 방법을 단계별 예제와 함께 알아보겠습니다.

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를 배치했습니다. 사용자가 이 TextView를 클릭하면 서비스를 시작하거나 중지하도록 구현할 것입니다.

3단계 — MainActivity 작성

src/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.java라는 이름으로 서비스 클래스를 생성하고 다음 코드를 추가합니다.

package com.example.andy.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
    }
}

서비스 실행 여부 확인하기

서비스가 현재 작동 중인지 확인하려면 다음 코드를 사용합니다.

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;

이 메서드를 호출할 때는 아래와 같이 작성합니다.

isMyServiceRunning(service.class)

참고: getRunningServices()는 API 26(오레오)부터 공식적으로 지원 중단(deprecated)되었으며, 현재는 자신의 앱에서 실행 중인 서비스 정보만 반환됩니다. 따라서 자기 앱의 서비스 상태를 확인하는 용도로는 여전히 유효하지만, 다른 앱의 서비스 목록을 조회할 수는 없습니다.

4단계 — 매니페스트 등록

manifest.xml에 아래 코드를 추가합니다. 반드시 <service> 태그로 서비스를 선언해야 정상적으로 동작합니다.

<?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 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요.

Android에서 서비스(Service)가 실행 중인지 확인하는 방법

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

Android에서 서비스(Service)가 실행 중인지 확인하는 방법

서비스가 시작된 상태에서 다시 TextView를 클릭하면, 아래와 같이 서비스가 중지됩니다.

Android에서 서비스(Service)가 실행 중인지 확인하는 방법

이처럼 ActivityManagergetRunningServices() 메서드를 활용하면 특정 서비스가 현재 실행 중인지 손쉽게 확인할 수 있으며, 이를 바탕으로 서비스의 시작과 중지를 유연하게 제어할 수 있습니다.