android - Pushwoosh 和 Android Phonegap 应用程序无法通信

标签 android cordova push-notification google-cloud-messaging pushwoosh

问题

好的,我有一个带有 Pushwoosh 的 Phonegap (2.3.0) android 应用程序来管理推送通知。我按照说明操作,得到了一个只有几个措辞错误的应用程序。该应用程序本身似乎运行得非常好,但是 Pushwoosh 似乎没有向 GCM(谷歌云信使)推送任何内容,而 GCM 也没有向该应用程序推送任何内容。现在我认为这是错误的,但这是我第一次使用 GCM 和 Pushwoosh。

在 Pushwoosh 控制台页面上,它显示每个“推送”都已完成且没有错误,但是在我的 GCM 控制台上它没有显示任何请求,我的手机上也没有弹出任何通知。

我的 XML 中有 GCM API key (服务器 key ),我的 Pushwoosh 是正确的 XXXXX-XXXXX key 。这是我的代码,可以更好地概述我的代码是如何设置的(也许有人可以看到我遗漏了什么)。


代码

这是 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<supports-screens
    android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:resizeable="true"
    android:anyDensity="true"
    />


<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />   
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<!--library-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET"/>

<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>

<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>

 <!--
Creates a custom permission so only this app can receive its messages.

NOTE: the permission *must* be called PACKAGE.permission.C2D_MESSAGE,
    where PACKAGE is the application's package name.
-->
<permission
     android:name="com.springmobile.employee.permission.C2D_MESSAGE"
     android:protectionLevel="signature"/>
<uses-permission
     android:name="com.springmobile.employee.permission.C2D_MESSAGE"/>

<!-- This app has permission to register and receive data message. -->
<uses-permission
     android:name="com.google.android.c2dm.permission.RECEIVE"/>



<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:allowBackup="true">

  <!--
Service for sending location updates
-->
<service android:name="com.arellomobile.android.push.GeoLocationService"/>
<intent-filter>
     <action android:name="com.springmobile.employee.MESSAGE"/>
     <category android:name="android.intent.category.DEFAULT"/>
 </intent-filter>
 <intent-filter>
     <action android:name="android.intent.action.MAIN"/>
     <category android:name="android.intent.category.LAUNCHER"/>
 </intent-filter>
    <activity android:name="com.arellomobile.android.push.PushWebview"/>

    <activity android:name="com.arellomobile.android.push.MessageActivity"/>

    <activity android:name="com.arellomobile.android.push.PushHandlerActivity"/>

    <!--
    BroadcastReceiver that will receive intents from GCM
    services and handle them to the custom IntentService.

    The com.google.android.c2dm.permission.SEND permission is necessary
    so only GCM services can send data messages for the app.
    -->
    <receiver
    android:name="com.google.android.gcm.GCMBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
    <!-- Receives the actual messages. -->
    <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
    <!-- Receives the registration id. -->
    <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
    <category android:name="com.springmobile.employee"/>
    </intent-filter>
    </receiver>

    <!--
    Application-specific subclass of PushGCMIntentService that will
    handle received messages.
    -->
    <service android:name="com.arellomobile.android.push.PushGCMIntentService"/>
    <activity android:name="org.apache.cordova.example.cordovaExample" android:label="@string/app_name"
            android:theme="@android:style/Theme.Black.NoTitleBar"
            android:configChanges="orientation|keyboardHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


这是我的 Phonegap 插件 config.XML

<plugins>
<plugin name="PushNotification" value="com.pushwoosh.plugin.pushnotifications.PushNotifications" onload="true"/>
</plugins>

这是我的 Phonegap 页面的 JS,用于初始化和监听 Pushwoosh 通知。

function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
pushNotification.onDeviceReady();

pushNotification.registerDevice({ projectid: "I_HAVE_MY_PROJECT_ID_HERE", appid : "THIS_IS_MY_PUSHWOOSH_ID" },
    function(status) {
        var pushToken = status;
        console.warn('push token: ' + pushToken);
    },
    function(status) {
        console.warn(JSON.stringify(['failed to register ', status]));
    }
);

document.addEventListener('push-notification', function(event) {
    var title = event.notification.title;
        var userData = event.notification.userdata;

        if(typeof(userData) != "undefined") {
        console.warn('user data: ' + JSON.stringify(userData));
    }

    navigator.notification.alert(title);
});
}

function init() {
document.addEventListener("deviceready", initPushwoosh, true);

//rest of the code
document.addEventListener('push-notification', function(event) {
    var title = event.notification.title;
        var userData = event.notification.userdata;

    console.warn('user data: ' + JSON.stringify(userData));
    navigator.notification.alert(title);
});
}

function initPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
pushNotification.onDeviceReady();

document.addEventListener('push-notification', function(event) {
                            var title = event.notification.title;
                            var userData = event.notification.userdata;

                            if(typeof(userData) != "undefined") {
                                console.warn('user data: ' + JSON.stringify(userData));
                            }

                            navigator.notification.alert(title);

                            pushNotification.stopGeoPushes();
                          });
}

function registerPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
//projectid: "GOOGLE_PROJECT_ID", appid : "PUSHWOOSH_APP_ID"
pushNotification.registerDevice({ projectid: "1039894503284", appid : "EE861-B95A3" },
                                function(token) {
                                    alert(token);
                                    onPushwooshInitialized(token);
                                },
                                function(status) {
                                    alert("failed to register: " +  status);
                                    console.warn(JSON.stringify(['failed to register ', status]));
                                });
}

function unregisterPushwoosh()
{
var pushNotification = window.plugins.pushNotification;
pushNotification.unregisterDevice(function(token) {
                                    alert("unregistered, old token " + token);
                                },
                                function(status) {
                                    alert("failed to unregister: " +  status);
                                    console.warn(JSON.stringify(['failed to unregister ', status]));
                                });
}

//set the settings for Pushwoosh or set tags, this must be called only after successful registration
function onPushwooshInitialized(pushToken)
{
//output the token to the console
console.warn('push token: ' + pushToken);

var pushNotification = window.plugins.pushNotification;

//set multi notificaiton mode
//pushNotification.setMultiNotificationMode();

//set single notification mode
//pushNotification.setSingleNotificationMode();

//disable sound and vibration
//pushNotification.setSoundType(1);
//pushNotification.setVibrateType(1);

pushNotification.setLightScreenOnNotification(false);

//goal with count
//pushNotification.sendGoalAchieved({goal:'purchase', count:3});

//goal with no count
//pushNotification.sendGoalAchieved({goal:'registration'});

//setting list tags
//pushNotification.setTags({"MyTag":["hello", "world"]});

//settings tags
pushNotification.setTags({deviceName:"hello", deviceId:10},
                                function(status) {
                                    console.warn('setTags success');
                                },
                                function(status) {
                                    console.warn('setTags failed');
                                });

function geolocationSuccess(position) {
    pushNotification.sendLocation({lat:position.coords.latitude, lon:position.coords.longitude},
                             function(status) {
                                  console.warn('sendLocation success');
                             },
                             function(status) {
                                  console.warn('sendLocation failed');
                             });
};

// onError Callback receives a PositionError object
//
function geolocationError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}

function getCurrentPosition() {
    navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
}

//greedy method to get user position every 3 second. works well for demo.
//  setInterval(getCurrentPosition, 3000);

//this method just gives the position once
//  navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);

//this method should track the user position as per Phonegap docs.
//  navigator.geolocation.watchPosition(geolocationSuccess, geolocationError, { maximumAge: 3000, enableHighAccuracy: true });

//Pushwoosh Android specific method that cares for the battery
pushNotification.startGeoPushes();
}

var app = {
// Application Constructor
initialize: function() {
    this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
    initPushwoosh();
    app.receivedEvent('deviceready');

    //optional: create local notification alert
    //var pushNotification = window.plugins.pushNotification;
//pushNotification.clearLocalNotification();
//pushNotification.createLocalNotification({"msg":"message", "seconds":30, "userData":"optional"});

},
// Update DOM on a Received Event
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');

    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');

    console.log('Received Event: ' + id);
}
};

这是 PushWoosh.js 代码

