如何在使用 GCMReceiver 和 GcmListenerService 时自定义通知显示和提示音

How to customize notification display and tone when using GCMReceiver and GcmListenerService

我已按照说明设置 Android GCM 客户端应用程序 here,但我对这段摘录有疑问:

For existing apps that extend a WakefulBroadcastReceiver, Google recommends migrating to GCMReceiver and GcmListenerService. To migrate: In the app manifest, replace your GcmBroadcastReceiver with "com.google.android.gms.gcm.GcmReceiver", and replace the current service declaration that extends IntentService to the new GcmListenerService Remove the BroadcastReceiver implementation from your client code Refactor the current IntentService service implementation to use GcmListenerService

我见过的大多数 GCM 实施示例都使用扩展 WakefulBroadcastReceiver 的 class。比如this one。当您这样做时,您将有机会使用 NotificationManager 并自定义通知图标、声音等。但是,如果您遵循 Google 的建议,我不确定如何自定义通知。大多数使用 Google 所建议的 GcmListenerService 的示例,只需覆盖 onMessageReceived 方法即可。但是只有在收到通知时应用程序已经在前台或者用户单击通知本身时才会调用该方法。该方法不是自定义通知声音的正确位置。在调用该方法之前已经播放了声音。

因此,如果我需要自定义通知声音,我可能应该重写 GcmListenerService 中的另一种方法,但没有说明是哪一种方法的文档。另一种选择是使用 here 描述的 sound 属性。但是您必须自己将声音文件捆绑到应用程序的 res/raw 目录中。这似乎是错误的。我宁愿只使用系统提供的声音、主题等

想法?

我只能看到可能的选项是通过由两个 XMPP and HTTP 连接服务器处理的负载(如您所指出的)。我不确定为什么这对你来说似乎是错误的,因为服务器将在有效负载中定义 sound 数据,而客户端只需要文件出现在它应该存在的相应资产文件夹中。

显示自定义也可以通过通知有效负载完成(尽管它仅限于 coloricon

@SamStern answered this question for me, when I posted it on a Google Samples github wiki:

So there are two kinds of GCM messages:

Notification Messages - these are intended to generate a notification with no intermediate processing by the application. They only hit onMessageReceived if the app is running.

Data Messages - these are intended to silently pass data to the app's messaging service. They hit onMessageReceived even if the app is in the background. The service may then choose to generate a notification using the normal system notification APIs, or it may choose to handle the message silently.

我的结论是,如果客户端应用想要自定义向用户显示通知的方式(即更改通知托盘中的图标、根据应用共享首选项中的声音设置播放声音等),然后我们必须让服务器发送 "Data Messages" 而不是 "Notification Messages"。 Here's Google 示例项目中的实现,展示了如何处理数据消息。