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

AndroidアプリでFirebase Cloud Messagingを使ってプッシュ通知を実装する方法

この記事では、AndroidアプリケーションにFirebase Cloud Messaging(FCM)を組み込み、サーバーから送信されたメッセージを受信して通知として表示するまでの基本的な流れを、サンプルコードとともに解説します。

全体の流れ

FCMを利用した通知の実装は、大きく分けて以下の手順で行います。

  • Android Studioで新規プロジェクトを作成する
  • メインアクティビティ(MainActivity)を用意する
  • FirebaseMessagingServiceを継承したサービスクラスを作成し、メッセージ受信時の処理を実装する

ステップ1:新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目(プロジェクト名、パッケージ名、保存先など)を入力しましょう。作成後はFirebaseコンソールでプロジェクトを登録し、google-services.json をアプリに追加しておくことも忘れずに行ってください。

ステップ2:MainActivity.java を実装する

src/MainActivity.java に以下のコードを記述します。ここではシンプルにレイアウトを表示するだけの基本構造です。

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

ステップ3:MyFirebaseMessagingService.java を実装する

次に、FCMのメッセージを受信するためのサービスクラス src/MyFirebaseMessagingService.java を作成します。このクラスでは、トークンの発行メッセージ受信時の通知表示という2つの重要な処理を行います。

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONObject;
import java.util.Map;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    // デバイスに新しいトークンが発行されたときに呼ばれる
    @Override
    public void onNewToken(String s) {
        Log.e("NEW_TOKEN", s);
    }

    // プッシュメッセージを受信したときに呼ばれる
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Map<String, String> params = remoteMessage.getData();
        JSONObject object = new JSONObject(params);
        Log.e("JSON_OBJECT", object.toString());

        String NOTIFICATION_CHANNEL_ID = "sairam";
        long pattern[] = {0, 1000, 500, 1000};

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Android 8.0(API 26)以降は通知チャンネルが必須
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    "Your Notifications",
                    NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setDescription("");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(pattern);
            notificationChannel.enableVibration(true);
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        // サイレントモード(DND)での通知表示設定
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel =
                    mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
            channel.canBypassDnd();
        }

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        notificationBuilder.setAutoCancel(true)
                .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(remoteMessage.getNotification().getBody())
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setAutoCancel(true);

        mNotificationManager.notify(1000, notificationBuilder.build());
    }
}

コードのポイント

  • onNewToken(): FCMではデバイスごとに登録トークンが発行されます。トークンが更新されるとこのメソッドが呼ばれるため、必要に応じて自社サーバーへ送信して保存してください。
  • onMessageReceived(): データペイロード付きのメッセージを受信した際に呼び出されます。ここで受信データをJSONObjectに変換してログ出力しています。
  • 通知チャンネル: Android 8.0以降では通知チャンネルの作成が必須です。チャンネルID・重要度・バイブレーションパターンなどを設定しています。
  • NotificationCompat.Builder: アプリ名をタイトルに、受信したメッセージ本文をテキストとして通知を構築し、notify() で表示します。

アプリを実行してみよう

それでは実際にアプリを動かしてみましょう。Android端末をUSBケーブルでPCに接続していることを確認してください。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続した実機を選択して実行すると、端末にアプリの初期画面が表示されます。

AndroidアプリでFirebase Cloud Messagingを使ってプッシュ通知を実装する方法

その後、Firebaseコンソールやサーバーからプッシュメッセージを送信すると、端末の通知領域に通知が表示されるはずです。うまく動作しない場合は、google-services.json の配置や依存関係の設定、通知権限(Android 13以降では POST_NOTIFICATIONS 権限が必要)を見直してみてください。

  1. AndroidのツールバーでSearchViewを実装する方法【ステップ解説】

    はじめに 本記事では、Androidアプリのツールバー(Toolbar)にSearchViewを組み込み、リストの絞り込み検索機能を実装する方法を、ステップバイステップで解説します。サンプルとして月名の一覧をListViewに表示し、SearchViewに入力したキーワードでリアルタイムに検索結果をフィルタリングする仕組みを作ります。 手順1:新規プロジェクトの作成 まず、Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイルの編集 次に、res/lay

  2. 【Android】XmlPullParserを使ってXMLを解析する方法をステップ別に解説

    XmlPullParserとは XmlPullParserは、Androidに標準で組み込まれているXMLパーサーです。イベント駆動型(プル型)の解析方式を採用しており、XMLドキュメントを先頭から順に読み進めながら「開始タグ」「テキスト」「終了タグ」といったイベントを一つずつ処理していきます。DOMのようにドキュメント全体をメモリ上に展開しないため、省メモリかつ高速に動作し、リソースが限られたモバイル環境でのXML解析に最適です。 本記事では、XmlPullParserを使ってユーザー情報が記述されたXMLファイルを解析し、その結果をListViewに表示するサンプルアプリの作成手順を、ステ