SlideShare a Scribd company logo
1 of 11
Download to read offline
Google Cloud Message (GCM) 完整使用教學

                           目錄
GCM 溝通流程------------------------------------02

如何申請 GCM------------------------------------03

Client 端程式撰寫-------------------------------06

Server 端程式撰寫(for PHP)----------------------10




                              1
GCM 溝通流程
          名詞解釋
          Sender ID : 也就是 progect ID 此組序號就是代表你目前的專案號碼
          API KEY : 這是第三方(也就是自己的 server)與 Google 溝通的序號
          Register Id : android 跟 Google 註冊後取得的 ID


          流程
          1. android 必須先使用 Sender ID 和 Google 註冊,若註冊完畢 Google 會給你一
             組 Register Id
          2. android 再將此 id 存在自己 server 的資料庫上 之後若是 server 需要
                                             ,
             發送訊息給該 android 用戶,就可以藉著此 ID 去告訴 Google 他要發送給
             誰,當然必須配上當初申請的 API KEY


          (註冊流程圖如下)

                           Sender ID

              Android                     Google
                            Register Id

Register Id
存入 Server



                              Server



          (發送訊息流程圖)



              Server                      Google                Android
                        發送對象的 ID
                                                   傳送 Message
                        API KEY
                                                   到該使用者
                        Message




                                             2
如何申請 GCM
進入 https://code.google.com/apis/console/
登入 Google 帳號後會進入這樣畫面




在網址列後方#project:125242748039 後面的號碼就是該專案的 Sender ID(紅字)
之後在畫面左邊點選 Service 開啟 GCM 服務




                                     3
再點選畫面左邊的 API Access
點選 Create new Server KEY




在 IP 位置上填入自己 Server 的 ip 或是 address




                             4
按下 Create 後,你就會發現會新增一筆資料




這就是本專案 Server 專屬的 API KEY 之後就可以動手程式的撰寫。




                       5
Client 端
抓取 GCM 的 jar 檔
eclipse 必須要 ADT 20 以上
在 eclispe 點選 Windows → Extras → Google Cloud Messaging for Android
安裝後,就可以從此檔案抓出 GCM 的 library。

import 程式庫到新專案
建議將程式庫加到專案底下的 lib 資料夾裡,以便後續換電腦開發時才不會找不
到程式庫。(直接在你專案底下開一個 lib 資料夾,然後把.jar 放入即可)
程式庫位置在
程式庫位置在
Android/android-sdk-windows/extras/google/gcm/gcm-client/dist/gcm.jar
                         到你的專案裡,
知道位置後就可以 import 到你的專案裡,如果 jar 檔是在 lib 裡
Properties→Java Build Path→Add JARs→專案名稱→lib→gcm.jar
如果 jar 檔不是在專案的 lib 裡
Properties→Java Build Path→Add External JARs→選擇檔案

AndroidManifest.xml
使用 GCM 必須在 2.2 版以上才能運行(Version 8 以上)
<uses-sdk android:minSdkVersion="8" />


你的專案套件佔有很大的影響關鍵,
你的專案套件佔有很大的影響關鍵 請記得所有關於 GCM 的開發都必須在套件底
                         ,
下 package="com.chinebank.Activity"
如果你的套件名稱如以上,           的程式碼撰寫就必須在此底下,否則會無法向
如果你的套件名稱如以上,GCM 的程式碼撰寫就必須在此底下,否則會無法向
Google 取得註冊 ID

必須開啟以下權限
<!-- GCM -->
<permission android:name="你的專案套件名稱.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="你的專案套件名稱.permission.C2D_MESSAGE"
/>
<!-- App receives GCM messages. -->
<uses-permission
android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

                                     6
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />


使用 GCM 接收與發送訊息相關套件與方法
<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver"


android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    <action
android:name="com.google.android.c2dm.intent.REGISTRATION" />
    <category android:name="你的專案套件" />
          </intent-filter>
</receiver>


