1
votes

I need to send a GCM Notification On A button click in the android application made through xamarin.

I Have followed this tutorial 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.
}

I Use a MessageSender.exe to send my notification but i cant make it into my application.

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);
        }
    }
  }
}

I need to make this into my application button click in xamarin.Android How Should i do that??

2
is it that you are trying to send an message from your Android app?Arthur Thompson
Yeah a Push NotificationHarsh Bakshi
Has your client application subscribed to the global topic? Could you include that code in your question?Arthur Thompson
Yes It is.! developer.xamarin.com/guides/cross-platform/… i have used the same code in the link to subscribe my application to global topic.Harsh Bakshi

2 Answers

0
votes

If I get your question right than your need a cross-platform HttpClient usage implementation for xamarin, right?

Try this: Consuming a RESTful Web Service. The topic might be a bit misleading but you should just get the HttpClient code you need.

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) 
    {
        ...
    }
}

In this example, the crossplatform Microsoft HTTP Client Libraries are used. If you do not like that you can use the conventional HttpWebRequest which is available in stock.

    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();
    }

If you need that synchronous, be very careful not to get stuck in a deadlock. Do not forget to use ConfigureAwait(false) or the like.

P.S. I see you are using the ContinueWith and do not care for it's danger. Have a look here: ContinueWith is Dangerous, Too and do not miss the main article: StartNew is Dangerous

0
votes

Actually I used the same as given in the question.

     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);
        }

It worked. Thanks for your Help. Brother @ZverevEugene