用于 android 的 vb.net 中的 pushSharp

Posted

技术标签:

【中文标题】用于 android 的 vb.net 中的 pushSharp【英文标题】:pushSharp in vb.net for android 【发布时间】:2014-04-08 08:04:33 【问题描述】:

我关注 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 以发送通知。 当我午餐这段代码时,什么都没有出现(没有事件匹配)并且我的手机上没有任何通知。

请帮助我,我真的需要这个代码。

【问题讨论】:

【参考方案1】:
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());
        



【讨论】:

就像我说的我的客户端工作正常,因为当我使用我的 npm 模块发送通知时,我会在智能手机上看到通知。所以我认为问题附加在服务器端。

以上是关于用于 android 的 vb.net 中的 pushSharp的主要内容,如果未能解决你的问题,请参考以下文章

使用VB.NET向android模拟器发送通知获取错误401

SQL Server 中的存储过程未使用 VB.Net 编码填充 ASP.Net 下拉列表

DllImport 与 VB.NET 中的声明

如何从 VB.NET 中的 USB 端口获取数据

如何从 C# 读取 VB.NET 项目中的“app.config”文件

如何从 vb.net 中的子表单访问父表单属性