【问题标题】:how to statusbar notification using phone gap push plugin如何使用phonegap推送插件进行状态栏通知
【发布时间】:2013-11-15 12:11:40
【问题描述】:

我使用了电话间隙推送插件,它对我来说很好用,也可以从我的服务器获取消息。 我有两个问题,如果有人可以更新代码或需要更改代码的地方,我需要感谢。

我点击此链接显示应用程序在后台时的通知你可以看到它。

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

关于我收到的这份文件,但有两件事没有做,正如我在两个问题中提到的那样。

  1. 收到消息时显示消息计数未定义。

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

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);
    }

}

【问题讨论】:

  • 请发布您的服务器代码。
  • 我不认为服务器代码与此错误有任何关系
  • 您说msgcnt 未定义。您的服务器可能没有发送此参数。这就是为什么服务器代码可能与您的问题有关。
  • 哦,第二个问题呢
  • 你调试过代码吗?仅当以下条件为真时才显示通知 - !PushPlugin.isInForeground() &amp;&amp; extras.getString("message").length() != 0。在不显示通知的情况下,该条件是否成立?

标签: android cordova push-notification


【解决方案1】:

This tutorial 是状态栏通知的最佳选择。

只需注释掉

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多