从状态栏中删除通知图标

时间:2010-05-15 10:22:17

标签: android

我在状态栏中显示一个图标。现在我想在打开该内容时立即删除该图标,一段时间后如果我们收到任何提醒,该图标将再次显示。我怎么能这样做?

4 个答案:

答案 0 :(得分:36)

使用NotificationManager取消通知。您只需提供通知ID。

https://developer.android.com/reference/android/app/NotificationManager.html

private static final int MY_NOTIFICATION_ID= 1234;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.notify(MY_NOTIFICATION_ID, notification);

示例代码不完整。这取决于您创建通知的方式。 只需确保使用相同的ID取消您在创建通知时使用的通知。

取消:

mNotificationManager.cancel(MY_NOTIFICATION_ID);

答案 1 :(得分:15)

如果您想在用户点击通知时删除通知,请在创建通知之前设置通知标记FLAG_AUTO_CANCEL

答案 2 :(得分:1)

我使用了构建器模式,因此您可以从setter setAutoCancel(true)设置自动取消。看起来像这样:

    String title = "Requests"; 
    String msg = "New requests available.";
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_gcm_icon)
                    .setContentTitle(title)
                    .setAutoCancel(true)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(msg))
                    .setContentText(msg);

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

答案 3 :(得分:-1)

Intent resultIntent = new Intent(application, MainActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultPendingIntent = PendingIntent.getActivity(application, 0, resultIntent, 0);
NotificationManager nmgr = (NotificationManager) application.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(application)
            .setSmallIcon(R.drawable.icon_battery)
            .setContentTitle(application.getString(R.string.app_name))
            .setContentText("your text")
            .setOnlyAlertOnce(false)
            .setAutoCancel(true)
            .setTicker("your ticker")
            .setDefaults(Notification.DEFAULT_SOUND  ) //| Notification.DEFAULT_VIBRATE
            .setContentIntent(resultPendingIntent)
            .setVisibility(VISIBILITY_SECRET)
            .setPriority(Notification.PRIORITY_MIN);

Notification mNotification = mBuilder.build();
//  mNotification.flags |= FLAG_NO_CLEAR;
nmgr.notify(0, mNotification);