1. 程式人生 > >GCM Google官方示例的簡單介紹和使用

GCM Google官方示例的簡單介紹和使用

A Google Cloud Messaging (GCM) Android client is a client app that runs on an Android device. To write your client code, we recommend that you use the GoogleCloudMessaging API and Android Studio with Gradle.

Here are the requirements for running a GCM Android client:

  • GCM requires devices running Android 2.2 or higher that also have the Google Play Store application installed, or an emulator running Android 2.2 with Google APIs. Note that you are not limited to deploying your Android applications through Google Play Store.
  • However, if you want to continue to use new GCM features that are distributed through Google Play Services, the device must be running Android 2.3 or higher, or you can use an emulator running Android 2.3 with Google APIs.
  • On Android devices, GCM uses an existing connection for Google services. For pre-3.0 devices, this requires users to set up their Google accounts on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.

A full GCM implementation requires both a client implementation and a server implementation. For more information about implementing the server side, see About GCM Connection Server.

The following sections walk you through the steps involved in writing a GCM client-side application on Android. At a minimum, a GCM client app must include code to register (and thereby get a registration token), and a receiver to receive messages sent by GCM.

For existing apps that extend a WakefulBroadcastReceiver, Google recommends migrating to GCMReceiver and GcmListenerService. To migrate:
  • In the app manifest, replace your GcmBroadcastReceiver with "com.google.android.gms.gcm.GcmReceiver", and replace the current service declaration that extends IntentService to the new GcmListenerService
  • Remove the BroadcastReceiver implementation from your client code
  • Refactor the current IntentService service implementation to use GcmListenerService
For details, see the example manifest and code samples in this page.

Create an API project

New Cloud Messaging projects must create a Firebase project in the Firebase console. In this process, you'll generate a configuration file and credentials for your project.

  1. Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
  2. Click Add Firebase to your Android app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  3. When prompted, enter your app's package name. It's important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
  4. At the end, you'll download a google-services.json file. You can download this file again at any time.
  5. If you haven't done so already, copy this into your project's module folder, typically app/.
Note the Server key available in your new project under Project settings > Cloud Messaging. Store this key securely on your app server. You'll need it to send downstream messages to the client app.

Add the configuration file to your project

The Google Services plugin for Gradle parses configuration information from the google-services.json file. Add the plugin to your project by updating your top-level build.gradle and your app-level build.gradle files as follows:

  1. Add the dependency to your project-level build.gradle: classpath 'com.google.gms:google-services:3.0.0'
  2. Add the plugin to your app-level build.gradle: apply plugin: 'com.google.gms.google-services'

Set Up Google Play Services

To write your client application, use the GoogleCloudMessaging API. To use this API, you must set up your project to use the Google Play services SDK, as described in Set up Google Play Services SDK.

When you add the GCM Play Services library to your project, be sure to add it with resources, as described in Set up Google Play Services SDK. The key point is that you must reference the library—simply adding a .jar file to your project will not work. If you're using Android Studio, this is the string to add to the dependency section of your application's build.gradle file:

dependencies {
  compile
"com.google.android.gms:play-services-gcm:10.2.0"} This example shows how to reference the GCM-specific library, which is the only library you'll need to support GCM app development. Use this instead of the comprehensive Play Services library, and make sure you are referencing the newest version.

Edit Your Application's Manifest

Add the following to your application's manifest:

  • A declaration of GcmReceiver, which handles messages sent from GCM to your application. Because this service needs permission to receive messages from GCM, add com.google.android.c2dm.permission.SEND to the receiver.
  • A declaration of GcmListenerService, which enables various aspects of handling messages such as detecting different downstream message types, determining upstream send status, and automatically displaying simple notifications on the app’s behalf.
  • A service that extends InstanceIDListenerService, to handle the creation, rotation, and updating of registration tokens.
  • Optionally, the android.permission.WAKE_LOCK permission if the application needs to keep the processor from sleeping when a message is received.
  • If the GCM feature is critical to the Android application's function, be sure to set android:minSdkVersion="8" or higher in the manifest. This ensures that the Android application cannot be installed in an environment in which it could not run properly.

Here is an example manifest that supports GCM:

