您可以在 GCMIntentService 意图类的 onMessage 侦听器上的 SharedPreferences 中保存一些数据。GCM 监听器毕竟属于你的包应用程序。您保存的内容取决于您的应用程序和消息负载,但它可能是您想要的任何内容。然后在单击通知时启动的 Activity 的 onCreate 函数上,您阅读 Shared Preferences 以查看您是否来自 GCM 通知。请记住清除您保存在 SharedPreferences 中的变量,以便下次用户打开应用程序时,它可以正确显示内容。
你在这里有一个例子。不幸的是,我现在无法尝试,但看到这个想法很有用。它与 G2DM 非常相似,因此您必须在您的情况下寻找等价物。
public class GCMIntentService extends GCMBaseIntentService {
/*... other functions of the class */
/**
* Method called on Receiving a new message
* */
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("your_message");
// notifies user
generateNotification(context, message);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
// Save your data in the shared preferences
SharedPreferences prefs = getSharedPreferences("YourPrefs", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = prefs.edit();
prefEditor.putBoolean("comesFromGCMNotification", true);
prefEditor.commit();
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}