読者です 読者をやめる 読者になる 読者になる

ふるすたっくえんじにあっぽい人の日記

ASP .NET MVC (C#)、.NET Framework、iOS (Objective-c) アプリ、Androidアプリ (Java)、AWS、たまにLAMPとかプロジェクトマネジメントあたりのお話

【C#】Androidへのプッシュ通知

C# Android

まんま
Android側の設定とかはぐぐってくださいな

using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;

namespace Hoge
{
    public sealed class Hoge
    {
        public static void HVSendPushForAndroid(string googleApiKey, string deviceToken, string message)
        {
            var rawData = new PushNotificationForAndroidModel()
            {
                RegistrationIds = new string[] { deviceToken },
                Data = new PushNotificationDataForAndroidModel() { Message = message },
            };
            var serializer = new DataContractJsonSerializer(typeof(PushNotificationForAndroidModel));
            var ms = new MemoryStream();
            serializer.WriteObject(ms, rawData);
            var data = Encoding.UTF8.GetString(ms.ToArray());
            using (var client = new HttpClient())
            {
                HttpContent content = new StringContent(data);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", "=" + googleApiKey);
                var result = client.PostAsync("https://android.googleapis.com/gcm/send", content).Result;
                Console.WriteLine(result.ToString());
            }
        }
    }

    [DataContract]
    public class PushNotificationForAndroidModel
    {
        [DataMember(Name = "registration_ids")]
        public string[] RegistrationIds { get; set; }

        [DataMember(Name = "data")]
        public PushNotificationDataForAndroidModel Data { get; set; }
    }

    [DataContract]
    public class PushNotificationDataForAndroidModel
    {
        [DataMember(Name = "message")]
        public string Message { get; set; }
    }
}