从ASP.NET到Android应用程序发送推送通知 [英] Sending a Push Notification from a ASP.NET to Android App

查看:180
本文介绍了从ASP.NET到Android应用程序发送推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的ASP.NET Web API POST方法发送一个小推送通知我简单的Andr​​oid应用程序。这里是所有我尝试并重新搜索。

I want to Send a small Push Notification from my ASP.NET WEB API Post Method to my Simple Android App.. Here is what all I tried and re searched.

我使用谷歌的云信息服务的通知应用发送。我的应用程序接收它的名称值对。这里我也给服务器code的工作Java版本,并在我的岗位我的方法C#实现。但我的方法抛出一个异常如
异常与错误发生的(15913):需要的println消息中的Andr​​oid应用

I am using Google Cloud Messaging Service to Send in the notification to the App. My App receives it in Name Value Pairs. I also give here the working Java Version of the Server Code and my C# implementation in my Post Method. But my Method throws an Exception as "Exception Occured with Error as(15913): println needs a message" in the Android App.

Java的工作code是服务器部分如下: -

Working Java Code is as follows for the Server Part:-

public void sendmessage2Device(View v,String regisID,String msg1,String msg2) {

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(
            "https://android.googleapis.com/gcm/send");


    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("registration_id",regisID));

        nameValuePairs.add(new BasicNameValuePair("data1",msg1));
        nameValuePairs.add(new BasicNameValuePair("data2", msg2));






        post.setHeader("Authorization","key=AIzaSyBB6igK9sYYBTSIly6SRUHFVexeOa_7FuM");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");




        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        InputStreamReader inputst = new InputStreamReader(response.getEntity().getContent());
        BufferedReader rd = new BufferedReader(inputst);


        String line = "";
        while ((line = rd.readLine()) != null) {
            Log.e("HttpResponse", line);


                String s = line.substring(0);
                Log.i("GCM response",s);
                //Toast.makeText(v.getContext(), s, Toast.LENGTH_LONG).show();


        }

    } catch (IOException e) {
        e.printStackTrace();
    }

同样我的C#$ C $的的ASP.NET Web API中c是如下...

Similarly My C# Code in the ASP.NET WEB API is as follows...

public String Post([FromBody]TransactionDetails value)
    {
        try
        {
            WebClient toGCM = new WebClient();
            toGCM.Headers.Add("ContentType:");
            toGCM.Headers["ContentType"] = "application/x-www-form-urlencoded; charset=UTF-8";
            //HttpWebRequest toGCM = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
            //toGCM.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            toGCM.Headers.Add("Accept:");
            toGCM.Headers["Accept"]= "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36";
            //toGCM.Accept = "application/json, text/javascript, */*; q=0.01";
            toGCM.Headers.Add("UserAgent:") ;
            toGCM.Headers["UserAgent"]= "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36";
            toGCM.Headers.Add("Authorization:");
            toGCM.Headers["Authorization"] = "key=AIzaSyCoxjeOGi_1ss2TeShDcoYbNcPU9_0J_TY";
            //String DatatoClient = "ToAccountNumber=" + value.ToAccountNumber + "&Amount=" + value.Amount;
            NameValueCollection postFieldNameValue = new NameValueCollection();
            postFieldNameValue.Add("registration_id", "APA91bHzO52-3TsEIMV3RXi45ICIo9HOe1ospPl3gRYwAAw59ATHvadGPZN86heHOQJNU8syju-yD9UQqSgkZOqllGi5AoSPMRRuw3RYhgApflr0abLoAh2GWFQCZgToG_aM0rOg0lBV8osz6ZMtP1JBF1S9_DiWiqKRT5WL6qFz4PqyE0jCHsE");
            postFieldNameValue.Add("Account", value.ToAccountNumber.ToString());
            postFieldNameValue.Add("Amount", value.Amount.ToString());

            byte[] responseArray = toGCM.UploadValues("https://android.googleapis.com/gcm/send", postFieldNameValue);
            String S=Encoding.ASCII.GetString(responseArray);
            return S;
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception Occured in Post Method on Web Server as:{0}", e.Message);
            return e.Message;
        }
    }

在Android应用我有一个接收器...

In the Android APP I have the following LOC for Receiver...

public void onReceive(Context context, Intent intent) {
    try {
        String action = intent.getAction();
        if (action.equals("com.google.android.c2dm.intent.REGISTRATION"))
        {
            String registrationId = intent.getStringExtra("registration_id");
            Log.i("Received the Registration Id as ",registrationId);
            String error = intent.getStringExtra("error");
            String unregistered = intent.getStringExtra("unregistered"); 
        }
        else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) 
        {
            Log.i("In the RECEIVE Method ",intent.getStringExtra("Account"));
            String Account = intent.getStringExtra("Account");
            String Amount = intent.getStringExtra("Amount");
            Log.i("Received Account as ",Account);
            Log.i("Received Amount as  ",Amount);
        }
    }
    catch(Exception e)
    {
        Log.i("Exception Occured with Error as ",e.getMessage());
    }
    finally
    {

    }

