簡體   English   中英

如何使用刪除意圖對清除通知執行某些操作?

[英]how to use delete intent to perform some action on clear notification?

當用戶清除我的通知時,我想重置我的服務變量:這就是全部!

環顧四周,我看到每個人都建議在我的通知上添加刪除意圖,但意圖用於啟動活動,服務o無論什么時候我只需要這樣的事情:

void onClearPressed(){
   aVariable = 0;
}

如何獲得這個結果?

通知不是由您的應用管理的,所有顯示通知和清除通知的內容實際上都發生在另一個進程中。 由於安全原因,您不能讓另一個應用程序直接執行一段代碼。

在您的情況下,唯一的可能性是提供一個PendingIntent ,它只包含一個常規的Intent,並在通知被清除時代表您的應用程序啟動。 您需要使用PendingIntent發送廣播或啟動服務,然后在廣播接收器或服務中執行您想要的操作。 究竟要使用什么取決於您顯示通知的應用程序組件。

在廣播接收器的情況下,您可以為廣播接收器創建一個匿名內部類,並在顯示通知之前動態注冊它。 它看起來像這樣:

public class NotificationHelper {
    private static final String NOTIFICATION_DELETED_ACTION = "NOTIFICATION_DELETED";

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            aVariable = 0; // Do what you want here
            unregisterReceiver(this);
        }
    };

    public void showNotification(Context ctx, String text) {
        Intent intent = new Intent(NOTIFICATION_DELETED_ACTION);
        PendingIntent pendintIntent = PendingIntent.getBroadcast(ctx, 0, intent, 0);
        registerReceiver(receiver, new IntentFilter(NOTIFICATION_DELETED_ACTION));
        Notification n = new Notification.Builder(mContext).
          setContentText(text).
          setDeleteIntent(pendintIntent).
          build();
        NotificationManager.notify(0, n);
    }
}

安德烈是對的。
如果您想要多條消息,例如:

  • 您想知道郵件是否被點擊了
  • 你附加了一個你想要抓住的圖標的動作
  • 並且您想知道消息是否被取消

您必須注冊每個響應過濾器:

public void showNotification(Context ctx, String text) ()
{
    /… create intents and pending intents same format as Andrie did../
    /… you could also set up the style of your message box etc. …/

    //need to register each response filter
    registerReceiver(receiver, new IntentFilter(CLICK_ACTION));
    registerReceiver(receiver, new IntentFilter(USER_RESPONSE_ACTION));
    registerReceiver(receiver, new IntentFilter(NOTIFICATION_DELETED_ACTION));

    Notification n = new Notification.Builder(mContext)
      .setContentText(text)
      .setContentIntent(pendingIntent)                          //Click action
      .setDeleteIntent(pendingCancelIntent)                     //Cancel/Deleted action
      .addAction(R.drawable.icon, "Title", pendingActionIntent) //Response action
      .build();

    NotificationManager.notify(0, n);

}

然后你可以使用if,else語句(如Andrei所做的)或switch語句來捕獲不同的響應。

注意:我做出這個回應主要是因為我無法在任何地方找到它,我必須自己解決這個問題。 (也許我會更好地記住它:-)玩得開心!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM