我做了一个GCM聊天应用程序。我面临的问题是我无法从接收方收到的通知中获取消息内容和发件人姓名。当我点击通知图标时,它会转到我的聊天活动,但不会显示消息,也不会显示发件人的姓名。 Plz帮助我使用pending intent
解决了这个问题。这是GcmIntentService.java
。
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(), "demo_email@email.com");
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("demo@gmail.com");
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 :(得分:0)
GCM 可以帮助您在通知屏幕中显示名称和消息。
单击它时,它会根据您的喜好打开所需的活动(在您的方案中为Declare @Var nvarchar(MAX)
Set @Var ='188,189,190,191,192,193,194'
DECLARE @XML AS XML
DECLARE @Delimiter AS CHAR(1) =','
SET @XML = CAST(('<X>'+REPLACE(@Var,@Delimiter ,'</X><X>')+'</X>') AS XML)
DECLARE @temp TABLE (ID INT)
INSERT INTO @temp
SELECT N.value('.', 'INT') AS ID FROM @XML.nodes('X') AS T(N)
SELECT * FROM @temp
。)
现在重点是, GCM的工作是通知正在发送消息的用户和短消息字符串。
当您在Chatactivity
方法中打开ChatActivity
时,请自行加载新邮件(从服务器数据库或存储它们的任何位置),并将其显示给用户。
在onCreate
打开后加载消息不是GCM
的工作。 您应手动加载邮件。
答案 1 :(得分:0)
在sendNotification
方法中,您需要更改以下行:
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ChatActivity.class), 0);
您必须在此行之前创建intent(ChatActivity.class)并设置其附加内容。从传递到onHandleIntent
的意图中获取额外内容,并将它们添加到您正在创建的意图中。
请记住,您需要添加一些标记,以避免在多个显示通知的情况下出现混淆。请阅读this post了解详情。