从ASP.NET向Android应用程序发送推送通知

3
我希望能从我的ASP.NET WEB API Post方法向我的简单Android应用程序发送小型推送通知。以下是我尝试过并进行了研究的内容。
我正在使用Google云消息传递服务将通知发送到应用程序中。我的应用程序以名称值对形式接收它。这里还提供了服务器代码的工作Java版本和我在Post方法中实现的C#版本。但是我的方法会抛出一个异常,错误为“Exception Occured with Error as(15913): println needs a message”,在Android应用程序中。
服务器部分的工作Java代码如下:
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();
    }

同样的,我的ASP.NET WEB API中C#代码如下:...
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应用程序中,我有以下接收器的LOC...
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应用程序。请问有人可以告诉我我在做什么错了吗?为什么会抛出异常并如何纠正它?


你发布完整的Logcat吗? - Sree
在异常发生之前,您是否收到了“已接收到注册ID为#”的消息?请提供Logcat。 - JustWe
06-04 10:33:24.890:我/已收到注册ID为(19955):APA91bHzO52-3TsEIMV3RXi45ICIo9HOe1ospPl3gRYwAAw59ATHvadGPZN86heHOQJNU8syju-yD9UQqSgkZOqllGi5AoSPMRRuw3RYhgApflr0abLoAh2GWFQCZgToG_aM0rOg0lBV8osz6ZMtP1JBF1S9_DiWiqKRT5WL6qFz4PqyE0jCHsE 06-04 10:34:17.606:我/发生异常,错误为(19955):println需要一条消息 - Sri Krishna Mallikarjuna
1个回答

1

在进行了大量研究之后,我找到了问题所在。我认为Log.i()内部使用println来将消息打印到LOG中。由于GCM没有推送任何数据给我的客户端代码,它会抛出异常。撇开这个问题,我让PUSH通知正常工作了,以下是我学到的一些内容,对于其他遇到相同问题的人可能会有用:

  1. GCM使用JSON来接收并推送通知到设备
  2. 要接收GCM的JSON具有以下预定义格式

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

因此,我在ASP.NET服务器端构建了上述JSON格式,并将其通过HTTP请求带着授权头传递给GCM服务器。在我的接收器端,我提取了所需的数据(在我的情况下是账户和金额),并根据用户显示了这些数据。

以下是我ASP.NET服务器端和客户端接收器的代码:

服务器端:-

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应用程序的客户端方面,如下所示:
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);
        }

现在我只想知道如何在警报框或任何类型的对话框中显示收到的通知,其中包含一个“确定”按钮。 有谁能帮助我找出在我的应用程序中使用什么类以及如何使用它来向用户显示它? 如果应用程序不活动,则可以在通知栏中显示,否则需要弹出窗口并提供一个“确定”按钮。

谢谢,


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接