google cloud message by sean

11
1 Google Cloud Message (GCM) 完整使用教學 目錄 GCM 溝通流程------------------------------------02 如何申請 GCM------------------------------------03 Client 端程式撰寫-------------------------------06 Server 端程式撰寫(for PHP)----------------------10

Upload: sean-lee

Post on 19-May-2015

5.161 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Google cloud message by sean

1

Google Cloud Message (GCM) 完整使用教學

目錄

GCM 溝通流程------------------------------------02

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

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

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

Page 2: Google cloud message by sean

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

(註冊流程圖如下)

(發送訊息流程圖)

Android Google

Sender ID

Register Id

Server

Register Id

存入 Server

Server Google

發送對象的 ID

API KEY

Message

Android

傳送 Message

到該使用者

Page 3: Google cloud message by sean

3

如何申請 GCM

進入 https://code.google.com/apis/console/

登入 Google 帳號後會進入這樣畫面

在網址列後方#project:125242748039 後面的號碼就是該專案的 Sender ID(紅字)

之後在畫面左邊點選 Service 開啟 GCM 服務

Page 4: Google cloud message by sean

4

再點選畫面左邊的 API Access

點選 Create new Server KEY

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

Page 5: Google cloud message by sean

5

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

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

Page 6: Google cloud message by sean

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

知道位置後就可以知道位置後就可以知道位置後就可以知道位置後就可以 importimportimportimport 到你的專案裡到你的專案裡到你的專案裡到你的專案裡,,,,如果如果如果如果 jarjarjarjar 檔是在檔是在檔是在檔是在 liblibliblib 裡裡裡裡

Properties→Java Build Path→Add JARs→專案名稱→lib→gcm.jar

如果如果如果如果 jarjarjarjar 檔檔檔檔不是在專案的不是在專案的不是在專案的不是在專案的 liblibliblib 裡裡裡裡

Properties→Java Build Path→Add External JARs→選擇檔案

AndroidManifest.xml

使用 GCM 必須在 2.2 版以上才能運行(Version 8 以上)

<uses-sdk android:minSdkVersion="8" />

你的專案套件佔有很大的影響關鍵你的專案套件佔有很大的影響關鍵你的專案套件佔有很大的影響關鍵你的專案套件佔有很大的影響關鍵,,,,請記得所有關於請記得所有關於請記得所有關於請記得所有關於 GCMGCMGCMGCM 的開發都必須在套件底的開發都必須在套件底的開發都必須在套件底的開發都必須在套件底

下下下下 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" />

Page 7: Google cloud message by sean

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";

Page 8: Google cloud message by sean

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);

Page 9: Google cloud message by sean

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);

}

Page 10: Google cloud message by sean

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);

//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);

上面 fields 包裝成 JSON 就會是以下

{

“registration_ids”:”android 註冊得到的 ID”,

“data”:[“message”:”Hello”]

}

Page 11: Google cloud message by sean

11

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

//轉換 JSON 格式,發出至 Google

$result = curl_exec($ch);

curl_close($ch);

echo $result;

//當然 Google 也會回你一個 response

//如果發送失敗他也會跟你說

?>