Android 如何通过接收gcm通知来获取发件人id

Android 如何通过接收gcm通知来获取发件人id,android,google-cloud-messaging,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.ServletExcept

当从服务器端推送通知时,我需要在客户端接收消息和发送者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;
导入java.util.ArrayList;
导入android.app.IntentService;
导入android.app.Notification;
导入android.app.NotificationManager;
导入android.app.pendingent;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.content.SharedReferences.Editor;
导入android.os.Bundle;
导入android.support.v4.app.NotificationCompat;
导入com.google.android.gms.gcm.GoogleCloudMessaging;
公共类GCMNotificationEntService扩展了IntentService
{
公共静态int通知_ID=0;
int mNumMessages=1;
ArrayList nare=新的ArrayList();
共享引用;
私有字符串MY\u PREFS=“通知消息”;
公共GCMNotificationtentService()
{
超级(“GCMinentService”);
}
@凌驾
受保护的手部内容无效(意图)
{
Bundle extras=intent.getExtras();
GoogleCloudMessaging gcm=GoogleCloudMessaging.getInstance(this);
字符串messageType=gcm.getMessageType(intent);
如果(!extras.isEmpty())
{
if(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType))
{
sendNotification(“发送错误:+extras.toString());
} 
else if(GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType))
{
sendNotification(“服务器上的已删除邮件:+extras.toString());
} 
else if(GoogleCloudMessaging.MESSAGE\u TYPE\u MESSAGE.equals(messageType))
{
对于(int i=0;i<3;i++)
{
尝试
{
睡眠(500);
} 
捕捉(中断异常e)
{
e、 printStackTrace();
}
}
字符串messg=extras.get(Config.MESSAGE_KEY).toString();
发送通知(messg);
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
私有void sendNotification(字符串msg)
{
添加(味精);
NotificationCompat.Builder=新建NotificationCompat.Builder(此);
builder.setSmallIcon(R.drawable.msg_chat);
builder.setAutoCancel(true);
builder.setContentText(msg);
builder.setContentTitle(“新消息”);
builder.setNumber(mNumMessages);
builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_vibration | Notification.DEFAULT_LIGHTS);
NotificationCompat.InboxStyle mBigView=新NotificationCompat.InboxStyle();
字符串[]事件=新字符串[6];

对于(intj=0;j
extras().get(“from”)
应该在您的
OnHandleContent
方法中为您提供发件人ID。

先生,您的程序工作了吗??,因为我收到了一个文件未找到的错误,GCMRegId.txt异常需要一些帮助GCMRegId.txt文件将在android eclipse文件夹中创建。请检查它。如果它不存在,则其未创建DSIR请检查此链接我收到了e先生,请告诉我该怎么做
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;
}
}