0

私は PushSharp プロジェクトの wiki に従い、このコードを書いてデバイスに通知を送信します。

https://github.com/Redth/PushSharp/wiki/How-to-Configure-&-Send-GCM-Google-Cloud-Messaging-Push-Notifications-using-PushSharp

Imports PushSharp
Imports PushSharp.Android
Imports PushSharp.Core

Module Module1

Sub Main()

    Console.WriteLine("Start notification : ")

    Dim push As New PushBroker()

    AddHandler push.OnDeviceSubscriptionExpired, AddressOf DeviceSubscriptionChanged
    AddHandler push.OnChannelException, AddressOf ChannelException
    AddHandler push.OnServiceException, AddressOf ServiceException
    AddHandler push.OnNotificationFailed, AddressOf NotificationFailed
    AddHandler push.OnDeviceSubscriptionExpired, AddressOf DeviceSubscriptionExpired
    AddHandler push.OnDeviceSubscriptionChanged, AddressOf DeviceSubscriptionChanged
    AddHandler push.OnChannelCreated, AddressOf ChannelCreated
    AddHandler push.OnChannelDestroyed, AddressOf ChannelDestroyed

    push.RegisterGcmService(New GcmPushChannelSettings("AIzaSyCcyNj2Q8bHJqJ-gFR6N3CFtM_VJpv9lIE"))
    push.QueueNotification(New GcmNotification().ForDeviceRegistrationId("APA91bGPD7eT7_MEqnL5D23BxihL3-4JkpFGpKy_2A2MNIJHFyEqhSM0iFVMRortNg_394VjsXqyuP0vbPbTQcWL-3ab_4mp-rUn4ypfkntqXfgurBeXOc6M5j25ewuclXuhezhV5yULQzpiJWoOlhYFn28Yx8iJRTA5jup4lKYBo7uVObSsLzs").WithJson("{""alert"":""Hello World2!"",""badge"":6,""sound"":""sound.caf""}"))

    Console.WriteLine("Waiting for Queue to Finish...")

    'Stop and wait for the queues to drains
    push.StopAllServices(True)

    Console.WriteLine("Queue Finished, press return to exit...")
    Console.ReadLine()
End Sub

Sub DeviceSubscriptionChanged(sender As Object, oldSubscriptionId As String, newSubscriptionId As String, notification As INotification)
    'Currently this event will only ever happen for Android GCM
    Console.WriteLine("Device Registration Changed:  Old-> " & oldSubscriptionId & "  New-> " & newSubscriptionId & " -> " & Convert.ToString(notification))
End Sub

Sub NotificationSent(sender As Object, notification As INotification)
    Console.WriteLine("Sent: " & Convert.ToString(sender) & " -> " & Convert.ToString(notification))
End Sub

Sub NotificationFailed(sender As Object, notification As INotification, notificationFailureException As Exception)
    Console.WriteLine("Failure: " & Convert.ToString(sender) & " -> " & Convert.ToString(notificationFailureException.Message) & " -> " & Convert.ToString(notification))
End Sub

Sub ChannelException(sender As Object, channel As IPushChannel, exception As Exception)
    Console.WriteLine("Channel Exception: " & Convert.ToString(sender) & " -> " & Convert.ToString(exception))
End Sub

Sub ServiceException(sender As Object, exception As Exception)
    Console.WriteLine("Channel Exception: " & Convert.ToString(sender) & " -> " & Convert.ToString(exception))
End Sub

Sub DeviceSubscriptionExpired(sender As Object, expiredDeviceSubscriptionId As String, timestamp As DateTime, notification As INotification)
    Console.WriteLine("Device Subscription Expired: " & Convert.ToString(sender) & " -> " & expiredDeviceSubscriptionId)
End Sub

Sub ChannelDestroyed(sender As Object)
    Console.WriteLine("Channel Destroyed for: " & Convert.ToString(sender))
End Sub

Sub ChannelCreated(sender As Object, pushChannel As IPushChannel)
    Console.WriteLine("Channel Created for: " & Convert.ToString(sender))
End Sub

End Module

