我正在使用 PushPlugin对于 cordova,在 android 中,当应用程序未运行或处于后台时,我无法让推送通知播放声音(状态栏中的横幅显示正常)。 这是在 android 推送通知上调用的函数-
function onNotification(e) {
.
.
.
case 'message':
{
var myMedia = new Media("/android_asset/www/res/raw/tritone.mp3");
myMedia.play({ numberOfLoops: 2 })
应用程序在前台运行时声音播放正常。
这是在我处于前台时收到推送后函数“onNotification(e)”的“e”参数值(确实可以正常播放声音)-
{
"message":"body text...",
"payload":{
"message":"body text...",
"soundname":"/android_asset/www/res/raw/tritone.mp3",
"title":"sometitle"
},
"collapse_key":"do_not_collapse",
"from":"969601086761",
"soundname":"/android_asset/www/res/raw/tritone.mp3",
"foreground":true,
"event":"message"
}
我有一种感觉,当应用程序未运行或处于后台时,根本不会调用“function onNotification(e)” block 。
最后,我想要的非常简单 - 在应用未运行或应用处于后台时在推送通知上播放自定义声音文件。/p>
提前致谢。
最佳答案
我观察了 Cordova PushPlugin 添加到 android 平台项目的 java 代码,查看文件“GCMIntentService”。在“onMessage”函数中,我看到了这个-
if (PushPlugin.isInForeground()) {
extras.putBoolean("foreground", true);
PushPlugin.sendExtras(extras);
}
else {
extras.putBoolean("foreground", false);
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
createNotification(context, extras);
}
}
然后就清楚了,看到PushPlugin.sendExtras(extras)
这行了吗?这是在 javascript webview 端触发代码的行。
您可能已经注意到,问题是只有当应用 isInForeground()
时才会调用此行。
起初,我想我也应该在 else
block 中添加这一行,就在 extras.putBoolean("foreground", false)
行的下方,但是仅在应用程序实际处于后台的情况下才有用,如果应用程序根本没有运行则无济于事。
出于上述原因,我将简单地用 Java 代码播放音频文件,就像这样(经过测试和工作)-
if (PushPlugin.isInForeground()) {
extras.putBoolean("foreground", true);
PushPlugin.sendExtras(extras);
}
else {
extras.putBoolean("foreground", false);
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.mytone);
mediaPlayer.start();
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
createNotification(context, extras);
}
}
它有效,但它不是一个完美的解决方案,我宁愿在后台处理通知或在我的 web View 中的 JAVASCRIPT 代码内销毁通知,而不是在 Java 中。希望此功能将添加到 PushPlugin。
也许至少他们可以在调用 createNotification(Context context, Bundle extras)
时为“soundname”添加一个参数,这对我来说也是一个足够好的解决方案插件。
澄清:
我使用下面的代码来播放通知声音文件名:
String soundName = extras.getString("soundname");
AssetFileDescriptor afd = getAssets().openFd(soundName);
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.start();
在服务器端,我会在为 Android 发送时传递一个如下所示的 JSON(iOS 有不同的 key ):
{
...
soundname: 'www/res/raw/yoursoundfile.mp3'
...
}
关于android - Cordova PushPlugin : Android won't play push sound while app not running,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24876092/