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

Androidでリマインダー通知を実装する方法を初心者向けに解説

この記事では、Androidアプリで毎日決まった時刻に通知を表示する「リマインダー通知」の実装方法を、サンプルコードとともにステップごとに解説します。AlarmManagerとServiceを組み合わせることで、アプリが起動していなくても指定時刻に通知を届けられる仕組みを作れます。

全体の仕組み

本サンプルでは、以下の流れでリマインダー通知を実現します。

1. 画面上のボタンをタップすると、翌日の午前0時に通知を発行するようAlarmManagerに登録します。
2. 指定時刻になるとシステムがNotifyService(Serviceクラス)を起動します。
3. Service内でNotificationCompat.Builderを使って通知を生成・表示します。

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

Android Studioを開き、File → New Projectから新しいプロジェクトを作成します。必要な項目(プロジェクト名、パッケージ名、保存先など)を入力してプロジェクトを完成させてください。

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

res/layout/activity_main.xml に以下のコードを追加します。画面中央に「create notification」ボタンを配置するシンプルなレイアウトです。

<?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"
    android:padding="16dp"
    tools:context=".MainActivity">

    <Button
        android:onClick="createNotification"
        android:text="create notification"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

ボタンの android:onClick 属性に「createNotification」を指定することで、タップ時にMainActivityの同名メソッドが呼び出されるようになります。

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

src/MainActivity.java に以下のコードを記述します。ボタンが押されたら、翌日午前0時を起点として24時間ごとに繰り返し通知を発行するようAlarmManagerへ登録しています。

package app.tutorialspoint.com.notifyme;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void createNotification(View view) {
        Intent myIntent = new Intent(getApplicationContext(), NotifyService.class);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);
        calendar.add(Calendar.DAY_OF_MONTH, 1); // 翌日の午前0時に設定

        // 24時間ごとに繰り返すアラームを登録
        alarmManager.setRepeating(
                AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                1000 * 60 * 60 * 24,
                pendingIntent);
    }
}

ポイントは setRepeating() メソッドです。第2引数に初回の発火時刻、第3引数に繰り返し間隔(ここでは24時間=86,400,000ミリ秒)を渡すことで、毎日自動的に通知が送られるようになります。

ステップ4:NotifyService.java の作成

src/NotifyService.java を新規作成し、以下のコードを記述します。このServiceが実際に通知を生成して表示する役割を担います。

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

public class NotifyService extends Service {

    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";

    public NotifyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 通知タップ時にMainActivityを開くためのPendingIntent
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        notificationIntent.putExtra("fromNotification", true);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(getApplicationContext(), default_notification_channel_id);
        mBuilder.setContentTitle("My Notification");
        mBuilder.setContentIntent(pendingIntent);
        mBuilder.setContentText("Notification Listener Service Example");
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);

        // Android 8.0(API 26)以降は通知チャンネルが必須
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new
                    NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());

        throw new UnsupportedOperationException("Not yet implemented");
    }
}

注意点:Android 8.0(Oreo / API レベル26)以降では、通知を表示するために必ず通知チャンネル(NotificationChannel)を作成する必要があります。上記コードではBuild.VERSION.SDK_INTでOSバージョンを判定し、該当する場合のみチャンネルを生成しています。

ステップ5:AndroidManifest.xml への権限とServiceの宣言

最後に、AndroidManifest.xml に以下のコードを記述します。VIBRATE権限(バイブレーション用)、RECEIVE_BOOT_COMPLETED権限(端末再起動後もアラームを維持する場合に使用)を追加し、NotifyServiceを宣言します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.notifyme">

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <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=".NotifyService"
            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スマートフォンをPCに接続している前提で説明します。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーのRun(実行)アイコンをクリックしてください。デバイス選択ダイアログが表示されたら、接続したスマートフォンを選択します。

アプリが起動したら「create notification」ボタンをタップしてください。これでアラームが登録され、翌日の午前0時に通知が表示されるようになります。

Androidでリマインダー通知を実装する方法を初心者向けに解説

まとめ

本記事では、AlarmManagerによる定期アラームの登録、Serviceでの通知生成、Android 8.0以降で必須となる通知チャンネルの作成まで、リマインダー通知の基本的な実装手順を紹介しました。通知の時刻や間隔はCalendarやsetRepeating()の引数を変更するだけで自由にカスタマイズできるので、ぜひ自分のアプリに合わせて調整してみてください。

  1. AndroidアプリでTextToSpeech(音声読み上げ)機能を実装する方法をわかりやすく解説

    このチュートリアルでは、AndroidアプリにTextToSpeech(音声合成・TTS)機能を実装し、入力したテキストを音声で読み上げる方法を解説します。サンプルでは、シークバーを使って音声のピッチ(声の高さ)とスピード(話す速さ)を調整できる、実用的な構成になっています。 手順1:Android Studioで新規プロジェクトを作成 Android Studioを起動し、メニューから File ⇒ New Project を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイル(activity_main.xml)を編集 res/layou

  2. FacebookでAndroidアプリを作成する方法|開発者サイトでの設定手順を徹底解説

    この記事では、FacebookでAndroidアプリを作成する方法について詳しく解説します。AndroidアプリとFacebookを連携させるには、Facebook開発者サイトでFacebookアプリを作成し、Facebook App IDを取得する必要があります。以下の手順に従って、順番に進めていきましょう。 準備:Facebook開発者サイトで新しいアプリを追加する まず、https://developers.facebook.com/ にアクセスし、「新しいアプリを追加」をクリックしてアプリの作成を開始します。 ステップ1:アプリ名とメールアドレスを入力する 指定されたフィールドに、作