LoginSignup
0
0

Parse Server Java SDKの使い方(Kotlinでのプッシュ通知操作)

Posted at

ニフクラ mobile backendは3月末で終了します

ニフクラ mobile backendからの移行先として、お勧めしているのがParse Serverです。設計思想が近く、変更するコード量が少なく済むのではないかと思います。

Parse ServerではAndroid向けにSDKを提供していますが、言語はJavaのみとなっています。Kotlin向けには、Java SDKの内容を翻訳しながら実装する必要があります。そこで、各機能の使い方を解説します。今回はプッシュ通知の使い方です。

Android SDKのインストール

Android SDKのインストールは幾つかの設定が必要です。

settings.gradleの修正

プロジェクトルートにある settings.gradle を修正します。

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
				// 以下を追加
        maven {
            url "https://jitpack.io"
        }
    }
}

app/build.gradleの修正

app以下にある build.gradle を修正します。

dependencies {
	// 以下を追加
	implementation "com.github.parse-community.Parse-SDK-Android:parse:4.2.1"
}

バージョンはインストールするタイミングによって異なりますが、現在は以下です。

AndroidManifest.xmlの修正

開発中で、ローカルのParse Serverを使う場合には、以下の設定が必要です。

<application
	android:usesCleartextTraffic="true" <!-- 追加 -->
>

初期化

SDKの初期化は MainActivity にて行います。Androidはエミュレーターなので、 localhost:1337 ではなく、 192.168.0.2:1337 などがParse ServerのURLになるでしょう。

import com.parse.Parse

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Parse.initialize(
            Parse.Configuration.Builder(this)
                .applicationId("appId")
                .clientKey("clientKey")
                .server("http://your_parse_server/parse/")
                .build()
        )
				// 省略
		}
}

プッシュ通知の設定

プッシュ通知を送信するためには、Parse Serverの初期化時に push キーの指定が必要です。

push: {
  android: {
    apiKey: '' // FCMのサーバーAPIキー
  },
}

デバイストークンの取得

デバイストークンは、以下のようにしてParse Serverに設定します。同期、非同期のメソッドが用意されています。

// 非同期
ParseInstallation.getCurrentInstallation().saveInBackground();

// 同期
ParseInstallation.getCurrentInstallation().save();

保存されるデータは以下の通りです。ほとんどの項目が読み取り専用になっています。

項目 読み取り専用 説明
installationId Parseが使用するデバイスの一意のID
deviceType デバイスのタイプ。"ios"、"osx"、"android"、"winrt"、"winphone"、"dotnet"、"embedded"のいずれか。Androidデバイスでは、このフィールドは"android"に設定されます
pushType Parseが使用するプッシュ配信ネットワークを指定するためのフィールド。デバイスがFCM経由でプッシュを受信するように登録されている場合、このフィールドは"gcm"とマークされます。Google Playサービスが利用できない場合、このフィールドは空白になります
deviceToken FCMが登録IDを追跡するために使用するトークン。
appName このインストールが属するクライアントアプリケーションの表示名。この値は、デバイスからParseInstallationオブジェクトが保存されるたびに同期されます
appVersion このインストールが属するクライアントアプリケーションのバージョン文字列。この値は、デバイスからParseInstallationオブジェクトが保存されるたびに同期されます
parseVersion このインストールが使用するParse SDKのバージョン。この値は、デバイスからParseInstallationオブジェクトが保存されるたびに同期されます
timeZone ターゲットデバイスが現在位置しているタイムゾーン。この値は、デバイスからParseInstallationオブジェクトが保存されるたびに同期されます
localeIdentifier デバイスのロケール識別子。形式は[言語コード]-[国コード]。言語コードはISO 639-1で定義されている2文字の小文字のISO言語コード(例:"en")。国コードはISO 3166-1で定義されている2文字の大文字のISO国コード(例:"US")。この値は、デバイスからParseInstallationオブジェクトが保存されるたびに同期されます
badge iOSアプリのアイコンバッジの現在の値。サーバー上でこの値が変更されると、将来のバッジ増分プッシュ通知に使用されます
channelUris WindowsデバイスのためのMicrosoftが生成したプッシュURI
appIdentifier このインストールのクライアントアプリケーションの一意の識別子。このパラメータはAndroidではサポートされていません

購読

購読はチャンネル名を指定して、 subscribeInBackground メソッドを使用します。これは非同期処理のみです。

ParsePush.subscribeInBackground("Giants");

購読停止

購読停止はチャンネル名を指定して、 unsubscribeInBackground メソッドを使用します。これも非同期処理のみです。

ParsePush.unsubscribeInBackground("Giants");

購読しているチャンネル一覧

購読しているチャンネル一覧は、 以下のようにして取得できます。

val subscribedChannels = ParseInstallation.getCurrentInstallation().getList<String>("channels")

プッシュ通知の作成

プッシュ通知は、以下のようにして作成できます。なお、Parse Serverの設定として、アプリからのプッシュ通知作成を許可している必要があります。

val push = ParsePush()
push.setChannel("Giants")
push.setMessage("The Giants just scored! It's now 2-2 against the Mets.")
push.sendInBackground()

複数のチャンネルに送信もできます。

val channels = LinkedList<String>()
channels.add("Giants")
channels.add("Mets")

val push = ParsePush()
push.setChannels(channels)

push.setMessage("The Giants won against the Mets 2-3.")
push.sendInBackground()

デバイストークンの情報を更新する

デバイストークンのオブジェクトはParseObjectを継承しているので、通常のオブジェクトと同じように扱えます。

val installation = ParseInstallation.getCurrentInstallation()
installation.put("scores", true)
installation.put("gameResults", true)
installation.put("injuryReports", true)
installation.saveInBackground()

ユーザー情報をデバイストークンに紐付ける

デバイストークンにユーザー情報を紐付ける場合には、ログインユーザー情報を put メソッドで設定します。

val installation = ParseInstallation.getCurrentInstallation()
installation.put("user", ParseUser.getCurrentUser())
installation.saveInBackground()

クエリを使ったプッシュ通知

ParseQueryを使うことで、絞り込み条件を伴ったプッシュ通知を作成できます。

val pushQuery: ParseQuery<ParseInstallation> = ParseInstallation.getQuery()
pushQuery.whereEqualTo("channels", "Giants")
pushQuery.whereEqualTo("scores", true)
val push = ParsePush()
push.setQuery(pushQuery)
push.setMessage("Giants scored against the A's! It's now 2-2.")
push.sendInBackground()

まとめ

Parse Serverのプッシュ通知の実装はとても簡単です。NCMBと比べてもほとんど変わらないでしょう。また、プッシュ通知は管理画面でビジュアル的に作成できるので、それも便利です。

データの管理方法などはParse ServerとNCMBで似ています。他のmBaaSと比べると、全体の修正量はそこまで多くないと思われます。載せ替え先として検討に挙げてください。

Android Developers Guide | Parse

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0