我很新到Android开发的部份是我第一次的Helloworld Android应用程序。谁能告诉我什么我做错了,为什么异常被抛出,以及如何纠正它吗?

I am very new to Android Development and ths is my first Helloworld Android App. Can anyone tell me what am I doing wrong and why the Exception is being thrown and how to correct it?

推荐答案

在一些实质性的调研中发现的问题。我presumed的Log.i()使用的println内部打印记录消息作为well.Since的GCM不推我的客户code正在寻找任何数据,它抛出一个异常。牢记这一边,我得到了推送通知的工作,这里是我学到的可能是别人同样的问题是有用的。

Found the issue after some substantial research. I presumed that the Log.i() uses println internally to print the messages to LOG as well.Since the GCM is not pushing any data my client code is looking for, it throws an exception. Keeping that aside, I got the PUSH notifications working and here is what I learnt as it might be useful to someone else with the same problem.


  1. 的GCM使用JSON接收和推通知设备

  2. 由GCM收到
  3. 该JSON有一个predefined格式如下

  1. The GCM uses JSON to Receive and Push the notification to the Device
  2. The JSON to be received by the GCM has a predefined format as below

{数据:
      {帐户:你的电话号码,
        金额:您的金额
      },
  registration_ids:[ID1,ID2,ID3 ......]
}

{ data: { Account: your number, Amount: your Amount }, registration_ids:[id1,id2,id3....] }

所以,我建我的ASP.NET服务器端上面的JSON格式和HTTP请求到服务器GCM在它的Authorization头传递。在我的接收端,我在我的案件中提取所需的数据(账户及金额),并显示相应的用户。

So, I constructed the above JSON format on my ASP.NET Server side and passed with Http request to GCM Server with the Authorization header in it. On my receiver side, I extracted the required data (Account and Amount) in my case and displayed to user accordingly.

PFB的​​$ C $的CS我的ASP.NET服务器端和客户端接收器。

PFB the codes of my ASP.NET Server Side and Client Side Receiver.

服务器端: -

public String Post([FromBody]TransactionDetails value, HttpRequestMessage receivedReq)
    {
        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
            httpWebRequest.ContentType = "application/json; charset=UTF-8";
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add("Authorization", "key=AIzaSyBs_eh4nNVaJl3FjQ_ZC72ZZ6uQ2F8r8W4");
            String result = "";
            String yourresp = "<html><head><title>Response from Server</title></head><body>";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"data\":" +"{\"Amount\":"+value.Amount+","+
                                "\"Account\":"+value.ToAccountNumber+"}"+","+
                                "\"registration_ids\":[" + "\""+value.RegID +"\"]}";


                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                     result = streamReader.ReadToEnd();
                }
            }
            DialogResult result1 = MessageBox.Show("Server sent the details to your phone, Check and Confirm to Continue or Not", "Important Information",MessageBoxButtons.YesNo);
            if (result1.ToString().Contains("Yes"))
            {
                WriteAccountNumber(value.ToAccountNumber, value.Amount);
                yourresp += "<h1>The Transaction was Successful</h1>";

            }
            else
            {
                yourresp += "<h1>The Transaction was NOT Successful</h1>";
            }
            yourresp += "</body></html>";
            return yourresp;
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception Occured in Post Method on Web Server as:{0}", e.Message);
            return e.Message;
        }
    }

在在Android应用程序的客户端如下: -

On the Client Side in the Android App is as follows:-

else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) 
        {
            //Log.i("Message Received","Before Scheme");

            String Account=intent.getStringExtra("Account");
            String Amount=intent.getStringExtra("Amount");
            Toast.makeText(context, "Your Transaction Details Received by the Server are...\n\nAccount="+Account+"\nAmount="+Amount, Toast.LENGTH_LONG).show();
            Log.i("Account=",Account);
            Log.i("Amount=",Amount);
        }

所以,现在我只是想知道如何在警报或任何种类的对话框与一个确定按钮显示收到的通知。谁能帮我一下班一个如何使用它在我的应用程序,以显示给用户?如果应用程序未激活就可以显示在Notifcation条其他需要有一个确定按钮弹出。

So, now I just want to know how to display the received Notification in an Alert or any kind of dialog box with an OK button. Could anyone help me what class an how to use it in my App to display it to user? if the App is not active it can be shown in Notifcation bar else a pop up is needed with an OK button.

谢谢,

这篇关于从ASP.NET到Android应用程序发送推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