2010-05-15 66 views
10

我在狀態欄中顯示一個圖標。現在,我想在打開該內容時立即刪除該圖標,過了一段時間後,如果我們收到任何警報,該圖標將再次顯示。我怎樣才能做到這一點?從狀態欄中刪除通知圖標

回答

34

使用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); 
15

如果你想一旦用戶點擊它,設置通知標誌FLAG_AUTO_CANCEL創建通知之前刪除通知。

1

我使用了生成器模式,所以你可以設置從設置器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()); 
-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);