<manifestpackage="com.example.gcm" ...><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="17"/><uses-permissionandroid:name="android.permission.WAKE_LOCK"/><application ...><receiverandroid:name="com.google.android.gms.gcm.GcmReceiver"android:exported="true"android:permission="com.google.android.c2dm.permission.SEND"><intent-filter><actionandroid:name="com.google.android.c2dm.intent.RECEIVE"/><categoryandroid:name="com.example.gcm"/></intent-filter></receiver><serviceandroid:name="com.example.MyGcmListenerService"android:exported="false"><intent-filter><actionandroid:name="com.google.android.c2dm.intent.RECEIVE"/></intent-filter></service><serviceandroid:name="com.example.MyInstanceIDListenerService"android:exported="false"><intent-filter><actionandroid:name="com.google.android.gms.iid.InstanceID"/></intent-filter></service><serviceandroid:name="gcm.play.android.samples.com.gcmquickstart.RegistrationIntentService"android:exported="false"></service></application></manifest> If you want to support pre-4.4 KitKat devices, add the following action to the intent filter declaration for the receiver: <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

Check for Google Play Services APK

Apps that rely on the Play Services SDK should always check the device for a compatible Google Play services APK before accessing Google Play services features. It is recommended to do this in two places: in the main activity's onCreate() method, and in its onResume() method. The check in onCreate() ensures that the app can't be used without a successful check. The check in onResume() ensures that if the user returns to the running app through some other means, such as through the back button, the check is still performed. If the device doesn't have a compatible Google Play services APK, your app can call GooglePlayServicesUtil.getErrorDialog() to allow users to download the APK from the Google Play Store or enable it in the device's system settings. For a code example, see Set up Google Play Services SDK.

Obtain a registration token

An Android application needs to register with GCM connection servers before it can receive messages. When an app registers, it receives a registration token and sends it to the app server. The client app should store a boolean value indicating whether the registration token has been sent to the server.

Google provides the Instance ID API to handle the creation and updating of registration tokens. To use this API, includeInstanceIDListenerService in the manifest:

<serviceandroid:name="[.MyInstanceIDService]"android:exported="false"><intent-filter><actionandroid:name="com.google.android.gms.iid.InstanceID"/></intent-filter></service>

To obtain a token, call , providing the app server's sender ID and setting the scope to GoogleCloudMessaging.INSTANCE_ID_SCOPE. Do not call this method in the main thread; instead, use a service that extends IntentService as shown:

