Android GCM(Google Cloud Messaging) Client&Server端建置筆記

  • 0
最低需求2.3
模擬器測試最低需求4.2.2
1.Google API Library下載
開發環境請先下載Google APIs的library,把 /extras/google/google_play_services/libproject/google-play-services_lib/複製到你的專案資料夾底下,再Import進專案,File > Import, select Android > Existing Android Code into Workspace。可以參考Android官方

2.在AndroidManifest.xml,設定google api
然後在AndroidManifest.xml裡的Application加入
    <meta-data android:name=“com.google.android.gms.version" android:value="@integer/google_play_services_version" />

3.建立Google APIs專案,取得伺服器應用程式的金鑰
請先到Google APIs建立專案給GCM用,並建立一組「伺服器應用程式的金鑰」,產生的金鑰用來讓PHP發送Message用的。
https://console.developers.google.com/project
4.設定AndroidManifest.xml新增App背景服務與權限
在AndroidManifest.xml裡,設定以下權限
    <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.GET_ACCOUNTS" />     <uses-permission android:name="android.permission.WAKE_LOCK" />     <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />     <permission android:name=“com.app.yourapp.permission.C2D_MESSAGE"         android:protectionLevel="signature" />     <uses-permission android:name=“com.app.yourapp.permission.C2D_MESSAGE" />

裡面
同樣設定一些服務
    <receiver android:name=".GcmBroadcastReceiver” android:permission="com.google.android.c2dm.permission.SEND" >             <intent-filter >                 <action android:name="com.google.android.c2dm.intent.RECEIVE" />                 <category android:name=“com.app.yourapp" />             </intent-filter >     </receiver= >     <service android:name=".GcmIntentService" />

5.主程式MainActivity
宣告一個字串,這串數字是Google APIs專案中的專案編號。
String SENDER_ID “123456789”;

在OnCreate加入,主要判斷是不是有playerServices,及App有沒有取得RegistrationId。
        context = getApplicationContext();         //  GCM registration.         if (checkPlayServices()) {             gcm = GoogleCloudMessaging.getInstance(this);             regid = getRegistrationId(context);             if (regid.isEmpty()) {                 registerInBackground();             }             Log.d(TAG,"Regid"+regid);         } else {             Log.d(TAG, "No valid Google Play Services APK found.");         }

新增GcmIntentService繼承IntentService, 處理App通知收到後要做什麼事。
實際程式碼請參考Android Developer

新增GcmBroadcastReceiver繼承WakefulBroadcastReceiver, 這支程式要幹嘛不曉得,應該是常駐在背景,等待接收通知用的(請有緣人解釋給我聽)。

6.完成以上步驟,實際測試。
也可以用Simulator測試,只要把Simulator的Target設定成Google Api即可。

7.PHP Server端原始碼
//------------------------------
// The recipient registration IDs
// that will receive the push
// (Should be stored in your DB)
//
// Read about it here:
// http://developer.android.com/google/gcm/
//------------------------------

$data = array('title' => $title, 'message' => $message );
$ids = array($registration_id);
//------------------------------
// Call our custom GCM function
//------------------------------

sendGoogleCloudMessage(  $data, $ids );

//------------------------------
// Define custom GCM function
//------------------------------

function sendGoogleCloudMessage( $data, $ids )
{
//------------------------------
// Replace with real GCM API
// key from Google APIs Console
//
// https://code.google.com/apis/console/
//------------------------------

$apiKey = '金鑰'; // 貼上步驟3的伺服器應用程式的金鑰」

//------------------------------
// Define URL to GCM endpoint
//------------------------------

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

//------------------------------
// Set GCM post variables
// (Device IDs and push payload)
//------------------------------

$post = array(
'registration_ids'  => $ids,
'data'              => $data,
);

//------------------------------
// Set CURL request headers
// (Authentication and type)
//------------------------------

$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);

//------------------------------
// Initialize curl handle
//------------------------------

$ch = curl_init();

//------------------------------
// Set URL to GCM endpoint
//------------------------------

curl_setopt( $ch, CURLOPT_URL, $url );

//------------------------------
// Set request method to POST
//------------------------------

curl_setopt( $ch, CURLOPT_POST, true );

//------------------------------
// Set our custom headers
//------------------------------

curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );

//------------------------------
// Get the response back as
// string instead of printing it
//------------------------------

curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

//------------------------------
// Set post data as JSON
//------------------------------

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

//------------------------------
// Actually send the push!
//------------------------------

$result = curl_exec( $ch );

//------------------------------
// Error? Display it!
//------------------------------

if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}

//------------------------------
// Close curl handle
//------------------------------

curl_close( $ch );

//------------------------------
// Debug GCM response
//------------------------------
echo $result;
}







沒有留言: