如何在单击按钮时发送远程通知? Xamarin.Android C#

How to Send a Remote Notification on a Button Click? Xamarin.Android C#

我需要在通过 xamarin 创建的 android 应用程序中单击按钮时发送 GCM 通知。

我已经学习了这个教程https://developer.xamarin.com/guides/cross-platform/application_fundamentals/notifications/android/remote_notifications_in_android/

Button btnCLick = Findviewbyid<button>(resource.id.btnclikc);
btnCLick.Click += btnCLick_CLICK;
void btnCLick_Click (object sender, System.EventArgs e)
{
// Here i need to send my notification. I am not able to get it.
}

我使用 MessageSender.exe 发送我的通知,但我无法将其发送到我的应用程序中。

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace MessageSender

{
class Program
{
    public const string API_KEY =    "API_KEY";
    public const string MESSAGE = "MESSAGE";

    static void Main(string[] args)
    {
        var jGcmData = new JObject();
        var jData = new JObject();

        jData.Add("message", MESSAGE);
        jGcmData.Add("to", "/topics/global");
        jGcmData.Add("data", jData);

        var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key=" + API_KEY);

                Task.WaitAll(client.PostAsync(url,
                    new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                        }));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to send GCM message:");
            Console.Error.WriteLine(e.StackTrace);
        }
    }
  }
}

我需要将其添加到我的应用程序按钮中单击 xamarin.Android 我应该怎么做?

如果我答对了你的问题,那么你需要 xamarin 的跨平台 HttpClient 使用实现,对吗?

试试这个:Consuming a RESTful Web Service。该主题可能有点误导,但您应该只获取所需的 HttpClient 代码。

async void MyNotificationPost(Uri uri, string json)
{
    HttpClient client = new HttpClient();
    var content = new StringContent (json, Encoding.UTF8, "application/json");
    HttpResponseMessage response = await client.PostAsync(uri, content);

    ...

    if (response.IsSuccessStatusCode) 
    {
        ...
    }
}

在这个例子中,使用了跨平台Microsoft HTTP Client Libraries。如果您不喜欢,您可以使用有现货的常规 HttpWebRequest

    Task<WebResponse> HTTPRequestSend(
        Uri uri, 
        byte[] bodyData,
        CancellationToken cancellationToken)
    {
        HttpWebRequest request = WebRequest.CreateHttp(uri);
        request.Method = "POST";
        request.Headers["Accept"] = "application/json";

        return Task.Factory.FromAsync<Stream>(
            request.BeginGetRequestStream, 
            request.EndGetRequestStream, 
            null).ContinueWith(
                reqStreamTask => 
                {
                    using (reqStreamTask.Result) 
                    {
                        reqStreamTask.Result.Write(bodyData, 0, bodyData.Length);
                    }

                    return Task.Factory.FromAsync<WebResponse>(
                        request.BeginGetResponse, 
                        request.EndGetResponse, 
                        null).ContinueWith(
                            resTask => 
                            {
                                return resTask.Result;
                            }, 
                            cancellationToken);
                }, 
                cancellationToken).Unwrap();
    }

如果您需要同步,请小心不要陷入死锁。不要忘记使用 ConfigureAwait(false) 之类的。

P.S。我看到您正在使用 ContinueWith 并且不关心它的危险。看看这里:ContinueWith is Dangerous, Too and do not miss the main article: StartNew is Dangerous

实际上我使用了问题中给出的相同内容。

     string API_KEY = "APIKEY";
        var jGcmData = new JObject();
        var jData = new JObject();
        jData.Add("message", message);
        jGcmData.Add("to", "/topics/global");
        jGcmData.Add("data", jData);

        var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Authorization", "key=" + API_KEY);

                Task.WaitAll(client.PostAsync(url,
                    new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                        .ContinueWith(response =>
                        {
                            Console.WriteLine(response);
                            Console.WriteLine("Message sent: check the client device notification tray.");
                        }));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to send GCM message:");
            Console.Error.WriteLine(e.StackTrace);
        }

成功了。谢谢你的帮助。兄弟@ZverevEugene