如何使用phonegap推送插件进行状态栏通知

时间:2013-11-15 12:11:41

标签: android cordova push-notification

我使用手机间隙推送插件它对我来说很好,以及从我的服务器获取消息。 我有两个问题,如果有人可以更新代码或需要更改代码的代码必须得到赞赏。

我按照此链接显示应用在后台时的通知你可以看到它。

http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/

注意这个文件我收到了但是有两件事情并没有像我在两个问题中提到的那样。

  1. 收到消息后,我显示的消息计数未定义。

  2. 我希望如果我的应用程序在后台运行,那么状态栏会像其他应用程序一样显示通知。

  3. 的index.html

    <!DOCTYPE HTML>
    <html>
        <head>
            <title>com.PhoneGap.c2dm</title>
        </head>
        <body>
    
            <script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
            <script type="text/javascript" charset="utf-8" src="jquery_1.5.2.min.js"></script>
            <script type="text/javascript" charset="utf-8" src="js/main.js"></script>
            <script type="text/javascript" charset="utf-8" src="js/service.js"></script>
            <script type="text/javascript" src="PushNotification.js"></script>
    
            <script type="text/javascript">
                var pushNotification;
    
                function onDeviceReady() {
                    $("#app-status-ul").append('<li>deviceready event received</li>');
    
    
                    try 
                    { 
                        pushNotification = window.plugins.pushNotification;
                        if (device.platform == 'android' || device.platform == 'Android') {
                            $("#app-status-ul").append('<li>registering android</li>');
                            pushNotification.register(successHandler, errorHandler, {"senderID":"XXXXXXX","ecb":"onNotificationGCM"});      // required!
                        } else {
                            $("#app-status-ul").append('<li>registering iOS</li>');
                            pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});    // required!
                        }
                    }
                    catch(err) 
                    { 
                        txt="There was an error on this page.\n\n"; 
                        txt+="Error description: " + err.message + "\n\n"; 
                        alert(txt); 
                    } 
                }
    
                // handle APNS notifications for iOS
                function onNotificationAPN(e) {
                    if (e.alert) {
                         $("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
                         navigator.notification.alert(e.alert);
                    }
    
                    if (e.sound) {
                        var snd = new Media(e.sound);
                        snd.play();
                    }
    
                    if (e.badge) {
                        pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
                    }
                }
    
                // handle GCM notifications for Android
                function onNotificationGCM(e) {
                    $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');
    
    
                    switch( e.event )
                    {
                        case 'registered':
                        if ( e.regid.length > 0 )
                        {
                            $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
                            // Your GCM push server needs to know the regID before it can push to this device
                            // here is where you might want to send it the regID for later use.
    
    
    
                        }
                        break;
    
                        case 'message':
                            // if this flag is set, this notification happened while we were in the foreground.
                            // you might want to play a sound to get the user's attention, throw up a dialog, etc.
                            if (e.foreground)
                            {
                                $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');
    
                                // if the notification contains a soundname, play it.
                                var my_media = new Media("/android_asset/www/"+e.soundname);
                                my_media.play();
                            }
                            else
                            {   // otherwise we were launched because the user touched a notification in the notification tray.
                                if (e.coldstart)
                                    $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
                                else
                                $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
                            }
    
                            $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
                            $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
                        break;
    
                        case 'error':
                            $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
                        break;
    
                        default:
                            $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
                        break;
                    }
                }
    
                function tokenHandler (result) {
                    $("#app-status-ul").append('<li>token: '+ result +'</li>');
                    // Your iOS push server needs to know the token before it can push to this device
                    // here is where you might want to send it the token for later use.
                }
    
                function successHandler (result) {
                    $("#app-status-ul").append('<li>success:'+ result +'</li>');
                }
    
                function errorHandler (error) {
                    $("#app-status-ul").append('<li>error:'+ error +'</li>');
                }
    
                document.addEventListener('deviceready', onDeviceReady, true);
    
             </script>
            <div id="home">
                <div id="app-status-div">
                    <ul id="app-status-ul">
                        <li>Cordova PushNotification Plugin Demo</li>
                    </ul>
                    <button id="sendRegistrationID">Save Registration ID</button>
                    <button id="getRegistrationID">Get Registration ID</button>
                </div>
            </div>
        </body>
    </html>
    

    GCMINtentService.js

    package com.plugin.gcm;
    
    import java.util.List;
    
    import com.google.android.gcm.GCMBaseIntentService;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.annotation.SuppressLint;
    import android.app.ActivityManager;
    import android.app.ActivityManager.RunningTaskInfo;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    
    @SuppressLint("NewApi")
    public class GCMIntentService extends GCMBaseIntentService {
    
        public static final int NOTIFICATION_ID = 237;
        private static final String TAG = "GCMIntentService";
    
        public GCMIntentService() {
            super("GCMIntentService");
        }
    
        @Override
        public void onRegistered(Context context, String regId) {
    
            Log.v(TAG, "onRegistered: "+ regId);
    
            JSONObject json;
    
            try
            {
                json = new JSONObject().put("event", "registered");
                json.put("regid", regId);
    
                Log.v(TAG, "onRegistered: " + json.toString());
    
                // Send this JSON data to the JavaScript application above EVENT should be set to the msg type
                // In this case this is the registration ID
                PushPlugin.sendJavascript( json );
    
            }
            catch( JSONException e)
            {
                // No message to the user is sent, JSON failed
                Log.e(TAG, "onRegistered: JSON exception");
            }
        }
    
        @Override
        public void onUnregistered(Context context, String regId) {
            Log.d(TAG, "onUnregistered - regId: " + regId);
        }
    
        @SuppressWarnings("deprecation")
        @Override
        protected void onMessage(Context context, Intent intent) {
            Log.d(TAG, "onMessage - context: " + context);
    
    
    
            // Extract the payload from the message
            Bundle extras = intent.getExtras();
            if (extras != null)
            {
                PushPlugin.sendExtras(extras);
    
                // Send a notification if there is a message and not in foreground
                if (!PushPlugin.isInForeground() && extras.getString("message").length() != 0) {
                    createNotification(context, extras);
                }
            }
        }
    
        public void createNotification(Context context, Bundle extras)
        {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            String appName = getAppName(this);
    
            Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
            notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            notificationIntent.putExtra("pushBundle", extras);
    
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    
            NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setSmallIcon(context.getApplicationInfo().icon)
                    .setWhen(System.currentTimeMillis())
                    .setContentTitle(extras.getString("title"))
                    .setTicker(extras.getString("title"))
                    .setContentIntent(contentIntent);
    
            String message = extras.getString("message");
            if (message != null) {
                mBuilder.setContentText(message);
            } else {
                mBuilder.setContentText("<missing message content>");
            }
    
            String msgcnt = extras.getString("msgcnt");
            if (msgcnt != null) {
                mBuilder.setNumber(Integer.parseInt(msgcnt));
            }
    
            mNotificationManager.notify((String) appName, NOTIFICATION_ID, mBuilder.build());
        }
    
        public static void cancelNotification(Context context)
        {
            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.cancel((String)getAppName(context), NOTIFICATION_ID);  
        }
    
        private static String getAppName(Context context)
        {
            CharSequence appName = 
                    context
                        .getPackageManager()
                        .getApplicationLabel(context.getApplicationInfo());
    
            return (String)appName;
        }
    
        @Override
        public void onError(Context context, String errorId) {
            Log.e(TAG, "onError - errorId: " + errorId);
        }
    
    }
    

1 个答案:

答案 0 :(得分:1)

This tutorial最适合状态栏通知。

只需注释掉

//  if (!flag.isEmpty()){
//      flagVal = Integer.parseInt(flag);
//}

StatusBarNotification.java中获取新的cordova lib版本。