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

【Android】アクティビティとサービス間の通信を実現する方法を徹底解説

はじめに

このチュートリアルでは、Androidアプリにおいてアクティビティ(Activity)サービス(Service)の間で通信を行う方法を解説します。「Start Service」「Stop Service」の2つのボタンを持つシンプルなアプリを作成し、ボタンの操作でサービスを開始・停止しながら、そのライフサイクルの流れを確認していきましょう。

ステップ1:新規プロジェクトの作成

まず、Android Studioを起動し、メニューから「File」⇒「New Project」を選択します。必要な情報をすべて入力して、新しいプロジェクトを作成してください。

ステップ2:レイアウトファイル(res/layout/activity_main.xml)の実装

次に、サービスの開始用と停止用の2つのボタンを配置したレイアウトを定義します。以下のコードを activity_main.xml に追加してください。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">
    <Button
       android:id="@+id/buttonStart"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="74dp"
       android:text="Start Service" />
    <Button
       android:id="@+id/buttonStop"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerHorizontal="true"
       android:layout_centerVertical="true"
       android:text="Stop Service" />
</RelativeLayout>

ステップ3:MainActivity.javaの実装

続いて、ボタンのクリックイベントを処理するアクティビティを実装します。「Start Service」ボタンが押されたときには startService() を呼び出してサービスを起動し、「Stop Service」ボタンが押されたときには stopService() を呼び出してサービスを停止します。

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button buttonStart, buttonStop;
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       buttonStart = findViewById(R.id.buttonStart);
       buttonStop = findViewById(R.id.buttonStop);
       buttonStart.setOnClickListener(this);
       buttonStop.setOnClickListener(this);
    }
    public void onClick(View src) {
       switch (src.getId()) {
          case R.id.buttonStart:
            startService(new Intent(this, MyService.class));
          break;
          case R.id.buttonStop:
            stopService(new Intent(this, MyService.class));
          break;
       }
    }
}

ステップ4:サービスクラス(MyService)の作成

新しくServiceクラス(MyService)を作成し、以下のコードを記述します。このサービスは MediaPlayer を使って楽曲を再生するとともに、onCreate()・onStart()・onDestroy() の各タイミングでトーストを表示することで、状態の変化をユーザーに通知します。

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service {
    MediaPlayer myPlayer;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
       return null;
    }
    @Override
    public void onCreate() {
       Toast.makeText(this, "Service Created",
       Toast.LENGTH_LONG).show();
       myPlayer = MediaPlayer.create(this, R.raw.song);
       myPlayer.setLooping(false);
    }
    @Override
    public void onStart(Intent intent, int startId) {
       Toast.makeText(this, "Service Started",
       Toast.LENGTH_LONG).show();
       myPlayer.start();
    }
    @Override
    public void onDestroy() {
       Toast.makeText(this, "Service Stopped",
       Toast.LENGTH_LONG).show();
       myPlayer.stop();
    }
}

補足: サンプル内で使用されている onStart(Intent, int) は現在非推奨(Deprecated)となっています。最新の環境で開発する場合は、代わりに onStartCommand(Intent, int, int) をオーバーライドするのが推奨されています。また、音楽ファイル(R.raw.song)を参照しているため、あらかじめ res/raw フォルダに音声ファイルを配置しておく必要がありますのでご注意ください。

ステップ5:AndroidManifest.xmlへのサービス登録

サービスはマニフェストファイルへの宣言が必要です。applicationタグ内に service 要素を追加しましょう。

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <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">
       <service
          android:name=".MyService"
          android:enabled="true"
          android:exported="true"></service>
       <activity android:name=".MainActivity">
          <intent-filter>
            <action
               android:name="android.intent.action.MAIN" />
            <category
               android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
       </activity>
    </application>
</manifest>

アプリの実行と動作確認

それでは、アプリケーションを実行してみましょう。ここでは、実機のAndroid端末がパソコンに接続されているものとして説明します。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーにある「Run」アイコンをクリックします。表示された選択肢から接続済みのモバイルデバイスを選ぶと、端末にアプリの画面が表示されます。

【Android】アクティビティとサービス間の通信を実現する方法を徹底解説

「Start Service」ボタンをタップすると、「Service Created」「Service Started」のトーストが順番に表示され、音楽の再生が始まります。逆に「Stop Service」ボタンをタップすると「Service Stopped」と表示され、再生が停止します。

【Android】アクティビティとサービス間の通信を実現する方法を徹底解説

まとめ

本記事では、startService() / stopService() を使ってアクティビティからサービスを制御する基本的な方法を紹介しました。サービスのライフサイクルメソッド内で処理を実装すれば、バックグラウンドでの音楽再生なども実現できます。より高度な双方向の連携が必要な場合は、BinderやMessenger、AIDLを使ったバインド型サービスの活用も検討してみてください。

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

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

  2. Androidでアクティビティからフラグメントへ変数を渡す方法を徹底解説

    はじめに この記事では、Androidアプリ開発においてアクティビティ(Activity)からフラグメント(Fragment)へ変数を渡す方法を、実際のコード例とともに段階的に解説します。 アクティビティからフラグメントへのデータ受け渡しには、Bundleを使うのが基本です。アクティビティ側でsetArguments()メソッドによりBundleをフラグメントにセットし、フラグメント側でgetArguments()メソッドを使って値を取り出します。 手順1:新規プロジェクトを作成する Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Projec