Android - GCM推送通知未出现在通知列表中

Jon*_*ham 6 java notifications android push-notification google-cloud-messaging

我正在开发我的第一个Android应用,以使用Google云消息传递(GCM)服务进行推送通知.我已经到了可以从我的服务器应用程序成功发送消息的位置,并在客户端应用程序上的GCMIntentService类中的onMessage事件中记录消息的内容.但是,我没有在设备上看到任何收到消息的可视指示.我期待这条消息出现在手机的下拉通知列表中,就像在iPhone上一样.这是否必须手动编码?还有一种显示消息的常用方法,无论当前哪个活动处于活动状态,以及应用程序是否在后台处于空闲状态?任何帮助赞赏.

Zac*_*sky 7

此代码将在屏幕顶部的android系统栏中生成通知.此代码将创建一个新的intent,在单击顶部栏中的通知后将用户定向到"Home.class".如果您希望它根据当前活动执行某些特定操作,您可以将GCMIntentService的广播请求发送到您的其他活动.

Intent notificationIntent=new Intent(context, Home.class);
generateNotification(context, message, notificationIntent);

private static void generateNotification(Context context, String message, Intent notificationIntent) {
    int icon = R.drawable.icon;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);

    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent =PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);
}
Run Code Online (Sandbox Code Playgroud)

请注意,此示例使用R.drawable和R.String中的资源,这些资源需要存在才能工作,但它应该为您提供想法.有关状态通知http://developer.android.com/guide/topics/ui/notifiers/index.html以及有关广播接收器的详细信息,请参阅此处.http://developer.android.com/reference/android/content/BroadcastReceiver.html