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

AndroidサービスにSTART_STICKYを実装する方法を徹底解説

AndroidにおけるService(サービス)とは?

実装方法を解説する前に、まずAndroidの「Service」について簡単におさらいしましょう。Serviceは、UI(ユーザーインターフェース)と直接やり取りすることなくバックグラウンドで処理を実行するためのコンポーネントです。Activityが破棄された後も処理を続けることができるのが大きな特徴です。

START_STICKYとは何か?

START_STICKYは、onStartCommand()メソッドの戻り値として指定できる定数の一つです。この値を返すようにサービスを実装すると、Activityがフォアグラウンドに存在しなくてもサービスはバックグラウンドで動作し続けます。さらに重要なのは、メモリ不足などの理由でシステムがサービスを強制終了した場合でも、ユーザーの操作なしに自動的にサービスが再起動されるという点です。

なお、類似の定数には強制終了後に再起動しないSTART_NOT_STICKYや、直前のIntentを再送して再起動するSTART_REDELIVER_INTENTがあります。用途に応じて使い分けましょう。

本記事では、サンプルコードを通じてサービスにSTART_STICKYを実装する具体的な手順を紹介します。

START_STICKYを実装する手順

ステップ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をタップするたびに、サービスの開始と停止が切り替わる仕組みです。

ステップ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にコンテキストとサービスクラスを渡すことでサービスの開始・停止を行っています。また、isMyServiceRunning()メソッドでサービスの稼働状態を判定し、状態に応じて表示テキストを切り替えています。

サービスクラスを作成する

次に、パッケージフォルダ内にservice.javaというサービスクラスを作成し、以下のコードを追加します。

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.util.Log;
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();
        Log.d("Tutorialspoint.com","Services is working background");
        return START_STICKY;
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Notification Service destroyed by user.", Toast.LENGTH_LONG).show();
    }
}

ポイントはonStartCommand()内でSTART_STICKYを返している箇所です。これにより、システムによる強制終了後もサービスが自動的に再起動されます。アプリを実行すると、以下のように端末側でサービスの情報を確認できます。

AndroidサービスにSTART_STICKYを実装する方法を徹底解説

ステップ4:manifest.xmlにコードを追加する

最後に、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端末をパソコンに接続しているものとします。Android Studioでプロジェクト内の任意のアクティビティファイルを開き、ツールバーのRunアイコンをクリックします。接続したモバイルデバイスを選択すると、端末に以下のような初期画面が表示されます。

AndroidサービスにSTART_STICKYを実装する方法を徹底解説

上記が初期画面です。TextViewをタップすると、以下のように通知サービスが起動します。

AndroidサービスにSTART_STICKYを実装する方法を徹底解説

サービスが起動したら、もう一度TextViewをタップしてみてください。以下のように通知サービスが停止します。

AndroidサービスにSTART_STICKYを実装する方法を徹底解説

  1. Androidで線を引く方法とは?Canvasを使った描画手順をステップ解説

    この記事では、Androidアプリで線を描画する方法を、実際のサンプルコードとともにステップごとに解説します。BitmapとCanvasを組み合わせれば、ボタンをタップしたタイミングで画面上に線を簡単に描くことができます。 作成するアプリの概要 今回作成するのは、画面下部の「Draw Line」ボタンを押すと、中央のImageView上に赤い横線が表示されるシンプルなアプリです。レイアウトの定義、MainActivityへの処理の記述、マニフェストファイルの確認という流れで進めていきます。 ステップ1:新規プロジェクトを作成する Android Studioを起動し、「File」→「New P

  2. 【Android開発】AlarmManagerを使ってサービスを起動する方法を徹底解説

    この記事では、AndroidアプリにおいてAlarmManager(アラームマネージャー)を使用してサービス(Service)を起動する方法を、サンプルコードとともにステップ形式で解説します。指定した時刻に処理を自動実行したい場合や、バックグラウンドでの定期処理を実装したい場合に役立つテクニックです。実装の全体像本チュートリアルで作成するアプリは、以下の構成になっています。「Start Service Alarm」ボタン:3秒後にサービスを起動するアラームをセット「Cancel Service」ボタン:セット済みのアラームをキャンセルそれでは、順番に実装していきましょう。ステップ1:新規プロジ