C2DM在通知区域显示通知,如gmail

时间:2011-11-28 08:39:07

标签: android android-c2dm

我已经尝试过c2dm并且它正常工作我正在收到消息(我打印简单的吐司)。如何设置通知看起来像gmail的通知一样,例如,当我新的时候在右上角的通知区域显示我?这个或api有标志吗? (在momemnt我在代码中获取消息,通过密钥提取意图并显示吐司但通知区域中没有任何内容)。

1 个答案:

答案 0 :(得分:4)

在C2DMReceiver类中,从C2DMBaseReceiver扩展。将以下代码放在覆盖函数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);
    }