我需要在通过 xamarin 创建的 Android 应用程序中单击按钮时发送 GCM 通知。
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)
等。
附注我看到您正在使用 ContinueWith
并且不关心它的危险。看看这里:ContinueWith is Dangerous, Too不要错过主要文章:StartNew is Dangerous
关于c# - 如何在单击按钮时发送远程通知? Xamarin.Android C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37584224/