2014-10-06 2 views
-1

Когда уведомление отправляется со стороны сервера, мне нужно получить сообщение и идентификатор отправителя на стороне клиента. Я получаю сообщение, но не получает идентификатор отправителя ..... Пожалуйста, помогите мнеКак получить sender_id, получив уведомление gcm

Мой код на стороне сервера является

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; 
} 
} 

// Sharing Регистрация ключа с внешним сервером

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; 
} 
} 
+0

сэр сделал вашу программу работать, так как я получаю ошибку файла, не найденного исключение для GCMRegId.txt нужна помощь –

+0

Файл GCMRegId.txt будет создан в папке eclipse для Android. Если он не появится, то его не создано –

+0

сэр, пожалуйста, проверьте эту ссылку http://stackoverflow.com/questions/27895142/gcm-push-notification-not-working-and-register-id-is-also-not-displaying я получаю ошибку, пожалуйста, предложите мне, что делать –

ответ

0

extras().get("from") должен дать вам идентификатор отправителя в ваших onHandleIntent способ.

Смежные вопросы