2010-05-15 70 views
10

Tôi đang hiển thị biểu tượng trên thanh trạng thái.Bây giờ, tôi muốn xóa biểu tượng đó ngay khi tôi mở nội dung đó, sau một thời gian nếu chúng tôi nhận được bất kỳ cảnh báo nào, biểu tượng đó sẽ được hiển thị lại. Tôi có thể làm cái này như thế nào?Xóa biểu tượng thông báo khỏi thanh trạng thái

Trả lời

34

Sử dụng Trình quản lý thông báo để hủy thông báo của bạn. Bạn chỉ cần cung cấp id thông báo của mình.

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); 

Ví dụ mã không hoàn chỉnh. Nó phụ thuộc vào cách bạn tạo thông báo của mình. Chỉ cần đảm bảo bạn sử dụng cùng một id để hủy thông báo của mình khi bạn sử dụng khi tạo thông báo.

Để hủy:

mNotificationManager.cancel(MY_NOTIFICATION_ID); 
15

Nếu bạn muốn loại bỏ các thông báo khi người dùng nhấp vào nó, thiết lập thông báo cờ FLAG_AUTO_CANCEL trước khi bạn tạo ra các thông báo.

1

Tôi đã sử dụng Trình tạo bản dựng để bạn có thể đặt tự động hủy từ công cụ đặt số setAutoCancel(true). Trông giống như sau:

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); 
Các vấn đề liên quan