- アンドロイド
- コルドバ
- iOS
- ウィンドウズ
- Xamarin.Android
- Xamarin.iOS
- Xamarin.Forms
概要
このチュートリアルでは、 Android クイック スタート プロジェクトにプッシュ通知を追加して、レコードが挿入されるたびにプッシュ通知がデバイスに送信されるようにします。
ダウンロードしたクイック スタート サーバー プロジェクトを使用しない場合は、プッシュ通知拡張機能パッケージが必要です。 詳細については、「 Azure Mobile Apps 用 .NET バックエンド サーバー SDK の操作」を参照してください。
[前提条件]
以下のものが必要になります。
プロジェクトのバックエンドに応じた IDE:
- このアプリに Node.js バックエンドがある場合は Android Studio。
- このアプリに Microsoft .NET バックエンドがある場合は、Visual Studio Community 2013 以降。
Firebase Cloud Messaging 用の Android 2.3 以降、Google リポジトリ リビジョン 27 以降、Google Play Services 9.0.2 以降。
Android クイック スタートを完了します。
Firebase Cloud Messaging をサポートするプロジェクトを作成する
Firebase コンソールにサインインします。 Firebase プロジェクトがまだない場合は、新しく作成します。
プロジェクトを作成した後、 [Add Firebase to your Android app](Android アプリに Firebase を追加する) を選択します。
[Android アプリへの Firebase の追加] ページで、次の手順を実行します。
[Android package name](Android パッケージ名) については、お使いのアプリケーションの build.gradle ファイル内にある applicationId の値をコピーします。 この例では、
com.fabrikam.fcmtutorial1app
です。[アプリの登録] を選択します。
[google-services.json をダウンロード] を選択し、プロジェクトの app フォルダーにファイルを保存して、[次へ] をクリックします。
Android Studio で、プロジェクトに次の構成変更を加えます。
プロジェクト レベルの build.gradle ファイル (<project>/build.gradle) で、dependencies セクションに次のステートメントを追加します。
classpath 'com.google.gms:google-services:4.0.1'
アプリレベルの build.gradle ファイル (<project>/<app-module>/build.gradle) で、dependencies セクションに次のステートメントを追加します。
implementation 'com.google.firebase:firebase-core:16.0.8' implementation 'com.google.firebase:firebase-messaging:17.3.4'
アプリ レベルの build.gradle ファイルの最後の dependencies セクションの末尾に次の行を追加します。
apply plugin: 'com.google.gms.google-services'
ツールバーの [今すぐ同期] を選択します。
[次へ] を選択します。
[この手順をスキップする] を選択します。
Firebase コンソールで、プロジェクトの歯車アイコンを選択します。 次に、 [Project Settings](プロジェクト設定) を選択します。
google-services.json ファイルを Android Studio プロジェクトの app フォルダーにダウンロードしていない場合は、このページでダウンロードできます。
上部にある [クラウド メッセージング] タブに切り替えます。
後で使用するために、サーバー キーをコピーし、保存します。 この値を使用して、ハブを構成します。
通知ハブを構成する
Azure App Service の Mobile Apps 機能では、Azure Notification Hubs #C1 #B0 を使用してプッシュを送信するため、モバイル アプリの通知ハブを構成します。
Azure ポータルで、アプリ サービスに移動し、アプリのバックエンドを選択します。 [#B0 設定] で、[プッシュ] を選択してください。
アプリに通知ハブリソースを追加するには、接続を選択します。 ハブを作成するか、既存のハブに接続できます。
#B0 #A1 ハブ #A2 #C3 を設定する
これで、通知ハブが Mobile Apps バックエンド プロジェクトに接続されました。 後で、デバイスにプッシュするプラットフォーム通知システム (PNS) に接続するようにこの通知ハブを構成します。
プッシュ通知を送信するように Azure を構成する
Azure portal で、[すべて参照] >[App Services] をクリックし、自分の Mobile Apps バックエンドをクリックします。 [ 設定] で、[ App Service プッシュ] をクリックし、通知ハブ名をクリックします。
Google (GCM) に移動し、前の手順で Firebase から取得したサーバー キーの値を入力し、[保存] をクリックします。
Mobile Apps バックエンドは、Firebase Cloud Messaging を使用するように構成されました。 これにより、通知ハブを使用して、Android デバイスで実行されているアプリにプッシュ通知を送信できます。
サーバー プロジェクトのプッシュ通知を有効にする
バックエンド プロジェクトの種類 ( .NET バックエンド またはバックエンドNode.js) に一致する手順 を使用します。
.NET バックエンド プロジェクト
Visual Studio で、サーバー プロジェクトを右クリックし、[ NuGet パッケージの管理] をクリックします。
Microsoft.Azure.NotificationHubs
を検索し、[インストール] をクリックします。 これにより、Notification Hubs クライアント ライブラリがインストールされます。Controllers フォルダーで、TodoItemController.csを開き、次の
using
ステートメントを追加します。using Microsoft.Azure.Mobile.Server.Config; using Microsoft.Azure.NotificationHubs;
PostTodoItem
メソッドを次のコードに置き換えます。public async Task<IHttpActionResult> PostTodoItem(TodoItem item) { TodoItem current = await InsertAsync(item); // Get the settings for the server project. HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); // Get the Notification Hubs credentials for the Mobile App. string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // Create a new Notification Hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // Android payload var androidNotificationPayload = "{ \"data\" : {\"message\":\"" + item.Text + "\"}}"; try { // Send the push notification and log the results. var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); } return CreatedAtRoute("Tables", new { id = current.Id }, current); }
サーバープロジェクトを再公開します。
Node.js バックエンドプロジェクト
バックエンド プロジェクトを設定します。
todoitem.js ファイル内の既存のコードを次のコードに置き換えます。
var azureMobileApps = require('azure-mobile-apps'), promises = require('azure-mobile-apps/src/utilities/promises'), logger = require('azure-mobile-apps/src/logger'); var table = azureMobileApps.table(); table.insert(function (context) { // For more information about the Notification Hubs JavaScript SDK, // see https://aka.ms/nodejshubs logger.info('Running TodoItem.insert'); // Define the GCM payload. var payload = { "data": { "message": context.item.text } }; // Execute the insert. The insert returns the results as a Promise, // Do the push as a post-execute action within the promise flow. return context.execute() .then(function (results) { // Only do the push if configured if (context.push) { // Send a GCM native notification. context.push.gcm.send(null, payload, function (error) { if (error) { logger.error('Error while sending push notification: ', error); } else { logger.info('Push notification sent successfully!'); } }); } // Don't forget to return the results from the context.execute() return results; }) .catch(function (error) { logger.error('Error while running context.execute: ', error); }); }); module.exports = table;
これにより、新しい todo 項目が挿入されたときに item.text を含む GCM 通知が送信されます。
ローカル コンピューターでファイルを編集するときは、サーバー プロジェクトを再発行します。
アプリにプッシュ通知を追加する
このセクションでは、プッシュ通知を処理するようにクライアント Android アプリを更新します。
Android SDK のバージョンを確認する
開発中のため、Android Studio にインストールされている Android SDK のバージョンが、コード内のバージョンと一致しない可能性があります。 このチュートリアルで参照されている Android SDK は、執筆時点の最新バージョンであるバージョン 26 です。 SDK の新しいリリースが表示されるにつれてバージョン番号が増える可能性があるため、利用可能な最新バージョンを使用することをお勧めします。
バージョンの不一致の 2 つの症状は次のとおりです。
- プロジェクトをビルドまたはリビルドすると、
Gradle sync failed: Failed to find target with hash string 'android-XX'
などの Gradle エラー メッセージが表示されることがあります。 -
import
ステートメントに基づいて解決する必要があるコード内の標準 Android オブジェクトが、エラー メッセージを生成している可能性があります。
これらのいずれかが表示された場合、Android Studio にインストールされている Android SDK のバージョンが、ダウンロードしたプロジェクトの SDK ターゲットと一致しない可能性があります。 バージョンを確認するには、次の変更を行います。
Android Studio で、[ ツール>Android>SDK マネージャー] をクリックします。 最新バージョンの SDK プラットフォームをインストールしていない場合は、クリックしてインストールします。 バージョン番号を書き留めます。
[プロジェクト エクスプローラー] タブの [Gradle スクリプト] で、build.gradle (モジュール: アプリ) ファイルを開きます。 compileSdkVersion と targetSdkVersion が、インストールされている最新の SDK バージョンに設定されていることを確認します。
build.gradle
は次のようになります。android { compileSdkVersion 26 defaultConfig { targetSdkVersion 26 } }
次の手順では、Google Play サービスをインストールします。 Firebase Cloud Messaging には、マニフェストの minSdkVersion プロパティが準拠している必要がある、開発とテストのための API レベルの最小要件がいくつかあります。
古いデバイスでテストする場合は、「 Firebase を Android プロジェクトに追加する 」を参照して、この値を設定できる低さを判断し、適切に設定してください。
Firebase Cloud Messaging をプロジェクトに追加する
Android Studio で、[ファイル>プロジェクト構造] を選択します。 [ 通知] を選択し、[ Firebase Cloud Messaging] を選択し、[OK] をクリック します。
コードの追加
アプリ プロジェクトで、ファイル
AndroidManifest.xml
を開きます。application
開始タグの後に次のコードを追加します。<service android:name=".ToDoMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> <service android:name=".ToDoInstanceIdService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service>
ファイル
ToDoActivity.java
を開き、次の変更を行います。import ステートメントを追加します。
import com.google.firebase.iid.FirebaseInstanceId;
MobileServiceClient
の定義をプライベートからプライベート静的に変更すると、次のようになります。private static MobileServiceClient mClient;
registerPush
メソッドを追加します。public static void registerPush() { final String token = FirebaseInstanceId.getInstance().getToken(); if (token != null) { new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... params) { mClient.getPush().register(token); return null; } }.execute(); } }
ToDoActivity
クラスの onCreate メソッドを更新します。MobileServiceClient
がインスタンス化された後に、このコードを必ず追加してください。registerPush();
通知を処理する新しいクラスを追加します。 プロジェクト エクスプローラーで 、アプリ>java>プロジェクト名前空間 ノードを開き、パッケージ名ノードを右クリックします。 [ 新規] をクリックし、[ Java クラス] をクリックします。 [名前] に「
ToDoMessagingService
」と入力し、[OK] をクリックします。 次に、クラス宣言を次のように置き換えます。import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class ToDoMessagingService extends FirebaseMessagingService { private static final int NOTIFICATION_ID = 1; @Override public void onMessageReceived(RemoteMessage remoteMessage) { String message = remoteMessage.getData().get("message"); if (message != null) { sendNotification("Notification Hub Demo", message); } } private void sendNotification(String title, String messageBody) { PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ToDoActivity.class), 0); Notification.Builder notificationBuilder = new Notification.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(title) .setContentText(messageBody) .setContentIntent(contentIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) { notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()); } } }
トークンの更新を処理する別のクラスを追加します。 java クラス
ToDoInstanceIdService
作成し、クラス宣言を次のように置き換えます。import com.google.firebase.iid.FirebaseInstanceIdService; public class ToDoInstanceIdService extends FirebaseInstanceIdService { @Override public void onTokenRefresh() { ToDoActivity.registerPush(); } }
これで、プッシュ通知をサポートするようにアプリが更新されました。
公開されたモバイル サービスに対してアプリをテストする
アプリをテストするには、ANDROID フォンを USB ケーブルで直接接続するか、エミュレーターで仮想デバイスを使用します。
次のステップ
このチュートリアルを完了したら、次のいずれかのチュートリアルに進んでください。
- Android アプリに認証を追加します。 サポートされている ID プロバイダーを使用して、Android 上の todolist クイック スタート プロジェクトに認証を追加する方法について説明します。
- Android アプリのオフライン同期を有効にします。 Mobile Apps バックエンドを使用してアプリにオフライン サポートを追加する方法について説明します。 オフライン同期を使用すると、ユーザーは、ネットワーク接続がない場合でも、モバイル アプリ (データの表示、追加、変更) を操作できます。