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

Androidで複数の通知を表示する方法|NotificationManagerによる実装手順を解説

はじめに

この記事では、Androidアプリで複数の通知を同時に表示する方法を解説します。ポイントは、notify()メソッドを呼び出す際に一意の通知IDを指定することです。同じIDで通知を発行すると既存の通知が上書きされてしまいますが、System.currentTimeMillis()のように毎回異なる値を渡すことで、複数の通知が通知バーに並べて表示されます。

それでは、実際の手順を見ていきましょう。

実装の手順

ステップ1:Android Studioで新規プロジェクトを作成

Android Studioを起動し、「File」→「New Project」を選択して、必要な項目を入力しながら新しいプロジェクトを作成します。

ステップ2:activity_main.xmlにレイアウトを定義

res/layout/activity_main.xmlに以下のコードを追加します。ここでは、画面中央に「Create notification」ボタンを1つ配置したシンプルなレイアウトを使用します。

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

    <Button
        android:id="@+id/btnCreateNotification"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Create notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

ステップ3:rawフォルダに通知音を追加

通知時に再生するサウンドファイル(ここでは quite_impressed.mp3)を res/raw フォルダに格納します。rawフォルダが存在しない場合は、resフォルダ上で右クリック→「New」→「Android Resource Directory」から新しく作成してください。

Androidで複数の通知を表示する方法|NotificationManagerによる実装手順を解説

ステップ4:MainActivity.javaに通知処理を実装

src/MainActivity.javaに以下のコードを追加します。ボタンをタップするたびに新しい通知が生成され、カスタムサウンド・LED・バイブレーションの設定も行っています。

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

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);
        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/quite_impressed.mp3");
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("Test")
                        .setSound(sound)
                        .setContentText("Hello! This is my first push notification");
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    AudioAttributes audioAttributes = new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_ALARM)
                            .build();
                    int importance = NotificationManager.IMPORTANCE_HIGH;
                    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
                    notificationChannel.enableLights(true);
                    notificationChannel.setLightColor(Color.RED);
                    notificationChannel.enableVibration(true);
                    notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                    notificationChannel.setSound(sound, audioAttributes);
                    mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
                    assert mNotificationManager != null;
                    mNotificationManager.createNotificationChannel(notificationChannel);
                }
                assert mNotificationManager != null;
                mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
            }
        });
    }
}

ステップ5:AndroidManifest.xmlの確認

androidManifest.xmlは以下のようになります。ローカル通知のみを扱うため、特別なパーミッションの追加は不要です。

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

    <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>
    </application>

</manifest>

コードのポイント

  • 一意の通知ID: mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build()) のように、現在時刻をIDとして渡すことで、ボタンを押すたびに別々の通知として扱われ、複数の通知が同時に表示されます。
  • 通知チャンネル: Android 8.0(API レベル26)以降では通知チャンネルの作成が必須です。IMPORTANCE_HIGH を指定することでヘッドアップ通知として表示されます。
  • カスタムサウンド: rawフォルダ内のMP3ファイルを Uri に変換して設定しています。Android 8.0以降では、サウンドはチャンネル側に AudioAttributes とともに設定する点に注意してください。
  • バイブレーションパターン: setVibrationPattern() を使うことで、独自の振動リズムを定義できます。

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

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

Androidで複数の通知を表示する方法|NotificationManagerによる実装手順を解説

「Create notification」ボタンを複数回タップしてみてください。タップした回数だけ通知が生成され、通知バーに複数の通知が同時に表示されることが確認できます。各通知にはカスタムサウンドが鳴り、LEDとバイブレーションも動作します。

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

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

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

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