私は適切な API キーを持っており、phonegap プラグインで登録 ID を取得しています。通知を送信するために、小さな npm モジュールを使用して、API キーと登録 ID を既にテストしています。このコードをランチすると、何も追加されず (イベントの一致もありません)、電話に通知もありません。

このコードが本当に必要なのを助けてください。

4

1 に答える 1

0
I have a suggestion.

In android GcmIntentService class onHandleIntent method us log.d to figure out notification is reaching at android end or not. Sometime our code for show notification is not working and we get confused on which side problem is occurring. Previously i have implemented push notification using C# PushSharp and i face same problem. but error was with my GcmIntentService, sendnotification code at android side.

working GCMIntentService class:

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.app.burnhelp.service;
import java.util.Date;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.app.burnhelp.R;
import com.app.burnhelp.R.color;
import com.app.burnhelp.main.activity.LoginActivity;
import com.app.burnhelp.receiver.GcmBroadcastReceiver;
import com.google.android.gms.gcm.GoogleCloudMessaging;
/**
 * This {@code IntentService} does the actual handling of the GCM message.
 * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
 * partial wake lock for this service while the service does its work. When the
 * service is finished, it calls {@code completeWakefulIntent()} to release the
 * wake lock.
 */
public class GcmIntentService extends IntentService {
       public static final int NOTIFICATION_ID = 1;
        private NotificationManager mNotificationManager;
        NotificationCompat.Builder builder;
        private String TAG = "GcmIntentService";

        public GcmIntentService() {
            super("GcmIntentService");
        }

        @Override
        protected void onHandleIntent(Intent intent) {
            Bundle extras = intent.getExtras();
            GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
            // The getMessageType() intent parameter must be the intent you received
            // in your BroadcastReceiver.
            String messageType = gcm.getMessageType(intent);

            if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
                /*
                 * Filter messages based on message type. Since it is likely that GCM
                 * will be extended in the future with new message types, just ignore
                 * any message types you're not interested in, or that you don't
                 * recognize.
                 */
                if (GoogleCloudMessaging.
                        MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                    sendNotification("Send error: " + extras.toString());
                } else if (GoogleCloudMessaging.
                        MESSAGE_TYPE_DELETED.equals(messageType)) {
                    sendNotification("Deleted messages on server: " +
                            extras.toString());
                // If it's a regular GCM message, do some work.
                } else if (GoogleCloudMessaging.
                        MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                     Log.i(TAG, "Working... ");
                     Date cal = new Date();
                     Log.d("Started at","started work on"+cal.getHours()+":"+cal.getMinutes()+":"+cal.getSeconds());

                    Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                    cal = new Date();
                    Log.d("End at","End work on"+cal.getHours()+":"+cal.getMinutes()+":"+cal.getSeconds());
                    // Post notification of received message.
                    sendNotification("" + extras.getString("collapse_key"));
                    cal = new Date();
                    Log.d("Done at","Done work on"+cal.getHours()+":"+cal.getMinutes()+":"+cal.getSeconds());

                    Log.i(TAG, "msg: " + extras.getString("msg"));
                    Log.i(TAG, "collapse_key: " + extras.getString("collapse_key"));
                    Log.i(TAG, "Received: " + extras);
                }
            }
            // Release the wake lock provided by the WakefulBroadcastReceiver.
            GcmBroadcastReceiver.completeWakefulIntent(intent);
        }

        // Put the message into a notification and post it.
        // This is just one simple example of what you might choose to do with
        // a GCM message.
        private void sendNotification(String msg) {
            mNotificationManager = (NotificationManager)
                    this.getSystemService(Context.NOTIFICATION_SERVICE);

            PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, LoginActivity.class), 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.bhiogo)
            .setContentTitle("BurnHelp")
            .setStyle(new NotificationCompat.BigTextStyle()
            .bigText(msg))
            .setContentText(msg);           
          //Vibration and sound
            mBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

         //LED
            mBuilder.setLights(color.sky_blue_1, 3000, 3000);
         //   mBuilder.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
          //  Toast.makeText(getApplicationContext(), "New Message: " + msg, Toast.LENGTH_LONG).show();

            mBuilder.setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }


}
于 2014-04-08T08:13:47.467 に答える