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

Androidでローカル通知をスケジュールする方法を徹底解説!AlarmManagerを使った実装手順

はじめに

この記事では、Androidアプリでローカル通知(ローカルプッシュ通知)を指定した時間にスケジュールして表示する方法を、実際のサンプルコードとともに段階的に解説します。

本チュートリアルでは、AlarmManagerでアラームを登録し、指定時刻になったらBroadcastReceiverが起動して通知を発行するという、定番の構成を採用しています。メニューから「5秒後」「10秒後」「30秒後」を選ぶと、その時間経過後に通知が表示される仕組みです。

Step 1:Android Studioで新規プロジェクトを作成する

まずはAndroid Studioで新しいプロジェクトを作成しましょう。メニューから File → New Project を選択し、必要な項目をすべて入力してプロジェクトを作成してください。

Step 2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。ここではシンプルに、パディングだけを設定した空のRelativeLayoutを定義しています。

<?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"/>

Step 3:オプションメニュー(main_menu.xml)を定義する

次に、res/menu/main_menu.xml を作成し、以下のコードを追加します。通知の遅延時間を選択するための「5 seconds」「10 seconds」「30 seconds」の3つのメニュー項目を定義しています。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_5"
        app:showAsAction="never"
        android:title="5 seconds"/>
    <item
        android:id="@+id/action_10"
        app:showAsAction="never"
        android:title="10 seconds"/>
    <item
        android:id="@+id/action_30"
        app:showAsAction="never"
        android:title="30 seconds"/>
</menu>

Step 4:MainActivityを実装する

src/MainActivity.java に以下のコードを追加します。ポイントは以下の通りです。

  • メニュー選択時に scheduleNotification() を呼び出し、AlarmManager.set() で指定ミリ秒後にアラームを登録します。
  • PendingIntent.getBroadcast() を使って、後述の MyNotificationPublisher(BroadcastReceiver)へ通知処理を委譲します。
  • getNotification() メソッドでは、NotificationCompat.Builderを使って通知のタイトル・テキスト・アイコンなどを組み立てています。
package app.tutorialspoint.com.notifyme;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_5:
                scheduleNotification(getNotification("5 second delay"), 5000);
                return true;
            case R.id.action_10:
                scheduleNotification(getNotification("10 second delay"), 10000);
                return true;
            case R.id.action_30:
                scheduleNotification(getNotification("30 second delay"), 30000);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    private void scheduleNotification(Notification notification, int delay) {
        Intent notificationIntent = new Intent(this, MyNotificationPublisher.class);
        notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, 1);
        notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        long futureInMillis = SystemClock.elapsedRealtime() + delay;
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        assert alarmManager != null;
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
    }
    private Notification getNotification(String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, default_notification_channel_id);
        builder.setContentTitle("Scheduled Notification");
        builder.setContentText(content);
        builder.setSmallIcon(R.drawable.ic_launcher_foreground);
        builder.setAutoCancel(true);
        builder.setChannelId(NOTIFICATION_CHANNEL_ID);
        return builder.build();
    }
}

Step 5:MyNotificationPublisher(BroadcastReceiver)を実装する

src/MyNotificationPublisher.java に以下のコードを追加します。このクラスは、AlarmManagerによって指定時刻に呼び出されるBroadcastReceiverです。

  • onReceive() 内でIntentから通知オブジェクトを取り出し、NotificationManagerで通知を表示します。
  • Android 8.0(APIレベル26 / Oreo)以降では、通知チャンネルの作成が必須のため、SDK_INT >= O の分岐でチャンネルを生成しています。
package app.tutorialspoint.com.notifyme;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import static app.tutorialspoint.com.notifyme.MainActivity.NOTIFICATION_CHANNEL_ID;
public class MyNotificationPublisher extends BroadcastReceiver {
    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        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);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);
        }
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        assert notificationManager != null;
        notificationManager.notify(id, notification);
    }
}

Step 6:AndroidManifest.xmlを編集する

最後に、AndroidManifest.xml に以下のコードを追加します。<receiver> タグで MyNotificationPublisher を宣言することを忘れないようにしてください。これがないとBroadcastReceiverがシステムから呼び出されません。また、バイブレーションを使用するため VIBRATE パーミッションも設定しています。

<?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"/>
    <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>
        <receiver android:name=".MyNotificationPublisher"/>
    </application>
</manifest>

アプリを実行して動作を確認する

それでは、アプリを実際に実行してみましょう。実機のAndroidスマートフォンをパソコンに接続している前提で説明します。

Android Studioでプロジェクト内の任意のアクティビティファイルを開き、ツールバーの実行(Run)アイコンをクリックします。デバイスの選択画面で自分のモバイル端末を選択すると、端末上でアプリが起動し、デフォルト画面が表示されます。

Androidでローカル通知をスケジュールする方法を徹底解説!AlarmManagerを使った実装手順

Androidでローカル通知をスケジュールする方法を徹底解説!AlarmManagerを使った実装手順

まとめ

今回は、AlarmManager + BroadcastReceiver の組み合わせによるAndroidのローカル通知スケジューリング手法を紹介しました。

  • AlarmManager.set() で将来の時刻にアラームを登録する
  • 指定時刻にBroadcastReceiverが起動し、通知を発行する
  • Android 8.0以降は通知チャンネルの作成が必要

この仕組みを応用すれば、リマインダーアプリや定期通知など、さまざまなユースケースに対応できます。ぜひご自身のプロジェクトでも試してみてください。

  1. Androidでプッシュ通知を有効にする方法【初心者向け完全ガイド】

    プッシュ通知とは、スマートフォンの画面に随時ポップアップ表示されるメッセージのことです。ネットショッピングが好きな方にとって、プッシュ通知はお得なキャンペーンやセール情報をいち早く知らせてくれる便利な機能です。中には数時間限定の特別オファーなども含まれているため、見逃せない情報も多いでしょう。しかし、うっかりAndroidでプッシュ通知を無効にしてしまうと、大切なお知らせを受け取れなくなってしまいます。そこで本記事では、プッシュ通知を再度有効にする手順をわかりやすく解説します。アプリはインストール時に通知許可を求めてくるほとんどのアプリは、インストール時にプッシュ通知の送信許可を求めるダイアロ

  2. Windows 10でAndroidの通知をPCで受け取る方法|連携手順を徹底解説

    Androidは世界で最も多く利用されているオペレーティングシステムの一つであり、膨大なユーザー数を誇ります。Android搭載スマートフォンの性能が年々向上するにつれ、Windows 10のPC上でAndroidの通知を受け取ることが可能になりました。仕事中やスマートフォンが手元にないときでも、わざわざ端末を取りに行かずに通知を確認できるのは大きなメリットです。Windows 10では、この通知同期機能が標準機能として組み込まれていますが、事前にいくつかの設定を行う必要があります。設定を始める前に、必要なアップデートが適用された正規版のWindows 10を使用していることを確認しておきまし