Android仅在消息到达时显示通知
在安卓系统中,我已经实现了谷歌云通知,它会在任何消息到达时发出通知,但即使消息在那里,它也会保持不变。安装应用程序后,它会立即在通知栏中显示图标,有没有办法只在消息到达时显示通知,并在用户单击它时将其隐藏 这是我的密码:Android仅在消息到达时显示通知,android,notifications,google-cloud-messaging,Android,Notifications,Google Cloud Messaging,在安卓系统中,我已经实现了谷歌云通知,它会在任何消息到达时发出通知,但即使消息在那里,它也会保持不变。安装应用程序后,它会立即在通知栏中显示图标,有没有办法只在消息到达时显示通知,并在用户单击它时将其隐藏 这是我的密码: private static void generateNotification(Context context, String message) { int icon = R.drawable.ic_launcher; long when = Syst
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);
String title = context.getString(R.string.app_name);
//Intent notificationIntent = new Intent(context, MainActivity.class); //Open Activity
// set intent so it does not start a new activity
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse("http://www.google.com")); //Open Link
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;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
如果看不到您在哪里接收消息,以及您想在哪里生成和取消通知,那么很难看出您需要做什么来实现这一点,但我将试一试 如果您(通过GCM)为加载示例项目,您将注意到GCM数据是以一种方式接收的。 该类有一个方法,您可以重写该方法,该方法称为
onMessage()
,每当您收到GCM消息时都将调用该方法。如果使用此方法创建通知,则应用程序将仅在收到GCM消息时生成通知
至于取消通知,您可以通过调用NotificationManager的
cancel()
方法,传递要取消的通知的ID来完成。您可能有一些向用户显示消息的活动,这将是取消与特定消息相关的任何未完成通知的好地方。是的,但是如果没有您的任何代码,很难判断您在哪里遇到问题。抱歉,Tanis.7x--刚刚更新了我的代码,这非常有帮助。谢谢,Tanis.7x也会尝试同样的方法