如何通过接收gcm通知获取sender_id

时间:2014-10-06 13:42:40

标签: android google-cloud-messaging

当从服务器端推送通知时,我需要在客户端接收消息和发件人ID。我收到消息但没有收到发件人ID .....请帮帮我

我的服务器端代码是

package com.javapapers.java.gcm;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

@WebServlet("/GCMNotification")
public class GCMNotification extends HttpServlet {
private static final long serialVersionUID = 1L;

// Put your Google API Server Key here
private static final String GOOGLE_SERVER_KEY="AIzaSyCft9Jk98jZz4-O4mMPPv5HmhWdgHBmVkg";
static final String MESSAGE_KEY = "message";

public GCMNotification() 
{
    super();
}

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);

}

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    Result result = null;
    String share = request.getParameter("regId");

    String regId = "";
    if (share != null && !share.isEmpty()) {
        regId = request.getParameter("regId");
        PrintWriter writer = new PrintWriter("GCMRegId.txt");
        writer.println(regId);
        writer.close();
        request.setAttribute("pushStatus", "GCM RegId Received.");
        request.getRequestDispatcher("index.jsp")
                .forward(request, response);
    } else {
        try 
        {
            BufferedReader br = new BufferedReader(new FileReader(
                    "GCMRegId.txt"));
            regId = br.readLine();
            br.close();
            String userMessage = request.getParameter("message");
            Sender sender = new Sender(GOOGLE_SERVER_KEY);
            Message message = new Message.Builder().addData(MESSAGE_KEY, userMessage).build();
            result = sender.send(message, regId, 1);
            request.setAttribute("pushStatus", result.toString());
        } catch (IOException ioe) {
            ioe.printStackTrace();
            request.setAttribute("pushStatus",
                    "RegId required: " + ioe.toString());
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("pushStatus", e.toString());
        }
    }
        request.getRequestDispatcher("index.jsp")
                .forward(request, response);
    }
}

//通知句柄类

package com.javapapers.android;

import java.util.ArrayList;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GCMNotificationIntentService extends IntentService 
{
public static int NOTIFICATION_ID = 0;
int mNumMessages = 1;
ArrayList<String> nare = new ArrayList<String>();
SharedPreferences mPreference;
private String MY_PREFS = "notification_message";
public GCMNotificationIntentService() 
{
    super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) 
{
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);
    if (!extras.isEmpty()) 
    {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) 
        {
            sendNotification("Send error: " + extras.toString());
        } 
        else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) 
        {
            sendNotification("Deleted messages on server: "+ extras.toString());
        } 
        else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) 
        {

            for (int i = 0; i < 3; i++) 
            {
            try 
                {
                    Thread.sleep(500);
                } 
            catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
            String messg = extras.get(Config.MESSAGE_KEY).toString();
            sendNotification(messg);
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) 
{
    nare.add(msg);
    NotificationCompat .Builder builder = new NotificationCompat.Builder(this);
                                        builder.setSmallIcon(R.drawable.msg_chat);
                                        builder.setAutoCancel(true);
                                        builder.setContentText(msg);
                                        builder.setContentTitle("New Message");
                                        builder.setNumber(mNumMessages);
                                        builder.setDefaults(Notification.DEFAULT_SOUND              |Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
    NotificationCompat.InboxStyle mBigView = new NotificationCompat.InboxStyle();
    String[] events = new String[6];
    for(int j=0; j<events.length; j++)
    {
        mBigView.addLine(events[j]);
    }
    mBigView.setBigContentTitle("New Message");
    builder.setStyle(mBigView);
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pintent = PendingIntent.getActivity(this, 0, intent,NOTIFICATION_ID);
    builder.setContentIntent(pintent);
    NotificationManager notify = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notify.notify(NOTIFICATION_ID, builder.build());
    mPreference = getApplicationContext().getSharedPreferences(MY_PREFS, MODE_PRIVATE);
    Editor edit = mPreference.edit();
    edit.putInt("array_msg_size", nare.size());
    for(int i=0; i<nare.size(); i++)
    {
        edit.putString("message"+i, nare.get(i));
    }
    edit.commit();
    ++mNumMessages;
}
}

//与外部服务器共享注册密钥

package com.javapapers.android;



public class ShareExternalServer 
{
public String shareRegIdWithAppServer(final Context context,final String regId) 
{
    String result = "";
    Map<String, String> paramsMap = new HashMap<String, String>();
    paramsMap.put("regId", regId);
    try {
        URL serverUrl = null;
        try 
        {
            serverUrl = new URL(Config.APP_SERVER_URL);
        } 
        catch (MalformedURLException e) 
        {
            result = "Invalid URL: " + Config.APP_SERVER_URL;
        }
        StringBuilder postBody = new StringBuilder();
        Iterator<Entry<String, String>> iterator = paramsMap.entrySet().iterator();
        while (iterator.hasNext()) 
        {
            Entry<String, String> param = iterator.next();
            postBody.append(param.getKey()).append('=').append(param.getValue());
            if (iterator.hasNext()) 
            {
                postBody.append('&');
            }
        }
        String body = postBody.toString();
        byte[] bytes = body.getBytes();
        HttpURLConnection httpCon = null;
        try {
                httpCon = (HttpURLConnection) serverUrl.openConnection();
                httpCon.setDoOutput(true);
                httpCon.setUseCaches(false);
                httpCon.setFixedLengthStreamingMode(bytes.length);
                httpCon.setRequestMethod("POST");
                httpCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
                OutputStream out = httpCon.getOutputStream();
                out.write(bytes);
                out.close();
                int status = httpCon.getResponseCode();
                if (status == 200) 
                {
                    result = "RegId shared with Application Server. RegId: "
                            + regId;
                } 
                else 
                {
                    result = "Post Failure." + " Status: " + status;
                }
            } 
        finally 
        {
            if (httpCon != null) 
            {
                httpCon.disconnect();
            }
        }
    } 
    catch (IOException e) 
    {
        result = "Post Failure. Error in sharing with App Server.";
    }
    return result;
}
}

1 个答案:

答案 0 :(得分:0)

extras ().get("from")应该使用onHandleIntent方法为您提供发件人ID。