Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidでサービスが実行中かどうかを確認する方法【サンプルコード付きで解説】

Androidのサービスとは?

本題に入る前に、Androidにおける「サービス(Service)」について簡単におさらいしておきましょう。サービスとは、UI(ユーザーインターフェース)と直接やり取りすることなく、バックグラウンドで処理を継続的に実行するためのコンポーネントです。最大の特徴は、アクティビティが破棄された後も動作を続けられるという点にあります。

この記事では、「Androidで特定のサービスが現在実行中かどうかを確認する方法」を、実際のサンプルコードとともにステップごとに解説します。

手順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を1つ配置しています。ユーザーがこのテキストをタップすると、サービスの開始と停止が交互に切り替わる仕組みになっています。

手順3:MainActivity.java を実装する

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)

補足: ActivityManager.getRunningServices() は API レベル26(Android 8.0)以降で非推奨(deprecated)となっており、取得できるのは自アプリのサービス情報のみです。最新のAndroidをターゲットに開発する場合は、サービス側に状態フラグを持たせて管理する方法や、JobScheduler・WorkManagerといった代替手段の活用も検討するとよいでしょう。

手順4:AndroidManifest.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">
    <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スマートフォンがPCに接続されているものとして説明を進めます。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。デバイス選択画面で接続したモバイル端末を選ぶと、端末に以下のような初期画面が表示されます。

Androidでサービスが実行中かどうかを確認する方法【サンプルコード付きで解説】

初期画面が表示されたら、TextViewをタップしてみましょう。サービスが起動し、以下のようにトーストメッセージが表示されます。

Androidでサービスが実行中かどうかを確認する方法【サンプルコード付きで解説】

サービスが起動した状態でもう一度TextViewをタップすると、今度はサービスが停止します。

Androidでサービスが実行中かどうかを確認する方法【サンプルコード付きで解説】

  1. Androidでバッテリーの劣化状態を確認する方法|隠しコードとアプリ活用術

    スマートフォンからリモコンまで、私たちの身の回りの多くの機器はバッテリーで動作しています。バッテリーは今や現代生活に欠かせない存在です。特にモバイル端末に搭載されているリチウムイオンバッテリーは、長期間の使用により必ず劣化していきます。劣化の兆候としては、充電時間の長期化や不安定化、充電容量の低下、発熱、急激なバッテリー消耗、バッテリーの膨張などが挙げられます。バッテリーとデバイス本体を長持ちさせるためには、定期的にバッテリーの状態を確認し、適切なメンテナンスを行うことが重要です。この記事では、Androidでバッテリーの状態を確認する方法を詳しく解説します。 Androidでバッテリーの状

  2. AndroidでGear VRサービスを無効にする7つの方法|バッテリー消費の悩みを解決

    古いモデルのSamsungスマートフォンをお使いの方なら、「Samsung Gear VRサービス」という項目を目にしたことがあるかもしれません。そもそもGear VRサービスとは何かというと、簡単に言えばVRヘッドセットを使用するためのシステムサービスです。しかし、このサービスには大きな問題点があります。それはバッテリー消費が激しいということです。 さらに厄介なことに、ユーザーが操作していないのにサービスが勝手に起動し、電力消費を増やしてしまうケースもあります。本記事では、Gear VRサービスの概要から、バックグラウンドでの動作を止める具体的な方法まで、詳しく解説していきます。 Gear