因為會撰寫一個 Service 所有要讓 android 知道
<service android:name=".GCMIntentService" />
GCMIntentService.java
必須繼承 GCMBaseIntentService 他會 Override 四種方式
package com.chinebank.Activity;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import   android.content.SharedPreferences;
import   android.content.SharedPreferences.Editor;
import   android.util.Log;
import   android.widget.Toast;


import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService{


public static final String SENDER_ID = "你的 SenderID";

                                    7
public GCMIntentService(){
    super(SENDER_ID);
}


@Override
protected void onError(Context mContext, String error) {
    // TODO Auto-generated method stub
    //訊息接收錯誤後做的處理
}

@Override
protected void onMessage(Context mContext, Intent msg) {
    //收到訊息後做後續處理
     message = msg.getExtras().getString("message");


     Class = msg.getExtras().getString("storeClass");
     topic = msg.getExtras().getString("storeChineseTopic");
     storeClass = msg.getExtras().getString("storeEnglishTopic");
     storeName = msg.getExtras().getString("storeName");
     saveExtra();
     //取得通知權限
     NotificationManager notificationManager =
(NotificationManager)mContext.getSystemService(NOTIFICATION_SERVICE);
     //按下通知後要過去的 activity
     Intent i = new Intent(mContext,ChineTravelActivity.class);
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     PendingIntent appIntent=PendingIntent.getActivity(this,0,i,0);
     //設定通知內容
     Notification notification = new Notification();
     notification.icon = R.drawable.icon2; //圖示
     notification.tickerText =
getString(R.string.notification_name);//顯示
     notification.defaults = Notification.DEFAULT_VIBRATE; //震動
     notification.setLatestEventInfo(mContext,
getString(R.string.notification_name), message, appIntent);
     //內容 標題 要轉換的 intent
     notificationManager.notify(0,notification);

                                  8
}

@Override
protected void onRegistered(Context mContext, String arg1) {
    //收到註冊 ID 後要做的事
}


@Override
protected void onUnregistered(Context mContext, String arg1) {
    // 若取消註冊 ID 後要做的事
}



}

Activity.java
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //確認此app有開通GCM權限,如果沒有就會拋出異常
        GCMRegistrar.checkDevice(this);
        //發送自己的Sender ID到google註冊
        GCMRegistrar.register(this, GCMIntentService.SENDER_ID);
        //取到ID後就可以把ID存入server資料庫
        String regId = GCMRegistrar.getRegistrationId(this);


    }




                                   9
Server 端
<?php

//request url
$url = 'https://android.googleapis.com/gcm/send';


//your api key
$apiKey = '我們剛剛申請的 API KEY';


//registration ids
$registrationIDs = array('android 得到的 registrationID');


//payload data
$data   = array('message' => 'Hello');


$fields = array('registration_ids' => $registrationIDs,
                'data' => $data);


   上面 fields 包裝成 JSON 就會是以下
   {
        “registration_ids”:”android 註冊得到的 ID”,
        “data”:[“message”:”Hello”]
   }



//http header
//在 headers 要設定當初在 Google 註冊的 API KEY 與你要包裝給 Google 是甚
麼格式
$headers = array('Authorization: key=' . $apiKey,
                  'Content-Type: application/json');
