2011-11-28 46 views
2

我已經嘗試過使用c2dm,它的工作原理和我收到的消息(我打印簡單的吐司)。如何將通知設置爲與gmail的通知相同,例如,在通知區域顯示我時,右上角會顯示新的消息?有沒有這個或API的標誌? (在momemnt我在代碼中獲取消息,通過鍵從意圖提取並顯示吐司,但通知區域中沒有任何內容)。C2DM在gmail的通知區域顯示通知

回答

4

在從C2DMBaseReceiver擴展的C2DMReceiver類中。把下面的代碼放在覆蓋函數onMessage下,並且寫一個名爲createNotification()的函數,它在下面給出。

@Override 
protected void onMessage(Context context, Intent intent) {  
    Bundle extras = intent.getExtras(); 
    if (extras != null) { 
     String msg = extras.getString("data.c2dmsg"); 
     String msgTitle = extras.getString("data.c2dmsgtitle"); 
     String msgTicker = extras.getString("data.c2dmsgticker"); 
     createNotification(msgTitle, msg, msgTicker); 
    } 
} 


public void createNotification(String title, String messageText, String tickerttext) { 
     int icon = R.drawable.ic_stat_notify_msg; // icon from resources 
     CharSequence tickerText = tickerttext; // ticker-text 
     long when = System.currentTimeMillis(); // notification time 
     Context context = getApplicationContext(); // application Context 
     CharSequence contentTitle = title; // expanded message title 
     CharSequence contentText = messageText; // expanded message text 
     Intent notificationIntent = new Intent(this, HomekhawarActivity.class); 

     Bundle xtra = new Bundle(); 
     xtra.putString("title", title); 
     xtra.putString("message", messageText); 

     notificationIntent.putExtras(xtra); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
     notificationIntent, PendingIntent.FLAG_ONE_SHOT 
      + PendingIntent.FLAG_UPDATE_CURRENT); 
     String ns = Context.NOTIFICATION_SERVICE; 

     NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 
     Notification notification = new Notification(icon, tickerText, when); 
     notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
     notification.defaults |= Notification.DEFAULT_LIGHTS; 
     notification.defaults |= Notification.DEFAULT_SOUND; 
     notification.defaults |= Notification.FLAG_AUTO_CANCEL; 
     notification.flags = Notification.DEFAULT_LIGHTS 
     | Notification.FLAG_AUTO_CANCEL; 
     final int HELLO_ID = rand.nextInt(); 
     mNotificationManager.notify(HELLO_ID, notification); 
    }