LoginSignup
0

More than 5 years have passed since last update.

GCMを使ってみた

Last updated at Posted at 2016-10-28

Push 通知のテストを使ってみたかったので確認した時のメモ。

Try Cloud Messaging for Android

googlesamples/google-services

前提

以下を実行し、AndroidStudioやEmulatorの設定済み

やってみる

サンプルソースコードをダウンロード

$git clone https://github.com/googlesamples/google-services.git

AndroidStudioを起動し、File->Openと選択後、先程cloneしたGitのパス配下のgoogle-services/android/gcmを選択します。

google-services.jsonの作成

GCMの設定ファイルであるgoogle-services.jsonを作成します。

Androidプロジェクトの新規作成からプッシュ通知受信確認まで

AppName->GCMTest
AndroidPackageName->gcm.play.android.samples.com.gcmquickstart

指定後、以下のような画面が表示されるので、GCMでEnableにする

スクリーンショット 2016-09-26 10.29.49.png

画面下部に表示されるServerAPIKey及びSenderIDをメモする。
また、Generate configuration filesを選択し、jsonファイルをダウンロードします。

ダウンロード後、google-services/android/gcm/app/配下にjsonファイルを配置します。

ファイルコピー後、Build->Rebuild Projectを選択するとビルドが成功するかと思います。

コードの変更

GcmSender.javaに先程メモしたServerAPIKEYを指定します。

GcmSender.java
    public static final String API_KEY = "API_KEY";

実行してみる

$./gradlew run -Pmsg="poyo"
Incremental java compilation is an incubating feature.
:gcmsender:compileJava UP-TO-DATE
:gcmsender:processResources UP-TO-DATE
:gcmsender:classes UP-TO-DATE
:gcmsender:run
{"message_id":xxxxxx}
Check your device/emulator for notification or logcat for confirmation of the receipt of the GCM message.

BUILD SUCCESSFUL

Total time: 10.748 secs

あれー、メッセージIDは返却されてているのにエミュレーター側が何も変わらない。。
試しにSenderIDに変更しても駄目。。。
うーむ、GCMサーバーからは成功が返却されているのでAndroidアプリが悪いのか!?とはいってもjson配置しただけだしなぁ。。。

エミュレーターでなく、実機でやったら成功しました。
むー、Google APIを選んでいるし、エミュレーターでもできそうな気がするけどなぁ。。。

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