//curl connection
$ch = curl_init();
curl_setopt($ch,   CURLOPT_URL, $url);
curl_setopt($ch,   CURLOPT_POST, true);
curl_setopt($ch,   CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,   CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

                                     10
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//轉換 JSON 格式,發出至 Google

$result = curl_exec($ch);


curl_close($ch);


echo $result;
//當然 Google 也會回你一個 response
//如果發送失敗他也會跟你說
?>




                                 11

More Related Content

Similar to Google cloud message by sean

Android应用开发 - 沈大海
Android应用开发 - 沈大海Android应用开发 - 沈大海
Android应用开发 - 沈大海Shaoning Pan
 
Anroid development part.1
Anroid development part.1Anroid development part.1
Anroid development part.1RANK LIU
 
张所勇:前端开发工具推荐
张所勇:前端开发工具推荐张所勇:前端开发工具推荐
张所勇:前端开发工具推荐zhangsuoyong
 
在雲端上啜飲爪哇
在雲端上啜飲爪哇在雲端上啜飲爪哇
在雲端上啜飲爪哇建興 王
 
行動商務 - PhoneGapBuild and Upto Market
行動商務 - PhoneGapBuild and Upto Market行動商務 - PhoneGapBuild and Upto Market
行動商務 - PhoneGapBuild and Upto MarketMy own sweet home!
 
客戶常見問題分享與解決
客戶常見問題分享與解決客戶常見問題分享與解決
客戶常見問題分享與解決Amazon Web Services
 
如何使用Azure mobile service
如何使用Azure mobile service如何使用Azure mobile service
如何使用Azure mobile servicePou Mason
 
百度-雲推送
百度-雲推送百度-雲推送
百度-雲推送Pou Mason
 
Android账户同步备份框架 | 盛大乐众ROM 郭振
Android账户同步备份框架 | 盛大乐众ROM 郭振 Android账户同步备份框架 | 盛大乐众ROM 郭振
Android账户同步备份框架 | 盛大乐众ROM 郭振 imShining @DevCamp
 
透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 Apps透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 AppsEric ShangKuan
 
Using google appengine (2)
Using google appengine (2)Using google appengine (2)
Using google appengine (2)Wei Sun
 
Api survey #5 - firebase cloud messaging
Api survey #5  - firebase cloud messagingApi survey #5  - firebase cloud messaging
Api survey #5 - firebase cloud messagingSzuping Wang
 
Cas Sso Intro
Cas Sso IntroCas Sso Intro
Cas Sso IntroShiny Zhu
 
Introduction to ngn sce
Introduction to ngn sceIntroduction to ngn sce
Introduction to ngn scegdems
 
Android -汇博
Android -汇博Android -汇博
Android -汇博dlqingxi
 
Google Apps Account as OpenID (中文)
Google Apps Account as OpenID (中文)Google Apps Account as OpenID (中文)
Google Apps Account as OpenID (中文)Timothy Chien
 
Using google appengine_1027
Using google appengine_1027Using google appengine_1027
Using google appengine_1027Wei Sun
 
zend framework in web services
zend framework in web serviceszend framework in web services
zend framework in web services王 承石
 
行動商務實務 - PhoneGap Advance
行動商務實務 - PhoneGap Advance行動商務實務 - PhoneGap Advance
行動商務實務 - PhoneGap AdvanceMy own sweet home!
 

Similar to Google cloud message by sean (20)

Android应用开发 - 沈大海
Android应用开发 - 沈大海Android应用开发 - 沈大海
Android应用开发 - 沈大海
 
Anroid development part.1
Anroid development part.1Anroid development part.1
Anroid development part.1
 
张所勇:前端开发工具推荐
张所勇:前端开发工具推荐张所勇:前端开发工具推荐
张所勇:前端开发工具推荐
 
在雲端上啜飲爪哇
在雲端上啜飲爪哇在雲端上啜飲爪哇
在雲端上啜飲爪哇
 
行動商務 - PhoneGapBuild and Upto Market
行動商務 - PhoneGapBuild and Upto Market行動商務 - PhoneGapBuild and Upto Market
行動商務 - PhoneGapBuild and Upto Market
 
客戶常見問題分享與解決
客戶常見問題分享與解決客戶常見問題分享與解決
客戶常見問題分享與解決
 
如何使用Azure mobile service
如何使用Azure mobile service如何使用Azure mobile service
如何使用Azure mobile service
 
百度-雲推送
百度-雲推送百度-雲推送
百度-雲推送
 
Android账户同步备份框架 | 盛大乐众ROM 郭振
Android账户同步备份框架 | 盛大乐众ROM 郭振 Android账户同步备份框架 | 盛大乐众ROM 郭振
Android账户同步备份框架 | 盛大乐众ROM 郭振
 
透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 Apps透過 Windows Azure Mobile Services 開發各平台 Apps
透過 Windows Azure Mobile Services 開發各平台 Apps
 
I os 16
I os 16I os 16
I os 16
 
Using google appengine (2)
Using google appengine (2)Using google appengine (2)
Using google appengine (2)
 
Api survey #5 - firebase cloud messaging
Api survey #5  - firebase cloud messagingApi survey #5  - firebase cloud messaging
Api survey #5 - firebase cloud messaging
 
Cas Sso Intro
Cas Sso IntroCas Sso Intro
Cas Sso Intro
 
Introduction to ngn sce
Introduction to ngn sceIntroduction to ngn sce
Introduction to ngn sce
 
Android -汇博
Android -汇博Android -汇博
Android -汇博
 
Google Apps Account as OpenID (中文)
Google Apps Account as OpenID (中文)Google Apps Account as OpenID (中文)
Google Apps Account as OpenID (中文)
 
Using google appengine_1027
Using google appengine_1027Using google appengine_1027
Using google appengine_1027
 
zend framework in web services
zend framework in web serviceszend framework in web services
zend framework in web services
 
行動商務實務 - PhoneGap Advance
行動商務實務 - PhoneGap Advance行動商務實務 - PhoneGap Advance
行動商務實務 - PhoneGap Advance
 

Google cloud message by sean

  • 1. Google Cloud Message (GCM) 完整使用教學 目錄 GCM 溝通流程------------------------------------02 如何申請 GCM------------------------------------03 Client 端程式撰寫-------------------------------06 Server 端程式撰寫(for PHP)----------------------10 1
  • 2. GCM 溝通流程 名詞解釋 Sender ID : 也就是 progect ID 此組序號就是代表你目前的專案號碼 API KEY : 這是第三方(也就是自己的 server)與 Google 溝通的序號 Register Id : android 跟 Google 註冊後取得的 ID 流程 1. android 必須先使用 Sender ID 和 Google 註冊,若註冊完畢 Google 會給你一 組 Register Id 2. android 再將此 id 存在自己 server 的資料庫上 之後若是 server 需要 , 發送訊息給該 android 用戶,就可以藉著此 ID 去告訴 Google 他要發送給 誰,當然必須配上當初申請的 API KEY (註冊流程圖如下) Sender ID Android Google Register Id Register Id 存入 Server Server (發送訊息流程圖) Server Google Android 發送對象的 ID 傳送 Message API KEY 到該使用者 Message 2
  • 3. 如何申請 GCM 進入 https://code.google.com/apis/console/ 登入 Google 帳號後會進入這樣畫面 在網址列後方#project:125242748039 後面的號碼就是該專案的 Sender ID(紅字) 之後在畫面左邊點選 Service 開啟 GCM 服務 3
  • 4. 再點選畫面左邊的 API Access 點選 Create new Server KEY 在 IP 位置上填入自己 Server 的 ip 或是 address 4
  • 5. 按下 Create 後,你就會發現會新增一筆資料 這就是本專案 Server 專屬的 API KEY 之後就可以動手程式的撰寫。 5
  • 6. Client 端 抓取 GCM 的 jar 檔 eclipse 必須要 ADT 20 以上 在 eclispe 點選 Windows → Extras → Google Cloud Messaging for Android 安裝後,就可以從此檔案抓出 GCM 的 library。 import 程式庫到新專案 建議將程式庫加到專案底下的 lib 資料夾裡,以便後續換電腦開發時才不會找不 到程式庫。(直接在你專案底下開一個 lib 資料夾,然後把.jar 放入即可) 程式庫位置在 程式庫位置在 Android/android-sdk-windows/extras/google/gcm/gcm-client/dist/gcm.jar 到你的專案裡, 知道位置後就可以 import 到你的專案裡,如果 jar 檔是在 lib 裡 Properties→Java Build Path→Add JARs→專案名稱→lib→gcm.jar 如果 jar 檔不是在專案的 lib 裡 Properties→Java Build Path→Add External JARs→選擇檔案 AndroidManifest.xml 使用 GCM 必須在 2.2 版以上才能運行(Version 8 以上) <uses-sdk android:minSdkVersion="8" /> 你的專案套件佔有很大的影響關鍵, 你的專案套件佔有很大的影響關鍵 請記得所有關於 GCM 的開發都必須在套件底 , 下 package="com.chinebank.Activity" 如果你的套件名稱如以上, 的程式碼撰寫就必須在此底下,否則會無法向 如果你的套件名稱如以上,GCM 的程式碼撰寫就必須在此底下,否則會無法向 Google 取得註冊 ID 必須開啟以下權限 <!-- GCM --> <permission android:name="你的專案套件名稱.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="你的專案套件名稱.permission.C2D_MESSAGE" /> <!-- App receives GCM messages. --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <!-- GCM requires a Google account. --> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> 6
  • 7. <!-- Keeps the processor from sleeping when a message is received. --> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.INTERNET" /> 使用 GCM 接收與發送訊息相關套件與方法 <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="你的專案套件" /> </intent-filter> </receiver> 因為會撰寫一個 Service 所有要讓 android 知道 <service android:name=".GCMIntentService" /> GCMIntentService.java 必須繼承 GCMBaseIntentService 他會 Override 四種方式 package com.chinebank.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; import android.widget.Toast; import com.google.android.gcm.GCMBaseIntentService; public class GCMIntentService extends GCMBaseIntentService{ public static final String SENDER_ID = "你的 SenderID"; 7
  • 8. public GCMIntentService(){ super(SENDER_ID); } @Override protected void onError(Context mContext, String error) { // TODO Auto-generated method stub //訊息接收錯誤後做的處理 } @Override protected void onMessage(Context mContext, Intent msg) { //收到訊息後做後續處理 message = msg.getExtras().getString("message"); Class = msg.getExtras().getString("storeClass"); topic = msg.getExtras().getString("storeChineseTopic"); storeClass = msg.getExtras().getString("storeEnglishTopic"); storeName = msg.getExtras().getString("storeName"); saveExtra(); //取得通知權限 NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(NOTIFICATION_SERVICE); //按下通知後要過去的 activity Intent i = new Intent(mContext,ChineTravelActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent appIntent=PendingIntent.getActivity(this,0,i,0); //設定通知內容 Notification notification = new Notification(); notification.icon = R.drawable.icon2; //圖示 notification.tickerText = getString(R.string.notification_name);//顯示 notification.defaults = Notification.DEFAULT_VIBRATE; //震動 notification.setLatestEventInfo(mContext, getString(R.string.notification_name), message, appIntent); //內容 標題 要轉換的 intent notificationManager.notify(0,notification); 8
  • 9. } @Override protected void onRegistered(Context mContext, String arg1) { //收到註冊 ID 後要做的事 } @Override protected void onUnregistered(Context mContext, String arg1) { // 若取消註冊 ID 後要做的事 } } Activity.java public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //確認此app有開通GCM權限,如果沒有就會拋出異常 GCMRegistrar.checkDevice(this); //發送自己的Sender ID到google註冊 GCMRegistrar.register(this, GCMIntentService.SENDER_ID); //取到ID後就可以把ID存入server資料庫 String regId = GCMRegistrar.getRegistrationId(this); } 9
  • 10. Server 端 <?php //request url $url = 'https://android.googleapis.com/gcm/send'; //your api key $apiKey = '我們剛剛申請的 API KEY'; //registration ids $registrationIDs = array('android 得到的 registrationID'); //payload data $data = array('message' => 'Hello'); $fields = array('registration_ids' => $registrationIDs, 'data' => $data); 上面 fields 包裝成 JSON 就會是以下 { “registration_ids”:”android 註冊得到的 ID”, “data”:[“message”:”Hello”] } //http header //在 headers 要設定當初在 Google 註冊的 API KEY 與你要包裝給 Google 是甚 麼格式 $headers = array('Authorization: key=' . $apiKey, 'Content-Type: application/json'); //curl connection $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 10
  • 11. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); //轉換 JSON 格式,發出至 Google $result = curl_exec($ch); curl_close($ch); echo $result; //當然 Google 也會回你一個 response //如果發送失敗他也會跟你說 ?> 11