2015-06-22 102 views
0

我做了一个GCM聊天应用程序。我面临的问题是我无法从接收方收到的通知中获取邮件内容和发件人姓名。当我点击通知图标时,它会带我聊天活动,但不会显示消息,也不会显示发件人的姓名。 Plz通过使用pending intent来帮助我解决这个问题。这里是GcmIntentService.java如何从GCM聊天应用程序的通知中获取消息内容?

public class GcmIntentService extends IntentService { 
public static final int NOTIFICATION_ID = 1; 
private NotificationManager mNotificationManager; 
NotificationCompat.Builder builder; 
public static final String TAG = "GcmIntentService"; 

public GcmIntentService() { 
    super("GcmIntentService"); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 

    Bundle extras = intent.getExtras(); 
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); 
    // The getMessageType() intent parameter must be the intent you received 
    // in your BroadcastReceiver. 
    String messageType = gcm.getMessageType(intent); 

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle 
     /* 
     * Filter messages based on message type. Since it is likely that 
     * GCM will be extended in the future with new message types, just 
     * ignore any message types you're not interested in, or that you 
     * don't recognize. 
     */ 
     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()); 
      // If it's a regular GCM message, do some work. 
     } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE 
       .equals(messageType)) { 
      sendNotification("Received Message : " 
        + extras.getString("message")); 
      Log.i(TAG, "Received: " + extras.toString()); 
     } 
    } 
    // Release the wake lock provided by the WakefulBroadcastReceiver. 
    GcmBroadcastReceiver.completeWakefulIntent(intent); 


} 

// Put the message into a notification and post it. 
// This is just one simple example of what you might choose to do with 
// a GCM message. 
private void sendNotification(String msg) { 

    mNotificationManager = (NotificationManager) this 
      .getSystemService(Context.NOTIFICATION_SERVICE); 

      PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
      new Intent(this, ChatActivity.class), 0); 

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
      this).setSmallIcon(R.drawable.ic_launcher) 
      .setContentTitle("GCM Notification") 
      .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) 
      .setContentText(msg); 

    mBuilder.setContentIntent(contentIntent); 
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 
} 

/*Intent notificationIntent = new Intent(getApplicationContext(), viewmessage.class); 
    notificationIntent.putExtra("NotificationMessage", notificationMessage); 
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT); 
    notification.flags |= Notification.FLAG_AUTO_CANCEL; 
    notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent); 
*/ 

} 

这里是ChatActivity.java

public class ChatActivity extends ActionBarActivity { 

HttpPost httppost; 
StringBuffer buffer; 
HttpResponse response; 
HttpClient httpclient; 
List<NameValuePair> nameValuePairs; 
Utils utils; 

static String TAG = "GCM DEMO"; 
String user_name; 
String regid; 
String chattingToName, chattingToDeviceID; 

String SENDER_ID = "abc"; //protected 
String API_KEY = "xyz"; //protected 

EditText edtMessage; 
ListView chatLV; 
DBOperation dbOperation; 

ChatListAdapter chatAdapater; 
ArrayList<ChatPeople> ChatPeoples; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    utils = new Utils(this); 

    chatLV = (ListView) findViewById(R.id.listView1); 
    edtMessage = (EditText) findViewById(R.id.editText_message); 

    ChatPeoples = new ArrayList<ChatPeople>(); 

    regid = utils.getRegistrationId(); 

    Bundle b = getIntent().getExtras(); 

    if (b != null) { 
     user_name = b.getString("chattingFrom"); 
     chattingToName = b.getString("chattingToName"); 
     chattingToDeviceID = b.getString("chattingToDeviceID"); 

     Log.i(TAG, "Chat From : " + user_name + " >> Chatting To : " 
       + chattingToName); 
    } 

    registerReceiver(broadcastReceiver, new IntentFilter(
      "CHAT_MESSAGE_RECEIVED")); 

    dbOperation = new DBOperation(this); 
    dbOperation.createAndInitializeTables(); 

    populateChatMessages(); 

    chatLV.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL); 
    chatLV.setStackFromBottom(true); 

    getSupportActionBar().setTitle("Chatting with : " + chattingToName); 
} 

private void populateChatMessages() { 

    getData(); 
    if (ChatPeoples.size() > 0) { 
     chatAdapater = new ChatListAdapter(this, ChatPeoples); 
     chatLV.setAdapter(chatAdapater); 
    } 

} 

void clearMessageTextBox() { 

    edtMessage.clearFocus(); 
    edtMessage.setText(""); 

    hideKeyBoard(edtMessage); 

} 

private void hideKeyBoard(EditText edt) { 
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
    imm.hideSoftInputFromWindow(edt.getWindowToken(), 0); 
} 

void addToDB(ChatPeople curChatObj) { 

    ChatPeople people = new ChatPeople(); 
    ContentValues values = new ContentValues(); 
    values.put(people.getPERSON_NAME(), curChatObj.getPERSON_NAME()); 
    values.put(people.getPERSON_CHAT_MESSAGE(), 
      curChatObj.getPERSON_CHAT_MESSAGE()); 
    values.put(people.getPERSON_DEVICE_ID(), 
      curChatObj.getPERSON_DEVICE_ID()); 
    values.put(people.getPERSON_CHAT_TO_FROM(), 
      curChatObj.getPERSON_CHAT_TO_FROM()); 
    values.put(people.getPERSON_EMAIL(), "[email protected]"); 
    dbOperation.open(); 
    long id = dbOperation.insertTableData(people.getTableName(), values); 
    dbOperation.close(); 
    if (id != -1) { 
     Log.i(TAG, "Succesfully Inserted"); 
    } 

    populateChatMessages(); 
} 

