2013年2月9日 星期六

使用GCM服務(六) 設計GCM應用程式(2)

在使用GCM服務(五) 設計GCM應用程式(1)文中已建立GCMIntentService程式框架,接著必須實作GCMIntentService類別程式碼。
(1). 在建構元中將在Google APIs Console建立Project編號當做Sender ID,傳給GCMBaseIntentService類別。

  public GCMIntentService(){
     super("Your_Sender_ID");
  }

(2). 向GCM Server註冊並取得裝置的registration Id後,GCMBroadcastReceiver會調用onRegistered(),在此須同步向訊息推播伺服器登錄裝置的registration Id。

  @Override
  protected void onRegistered(Context context, String regId) {
        /**
         * 撰寫程式碼向訊息推播伺服器登錄regId,例如
         * register(context, regId);
         * */       
        GCMRegistrar.setRegisteredOnServer(context, true);
  }

(3). 向GCM Server註銷裝置後,GCMBroadcastReceiver會調用onUnregistered(),在此須同步向訊息推播伺服器取消登錄裝置的registration Id。

  @Override
  protected void onUnregistered(Context context, String regId) {
        /**
         * 在此應撰寫程式碼向訊息推播伺服器取消登錄regId,例如
         * unregister(context, regId);
         * */       
        GCMRegistrar.setRegisteredOnServer(context, false);
  }

(4). 收到GCM Server送來的推播訊息時,GCMBroadcastReceiver會調用onMessage(),在此透過Notification通知用戶。

  @Override
  protected void onMessage(Context context, Intent intent) {
     //取出訊息payload內容
     String contentTitle = intent.getStringExtra("contentTitle");  
     String contentText = intent.getStringExtra("contentText");
    //在裝置狀態列顯示Notification通知用戶
     generateNotification(context, contentTitle, contentText); 
    }
  private static void generateNotification(Context context,
     String contentTitle, String contentText) {
     NotificationManager notificationManager = (NotificationManager)
          context.getSystemService(Context.NOTIFICATION_SERVICE);
     Notification notification = new Notification(
       R.drawable.ic_launcher,
       contentTitle,
       System.currentTimeMillis());
     //設定notification要喚醒的Activity      
     Intent notificationIntent = new Intent(context, MainActivity.class);
     notificationIntent.setFlags(
       Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
     PendingIntent intent = PendingIntent.getActivity(
       context,
       0,
       notificationIntent,
       PendingIntent.FLAG_UPDATE_CURRENT);
     //設定notification內容
     notification.setLatestEventInfo(context, contentTitle, contentText, intent);
     //自動移除看過的notification
     notification.flags |= Notification.FLAG_AUTO_CANCEL;
     //發送notification
     notificationManager.notify( 0, notification);     
  }

最後是撰寫MainActivity類別程式碼,在onCreate()方法中進行以下作業:
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     //檢查裝置是否支援GCM
     GCMRegistrar.checkDevice(this);
     //檢查應用程式之AndroidMainfest.xml設定是否正確
     GCMRegistrar.checkManifest(this);
     //取得registration id
     final String regId = GCMRegistrar.getRegistrationId(this);
     if (regId.equals("")) {        //尚未註冊
       //GCM server註冊以取得registration id
       GCMRegistrar.register(this, "Your_Sender_ID");
     }
  }