【问题标题】:How to Send a Remote Notification on a Button Click? Xamarin.Android C#如何在按钮单击时发送远程通知? Xamarin.Android C#
【发布时间】:2016-10-01 17:45:50
【问题描述】:

我需要在通过 xamarin 制作的 android 应用程序中单击 A 按钮时发送 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 中将其添加到我的应用程序按钮中单击 我该怎么做??

【问题讨论】:

  • 您是在尝试从您的 Android 应用发送消息吗?
  • 是的,推送通知
  • 您的客户端应用程序订阅了全局主题吗?您能否在问题中包含该代码?
  • 是的。! developer.xamarin.com/guides/cross-platform/… 我在链接中使用了相同的代码来为我的应用程序订阅全局主题。

标签: c# azure xamarin google-cloud-messaging xamarin.android


【解决方案1】:

其实我使用的和问题中给出的一样。

     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

【讨论】:

    【解决方案2】:

    如果我的问题是正确的,而不是您需要 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) 之类的。

    附:我看到你正在使用ContinueWith 并且不关心它的危险。看看这里:ContinueWith is Dangerous, Too,不要错过主要文章:StartNew is Dangerous

    【讨论】:

    • 先生,我做不到!请你给我一个例子!我会很高兴你!
    • @Bakshi 我没有举个例子吗?你现在到底有什么问题?
    • 其实。我无法让它如何使用。通知应该发送到主题/全局我无法使其如何使用。
    • @HarshBakshi 你的意思是你不知道如何构建正确的消息内容/元数据?您在教程中的 windows 应用程序中的代码是否按预期工作?
    • @HarshBakshi 是什么?我问了两个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    相关资源
    最近更新 更多