void getData() { 

    ChatPeoples.clear(); 

    Cursor cursor = dbOperation.getDataFromTable(chattingToDeviceID); 
    if (cursor.getCount() > 0) { 
     cursor.moveToFirst(); 
     do { 
      // Log.i(TAG, 
      // "Name = " + cursor.getString(0) + ", Message = " 
      // + cursor.getString(1) + " Device ID = " 
      // + cursor.getString(2)); 

      ChatPeople people = addToChat(cursor.getString(0), 
        cursor.getString(1), cursor.getString(3)); 
      ChatPeoples.add(people); 
     } while (cursor.moveToNext()); 
    } 
    cursor.close(); 

} 

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

     Bundle b = intent.getExtras(); 

     String message = b.getString("message"); 

     Log.i(TAG, " Received in Activity " + message + ", NAME = " 
       + chattingToName + ", dev ID = " + chattingToDeviceID); 

     // this demo this is the same device 
     ChatPeople curChatObj = addToChat(chattingToName, message, 
       "Received"); 
     addToDB(curChatObj); // adding to db 

     populateChatMessages(); 

    } 
}; 

public void sendMessage() { 

    final String messageToSend = edtMessage.getText().toString().trim(); 

    if (messageToSend.length() > 0) { 

     Log.i(TAG, "sendMessage"); 

     Thread thread = new Thread() { 
      @Override 
      public void run() { 
       try { 
        httpclient = new DefaultHttpClient(); 
        httppost = new HttpPost(utils.getCurrentIPAddress2()); 
        //httppost = new HttpPost("http://192.168.43.183/safety_app/gcm_engine.php"); 
          //+ "GCM/gcm_engine.php"); 
        nameValuePairs = new ArrayList<NameValuePair>(1); 
        nameValuePairs.add(new BasicNameValuePair("message", 
          messageToSend)); 

        nameValuePairs.add(new BasicNameValuePair(
          "registrationIDs", chattingToDeviceID)); 

        nameValuePairs.add(new BasicNameValuePair("apiKey", 
          API_KEY)); 

        httppost.setEntity(new UrlEncodedFormEntity(
          nameValuePairs)); 
        //ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
        //final String response = httpclient.execute(httppost, 
         // responseHandler); 
        response = httpclient.execute(httppost); 
        String responseBody = EntityUtils.toString(response.getEntity()); 
        utils.showToast("reached end-"+responseBody); 
        Log.i(TAG, "Response : " + responseBody); 
        if (responseBody.trim().isEmpty()) { 
         Log.d(TAG, "Message Not Sent"); 
        } 
        else 
         utils.showToast("msg sent"); 

       } catch (Exception e) { 
        //utils.showToast("exception-"+e.getMessage()); 
        Log.d(TAG, "Exception : " + e.getMessage()); 
       } 
      } 
     }; 

     thread.start(); 

    } 

} 

public void onDestroy() { 
    super.onDestroy(); 
    unregisterReceiver(broadcastReceiver); 
} 

ChatPeople addToChat(String personName, String chatMessage, String toOrFrom) { 

    Log.i(TAG, "inserting : " + personName + ", " + chatMessage + ", " 
      + toOrFrom + " , " + chattingToDeviceID); 
    ChatPeople curChatObj = new ChatPeople(); 
    curChatObj.setPERSON_NAME(personName); 
    curChatObj.setPERSON_CHAT_MESSAGE(chatMessage); 
    curChatObj.setPERSON_CHAT_TO_FROM(toOrFrom); 
    curChatObj.setPERSON_DEVICE_ID(chattingToDeviceID); 
    curChatObj.setPERSON_EMAIL("[email protected]"); 

    return curChatObj; 

} 

public void onClick(final View view) { 

    if (view == findViewById(R.id.send)) { 

     ChatPeople curChatObj = addToChat(chattingToName, edtMessage 
       .getText().toString().trim(), "Sent"); 
     addToDB(curChatObj); // adding to db 

     sendMessage(); 

     clearMessageTextBox(); 

    } 

} 
} 

回答

0

GCM可以帮助你显示在通知屏幕的名称和消息。 当您点击它时,会根据您的喜好(您的方案中的Chatactivity)打开所需的活动。

现在的重点是,GCM的工作是通知发送消息的用户和一个短消息字符串。 当您打开ChatActivity时,在onCreate方法中,您自己(从服务器数据库或存储的任何位置)加载新消息,并将其显示给用户。 它不是GCM的作业在Activity打开后加载消息。 你应该手动加载消息。

0

sendNotification方法,您需要更改以下行:

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ChatActivity.class), 0);

你要创建的意图(ChatActivity.class)之前,该行并设置其附加功能。从传递到onHandleIntent的意图中获取额外信息并将其添加到您创建的意图中。

请记住,您需要添加一些标志以避免多个显示的通知出现混淆。阅读this post了解更多详情。

相关问题