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

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

この記事では、AndroidアプリにおいてAlarmManager(アラームマネージャー)を使用してサービス(Service)を起動する方法を、サンプルコードとともにステップ形式で解説します。指定した時刻に処理を自動実行したい場合や、バックグラウンドでの定期処理を実装したい場合に役立つテクニックです。

実装の全体像

本チュートリアルで作成するアプリは、以下の構成になっています。

  • 「Start Service Alarm」ボタン:3秒後にサービスを起動するアラームをセット
  • 「Cancel Service」ボタン:セット済みのアラームをキャンセル

それでは、順番に実装していきましょう。

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

Android Studioを開き、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力し、Empty Activityテンプレートなどを選んでプロジェクトを生成してください。

ステップ2:レイアウトファイル(activity_main.xml)の編集

res/layout/activity_main.xml に以下のコードを記述します。サービスを起動するボタンとキャンセルするボタンの2つを配置したシンプルなレイアウトです。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16sp"
    android:orientation="vertical"
    android:gravity="center_horizontal">
    <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/btnStartService"
       android:text="Start Service Alarm"
       android:layout_marginTop="30dp"/>
    <Button
       android:id="@+id/btnStopService"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="10dp"
       android:text="Cancel Service"/>
</LinearLayout>

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

src/MainActivity.java に以下のコードを追加します。

ポイントは以下の通りです。

  • PendingIntent.getService():サービスを起動するためのPendingIntentを作成
  • Calendar:現在時刻から3秒後の時刻を算出
  • alarmManager.set():RTC_WAKEUPモードでアラームを登録(端末がスリープ状態でも起動)
  • alarmManager.cancel():登録済みのアラームを解除
package app.com.sample;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
    Button btnStart, btnStop;
    PendingIntent pendingIntent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       btnStart = findViewById(R.id.btnStartService);
       btnStop = findViewById(R.id.btnStopService);
       btnStart.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);
          pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
          AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
          Calendar calendar = Calendar.getInstance();
          calendar.setTimeInMillis(System.currentTimeMillis());
          calendar.add(Calendar.SECOND, 3);
          assert alarmManager != null;
          alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
          Toast.makeText(MainActivity.this, "Starting Service Alarm", Toast.LENGTH_LONG).show();
       }});
       btnStop.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
             AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
             assert alarmManager != null;
             alarmManager.cancel(pendingIntent);
             Toast.makeText(MainActivity.this, "Service Cancelled", Toast.LENGTH_LONG).show();
          }
       });
    }
}

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

次に、新しいJavaクラス「MyAlarmService.java」を作成し、以下のコードを記述します。各ライフサイクルメソッド(onCreate / onBind / onStart / onUnbind / onDestroy)が呼ばれたタイミングをToastで確認できるようにしています。

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyAlarmService extends Service {
    @Override
    public void onCreate() {
       Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
       Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
       return null;
    }
    @Override
    public void onDestroy() {
       super.onDestroy();
       Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onStart(Intent intent, int startId) {
       super.onStart(intent, startId);
       Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
    }
    @Override
    public boolean onUnbind(Intent intent) {
       Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
       return super.onUnbind(intent);
    }
}

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

最後に、androidManifest.xml にサービスを宣言します。<service>タグでMyAlarmServiceを登録しないと、アプリはサービスを起動できずクラッシュするので注意してください。

<?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">
       <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=".MyAlarmService" />
    </application>
</manifest>

アプリの実行と動作確認

それではアプリを実行してみましょう。実機のAndroidスマートフォンをPCに接続している前提で進めます。Android Studioからプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。デバイスを選択して実行すると、スマートフォンに以下のような画面が表示されます。

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


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


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


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

補足:最新のAndroidバージョンでの注意点

このサンプルは古いAndroidバージョン向けの書き方のため、最近の環境で動かす場合は以下の点に注意が必要です。

  • Android 12(API 31)以降では、PendingIntentの作成時にPendingIntent.FLAG_IMMUTABLEまたはPendingIntent.FLAG_MUTABLEの指定が必須になりました。
  • Android 8.0(API 26)以降でバックグラウンド制限に対応するには、startForegroundService()の利用やJobScheduler / WorkManagerへの移行を検討しましょう。

これらの点に配慮することで、より安定したアラーム・定期処理の実装が可能になります。

  1. Androidアプリで端末起動時にサービスを自動開始する方法【コード例付きで解説】

    はじめにAndroidアプリの中には、端末が再起動された後もバックグラウンド処理を継続したいケースがあります。本記事では、BroadcastReceiverとBOOT_COMPLETEDアクションを組み合わせて、端末の起動完了時にサービスを自動的に開始する方法を、実際のコード例とともにステップごとに解説します。この仕組みを実現するには、まずシステムから「起動完了」のブロードキャストを受け取るレシーバーを用意し、その中でActivityやServiceを起動します。以下の手順に従って実装していきましょう。Step 1:新規プロジェクトを作成するAndroid Studioを開き、「File」→「

  2. 【Android】JavaMail APIを使用してメールを送信する方法を解説

    はじめに この記事では、JavaMail APIを使用してAndroidアプリからメールを送信する方法を、ステップごとに詳しく解説します。画面に入力した宛先・件名・本文をもとに、GmailのSMTPサーバー経由でメールを送信するシンプルなサンプルアプリを作成していきます。 手順1:新規プロジェクトの作成 Android Studioを起動し、「File」→「New Project」を選択して、必要事項を入力して新しいプロジェクトを作成します。 手順2:レイアウトファイル(activity_main.xml)の作成 res/layout/activity_main.xmlに以下のコードを記述しま