(function(cordova) {

function PushNotification() {}

// Call this to register for push notifications and retreive a deviceToken
PushNotification.prototype.registerDevice = function(config, success, fail) {
    cordova.exec(success, fail, "PushNotification", "registerDevice", config ? [config] : []);
};

// Call this to set tags for the device
PushNotification.prototype.setTags = function(config, success, fail) {
    cordova.exec(success, fail, "PushNotification", "setTags", config ? [config] : []);
};

// Call this to send geo location for the device
PushNotification.prototype.sendLocation = function(config, success, fail) {
    cordova.exec(success, fail, "PushNotification", "sendLocation", config ? [config] : []);
};

//Android Only----
PushNotification.prototype.unregisterDevice = function(success, fail) {
    cordova.exec(success, fail, "PushNotification", "unregisterDevice", []);
};

//config params: {msg:"message", seconds:30, userData:"optional"}
PushNotification.prototype.createLocalNotification = function(config, success, fail) {
    cordova.exec(success, fail, "PushNotification", "createLocalNotification", config ? [config] : []);
};

PushNotification.prototype.clearLocalNotification = function() {
    cordova.exec(null, null, "PushNotification", "clearLocalNotification", []);
};

//advanced background task to track device position and not drain the battery
PushNotification.prototype.startGeoPushes = function(success, fail) {
    cordova.exec(success, fail, "PushNotification", "startGeoPushes", []);
};

PushNotification.prototype.stopGeoPushes = function(success, fail) {
    cordova.exec(success, fail, "PushNotification", "stopGeoPushes", []);
};

//sets multi notification mode on
PushNotification.prototype.setMultiNotificationMode = function(success, fail) {
    cordova.exec(success, fail, "PushNotification", "setMultiNotificationMode", []);
};

//sets single notification mode
PushNotification.prototype.setSingleNotificationMode = function(success, fail) {
    cordova.exec(success, fail, "PushNotification", "setSingleNotificationMode", []);
};

//type: 0 default, 1 no sound, 2 always
PushNotification.prototype.setSoundType = function(type, success, fail) {
    cordova.exec(success, fail, "PushNotification", "setSoundType", [type]);
};  

//type: 0 default, 1 no vibration, 2 always
PushNotification.prototype.setVibrateType = function(type, success, fail) {
    cordova.exec(success, fail, "PushNotification", "setVibrateType", [type]);
};  

PushNotification.prototype.setLightScreenOnNotification = function(on, success, fail) {
    cordova.exec(success, fail, "PushNotification", "setLightScreenOnNotification", [on]);
};

//set to enable led blinking when notification arrives and display is off
PushNotification.prototype.setEnableLED = function(on, success, fail) {
    cordova.exec(success, fail, "PushNotification", "setEnableLED", [on]);
};

//{goal:'name', count:3} (count is optional)
PushNotification.prototype.sendGoalAchieved = function(config, success, fail) {
    cordova.exec(success, fail, "PushNotification", "sendGoalAchieved", config ? [config] : []);
};

//Android End----

//iOS only----
PushNotification.prototype.onDeviceReady = function() {
    cordova.exec(null, null, "PushNotification", "onDeviceReady", []);
};

// Call this to get a detailed status of remoteNotifications
PushNotification.prototype.getRemoteNotificationStatus = function(callback) {
    cordova.exec(callback, callback, "PushNotification", "getRemoteNotificationStatus", []);
};

// Call this to set the application icon badge
PushNotification.prototype.setApplicationIconBadgeNumber = function(badge, callback) {
    cordova.exec(callback, callback, "PushNotification", "setApplicationIconBadgeNumber", [{badge: badge}]);
};

// Call this to clear all notifications from the notification center
PushNotification.prototype.cancelAllLocalNotifications = function(callback) {
    cordova.exec(callback, callback, "PushNotification", "cancelAllLocalNotifications", []);
};
//iOS End----

// Event spawned when a notification is received while the application is active
PushNotification.prototype.notificationCallback = function(notification) {
    var ev = document.createEvent('HTMLEvents');
    ev.notification = notification;
    ev.initEvent('push-notification', true, true, arguments);
    document.dispatchEvent(ev);
};

cordova.addConstructor(function() {
    if(!window.plugins) window.plugins = {};
    window.plugins.pushNotification = new PushNotification();
});

})(window.cordova || window.Cordova || window.PhoneGap);

GCM、Pushwoosh 和 Eclipse 截图

抱歉,这太长了,但我想确保我拥有这里的一切。也没有足够的代表发布图片,所以链接如下。

GCM API server key, Pushwoosh Control Panel, and Eclipse setup


谢谢!

最佳答案

check您的配置和设置适用于推送 woosh 通知。 Other推送通知服务也可以在 phone-gap 中使用,您可以查看它。您可以找到 phone gap 代码 (zip)、适当的配置和设置文档以及如何使用 Java 脚本使用它们的 API

关于android - Pushwoosh 和 Android Phonegap 应用程序无法通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15823134/

相关文章:

Android Fragment,返回而不重新创建/重新加载 Fragment

javascript - Cordova CLI 6.3.0 window.plugins 未定义

android - Cordova 地理定位不适用于 Android

android - 检查 AsyncTask 是否花费太长的时间

Android 设计库 23.1.0 NavigationView

android - 使用 RxJava 遍历 ViewGroup child

ios - CompileXIB 的 Phonegap (Cordova) 错误

ios - ionic io : push on ios failing to register

firebase - 将 PWA 安装到主屏幕后,我的通知徽章图标未显示

email - 发送包含许多大附件的电子邮件时,Gmail API 推送通知过多