我正在接收来自GCM的消息。AlertDialog在GCM消息每次显示后应用程序已打开
这是我处理如何在我的GCMBaseIntentService接收消息:
@Override
protected void onMessage(Context context, Intent intent) {
String msg = intent.getExtras().getString("message");
generateNotification(context, msg);
}
private static void generateNotification(Context context, String message) {
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MyClass.class);
notificationIntent.putExtra("message", message);
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;
notification.defaults|= Notification.DEFAULT_LIGHTS;
notification.defaults|= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notificationManager.notify(0, notification);
}
在MyClass
我有这样的onResume
:出现在状态栏中
String msg = this.getIntent().getStringExtra("message");
if(msg != null){
new AlertDialog.Builder(this)
.setTitle("New Notification")
.setMessage(msg)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create().show();
}
的GCM消息。一旦通知被点击,MyClass
打开并出现上面的AlertDialog
。
我会从MyClass
导航到一个新的活动,点击后退或点击回家。当我回到那个活动时,每次我返回时都会出现`AlertDialog`。
我该如何预防?我认为AlertDialog
只会在状态栏中的通知被点击后立即出现一次。
UPDATE:
因此,我认为正在发生的事情是,当我创建一个从GCM消息通知(generateNotification
),它会打开这个新意图的活动。现在每次打开此活动时,都会重复使用同一个意图,以便再次读取附加内容,然后显示警报。我仍然不知道如何阻止这一点。
我想我会尝试存储一个SharedPreference
作为额外的意图的时间戳。然后,如果msg == null
和时间戳是新的,我将只显示警报。
我喜欢devunwired的回答,但如果任何人都好奇,将时间戳存储在共享首选项中也可以。
这是我是如何实现它:(在MyClass
我这个在onResume
)
String msg = this.getIntent().getStringExtra("message");
if(msg != null){
long newTime = intent.getLongExtra("intentTime", 0);
long oldTime = preferences.getLong("intentTime", 0);
if(newTime > oldTime){
new AlertDialog.Builder(this)
.setTitle("New Notification")
.setMessage(msg)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create().show();
}
}
谢谢你的回答和解释。关于使用'setIntent'的好主意。我试图找出一种方法来做到这一点,但没有意识到这种方法。我正在使用最近的菜单重新启动应用程序,我不知道它会使用以前的意图。有趣。谢谢。 – Ryan
使用'SharedPreference'来存储时间戳也起作用。你的答案似乎更清洁,更好。 – Ryan
我知道这是一个旧帖子,但即使我回到活动时,它仍然显示相同的问题,并再次显示通知。你能帮我解决问题吗? – Kevin