使用Android的Azure通知中心 - 向用户子集发送通知

时间:2016-04-10 21:14:29

标签: c# android azure notifications azure-notificationhub

我目前正在构建一个Android消息传递应用,我正在尝试向属于某个群组的所有用户发送通知。我有一个Azure Notification Hub设置,可以正常发送通知给所有已注册的设备,但我似乎无法让它只为所有用户的一个子集(即一个组)工作。

设备在启动时注册Azure和GCM。

我尝试过使用"标签"尝试向个人发送通知,但我不确定我是否做得对...我不能因为它不起作用!

在以下代码中,我尝试使用其用户名作为标记向个人发送通知...

这是我的服务中发送通知的代码:

    // POST api/notification
    public async Task<IHttpActionResult> Post([FromBody]Notification notification)
    {
        var notificationToSave = new Notification
        {
            NotificationGuid = Guid.NewGuid().ToString(),
            TimeStamp = DateTime.UtcNow,
            Message = notification.Message,
            SenderName = notification.SenderName
        };

        var recipientNames = await GetRecipientNamesFromNotificationHub();

        var recipientNamesString = CreateCustomRecipientNamesString(recipientNames);

        string notificationJsonPayload =
            "{\"data\" : " +
            "   {" +
            "   \"message\": \"" + notificationToSave.Message + "\"," +
            "   \"senderName\": \"" + notificationToSave.SenderName + "\"," +
            "   \"recipientNames\": \"" + recipientNamesString + "\"" +
            "   }" +
            "}";

        var result = await _hubClient.SendGcmNativeNotificationAsync(notificationJsonPayload, "ken@test.com"); // If this second parameter is omitted then a notification is sent to all registered devices.

        notificationToSave.TrackingId = result.TrackingId;
        notificationToSave.Recipients = recipientNames;

        await Session.StoreAsync(notificationToSave);

        return Ok(notificationToSave);
    }

这就是我在Android端注册设备的方式:

private void sendRegistrationIdToBackend(String registrationId) {

        String backendBaseUrl = "http://myurl.net/";
        if (backendBaseUrl == null || backendBaseUrl == "")
        {
            return;
        }

        PushNotificationClient client = new PushNotificationClient(backendBaseUrl);

        Device device = createDevice(registrationId);

        client.registerDevice(device, new Callback<Device>() {
            @Override
            public void success(Device device, Response response) {
                //writeStringToSharedPreferences(SettingsActivity.SETTINGS_KEY_DEVICEGUID, device.DeviceGuid);
                Toast.makeText(context, "Device successfully registered with backend, DeviceGUID=" + device.DeviceGuid, Toast.LENGTH_LONG).show();
            }

            @Override
            public void failure(RetrofitError retrofitError) {
                Toast.makeText(context, "Backend registration error:" + retrofitError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

        Log.i(TAG, registrationId);
    }

    private Device createDevice(String registrationId) {
        Device device = new Device();
        device.Platform = "Android";
        device.Token = registrationId;
        device.UserName = LogInActivity.loggedInUser;
        device.DeviceGuid = null;
        //todo set device.PlatformDescription based on Android version
        device.SubscriptionCategories = new ArrayList<>();
        device.SubscriptionCategories.add("ken@test.com"); // This should be adding this username as a Tag which is referenced in the service.... Not sure if this is how I should do it!
        return device;
    }

这是我注册设备的方式:

 private async Task<RegistrationDescription> RegisterDeviceWithNotificationHub(Device device)
    {
        var hubTags = new HashSet<string>()
            .Add("user", new[] { device.UserName })
            .Add("category", device.SubscriptionCategories);

        var hubRegistrationId = device.HubRegistrationId ?? "0";//null or empty string as query input throws exception
        var hubRegistration = await _hubClient.GetRegistrationAsync<RegistrationDescription>(hubRegistrationId);
        if (hubRegistration != null)
        {
            hubRegistration.Tags = hubTags;
            await _hubClient.UpdateRegistrationAsync(hubRegistration);
        }
        else
        {
            hubRegistration = await _hubClient.CreateGcmNativeRegistrationAsync(device.Token, hubTags);
        }
        return hubRegistration;
    }

1 个答案:

答案 0 :(得分:1)

晚上好。 您应该尝试使用Visual Studio 2015检查您的注册。 安装它,连接天蓝色,天蓝色的集线器,注册设备。并尝试在测试令牌上发送测试消息(+检查“您的注册是否存在于通知中心上”)。