2013年2月8日 星期五

使用GCM服務(五) 設計GCM應用程式(1)

1. 建立GCM Client專案,注意!GCM只適用Android 2.2以上版本。
2. 將GCM library(android sdk目錄下之\extras\google\gcm\gcm-client\dist\gcm.jar檔)複製到GCM Client專案的libs目錄下。
3. 開啟AndroidManifest.xml檔,加入以下宣告(如果是Android 4.1以上版本專案,則不需要這個步驟),其中my_app_package必須替換為專案套件名稱。

  <permission android:name="my_app_package.permission.C2D_MESSAGE"
     android:protectionLevel="signature" />
  <uses-permission
     android:name="my_app_package.permission.C2D_MESSAGE" />

4. 在AndroidManifest.xml檔中加入以下使用權限宣告。

  <uses-permission
     android:name="com.google.android.c2dm.permission.RECEIVE" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />

5. 在AndroidManifest.xml之內宣告GCM receiver(由GCM library提供),負責處理由GCM system framework送出的com.google.android.c2dm.intent.RECEIVE以及com.google.android.c2dm.intent.REGISTRATION二種intent作業。
其中<category>的name屬性值(my_app_package)必須替換為專案套件名稱,但如果是Android 4.1以上版本專案,則不需要宣告<category>標籤。

  <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="my_app_package" />
     </intent-filter>
  </receiver>

6. 在AndroidManifest.xml之內加入以下的intent service宣告:
  <service android:name=".GCMIntentService" />
在此的name屬性值為繼承自com.google.android.gcm.GCMBaseIntentService的自訂Service類別名稱,當GCMBroadcastReceiver收到推播訊息時就會調用這個intent service。

7. 建立GCMIntentService類別框架

public class GCMIntentService extends GCMBaseIntentService {
  public GCMIntentService() {
     // TODO Auto-generated constructor stub
  }
  public GCMIntentService(String... senderIds) {
     super(senderIds);
     // TODO Auto-generated constructor stub
  }
  @Override
  protected void onError(Context arg0, String arg1) {
     // TODO Auto-generated method stub
  }
  @Override
  protected void onMessage(Context arg0, Intent arg1) {
     // TODO Auto-generated method stub
  }
  @Override
  protected void onRegistered(Context arg0, String arg1) {
     // TODO Auto-generated method stub
  }
  @Override
  protected void onUnregistered(Context arg0, String arg1) {
     // TODO Auto-generated method stub
  }
}