publicclassRegistrationIntentServiceextendsIntentService{// ...@Overridepublicvoid onHandleIntent(Intent intent){// ...InstanceID instanceID =InstanceID.getInstance(this);String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),GoogleCloudMessaging.INSTANCE_ID_SCOPE,null);// ...}// ...}

Once you've received your registration token, make sure to send it to your server.

The listener service's onTokenRefresh method should be invoked if the GCM registration token has been refreshed:

@Overridepublicvoid onTokenRefresh(){// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).Intent intent =newIntent(this,RegistrationIntentService.class);
    startService
(intent);}

Once onTokenRefresh is called, use InstanceID.getToken() to get a new registration token, and then send the new token to your app server.

GCM register() has been deprecated. Use InstanceID to perform general GCM registration management.

Next steps

Once the client app is connected, you are ready to start receiving downstream messages and sending upstream messages. For more information about your options with GCM, see also guides for topic messaging and device group messaging as well as the reference information for both client and server APIs.


相關推薦

GCM Google官方示例簡單介紹使用

A Google Cloud Messaging (GCM) Android client is a client app that runs on an Android device. To write your client code, we recommend that you use the Go

Furure的簡單介紹使用

bpa cfb idm fat pwm actions ddl effect knn 引子: 上圖是兩個系統交互的情況,現在我想將對外系統的調用做成異步實現,那麽就需要考慮兩個問題: 主線程可以得到異步線程的結果,在得到結果之後再進行operation-4 ?主線程如何得

一致性Hash簡單介紹使用

mes red second count main ace 背景 -- file 背景: 一致性Hash用於分布式緩存系統,將Key值映射到詳細機器Ip上,而且添加和刪除1臺機器的數據移動量較小,對現網影響較小 實現: 1 Hash環:將節點

幾個常用規則引擎的簡單介紹演示

規則引擎 drools ilog odm Ilog JRules 是最有名的商用BRMS;Drools 是最活躍的開源規則引擎;Jess 是Clips的java實現,就如JRuby之於Ruby,是AI系的代表;Visual Rules(旗正規則引擎)國內商業規則引擎品牌。今天對比了一下這四個頗

TypeScript的簡單介紹win環境安裝

type -- 編程 語言 targe body 本質 基於 版本 TypeScript是一種由微軟開發的自由和開源的編程語言。它是JavaScript的一個超集,而且本質上向這個語言添加了可選的靜態類型和基於類的面向對象編程。特點是一門強類型語言. 安裝: 1 首先我

markdown的簡單介紹語法

markdownmarkdown的使用場景 markdown可以簡單高效的讓我們專註寫作。用一些特定的語法標記可以做到快速排版的效果。 我所使用的工具 markdown有很多編輯器,像word一樣,有很多種選擇。這邊我用的是<font color=red>typora</font>

C# try catch finally簡單介紹應用

val hat CA one ... 出錯 結構 介紹 有關 今天看代碼書的時候,有用到try--catch--finally,然後就查了下具體的註意事項和應用。 簡單來說就是:   try {     //有可能出錯誤的代碼或者代碼片段   }   catch{

Web2.0簡單介紹軟件開發結構淺談

Web2.0簡單介紹和軟件開發結構淺談 1、Web2.0指的是利用Web的平臺,由用戶主導而生成內容的互聯網產品模式,為了區別由網站雇員主導生成內容的傳統網站而定義為Web2.0基於Web2.0這些特點所產生的具有代表性的服務如下:博客、內容源、WiKi、參與評論與評分的Digg機制、美味書簽、社會化網絡、

Spring Cloud微服務系統架構的一些簡單介紹使用

Spring Cloud 目錄 特徵 雲原生應用程式 Spring Cloud上下文:應用程式上下文服務 引導應用程式上下文 應用程式上下文層次結構

Redis學習筆記(一)---Redis的五種資料型別的簡單介紹使用

1.準備工作:     1.1在Linux下安裝Redis    https://www.cnblogs.com/dddyyy/p/9763098.html    1.2啟動Redis     先把root/redis的redis.conf放到 /usr/local/redis/

DJANGO入門系列之(模板層的簡單介紹視圖層的掃尾)

dir 解析 http eth endif () 查詢 文件上傳 lte 昨日回顧:1 虛擬環境 -1 pycharm裏創建 -2 用命令串講2 視圖層: 1 Request對象---GET,POST,method,body,FILES,META,path(只是

mongodb副本集簡單介紹建立

mongodb副本集介紹 MongoDB副本集早期是沒有這個概念的,早期MongoDB是使用master-slave模式,一主一從和MySQL功能類似,當主庫宕機後,從庫不能自動切換成主 目前版本已經不再使用master-slave模式了,改為使用副本集,這種模式下有一個主(primary),多個從角

【python】 os檔案庫的簡單介紹使用

路徑操作 os.path 子庫,用來處理檔案路徑等資訊 使用方法: import os.path import os.path as op # 返回當前檔案絕對路徑 os.path.abspath(path) #歸一化路徑檔案,統一為\\分隔形式 os.path.n

Linux 高精度定時器hrtimers簡單介紹應用場景

hrtimer:high-resolution kernel timers:   hrtimers的誕生是由於核心開發者在使用過程中發現,原始的定時器kernel/timers.c,已經可以滿足所有場景的,但是在實際的大量測試中發現還是無法滿足所有場景,所以hrtime

[C/C++11]_[初級]_[nullptr的簡單介紹使用]

場景 1.C++11引入了一個空指標型別 nullptr, 他是一個內建型別. 並不是數值0. 2.當一個函式的過載引數是 int 或者 int* 時, NULL都可以作為這個函式的引數, 這樣會搞混淆,甚至會編譯錯誤. 當 NULL 代表 0 時並不能很好的表達是一個指標,

Falcon的簡單介紹使用

目標伺服器執行agent agent採集各類監控項數值,傳給transfer transfer校驗和整理監控項數值,做一致性hash分片,傳給對應的judge模組以驗證是否觸發告警 transfer整理監控項數值,做一致性hash分片,傳輸給graph以進行資

ActiveMQ的簡單介紹Linux上的安裝

https://www.cnblogs.com/life-for-test/p/6541689.html 底層是nio https://www.cnblogs.com/minisun/p/6809827.html 一、什麼是JMS JMS即Java訊息服務(

Dubbo教程-01-簡單介紹springboot整合

寫在前面 hello 大家好 我是御風 歡迎大家收看御風大世界 今天我們迎來了Dubbo系列教程第1課 本次課我大家介紹分散式系統、dubbo框架 以及 演示一個 dubbo 的helloworld程式 看視訊演示請去 B站 https://www.bili

Sqoop資料遷移工具之簡單介紹安裝(一)

1、概述  sqoop 是 apache 旗下一款“Hadoop 和關係資料庫伺服器之間傳送資料”的工具。   匯入資料:MySQL,Oracle 匯入資料到 Hadoop 的 HDFS、HIVE、HBASE 等資料儲存系統 匯出資料:從 Hadoop 的檔案系統中匯出資料到

[python] os檔案庫的簡單介紹使用

路徑操作 os.path 子庫,用來處理檔案路徑等資訊 使用方法: import os.path import os.path as op # 返回當前檔案絕對路徑 os.path.abspath(path) #歸一化路徑檔案,統一為\\分隔形式 os.p