[英]Generic Listener when a notification is clicked or dismissed in Android
我想知道NotificationListenerService是否有一種方法可以知道是否已單擊Notification或已將其解除。 我可以看到NotificationListenerService中的Inner類NotificationListenerWrapper有一個onNotificationClick()方法,但由於NotificationListenerWrapper被@hide注釋隱藏,我無法使用它。
我的問題是我可以編寫一個監聽器,它基本上可以跟蹤通知是否被點擊或被解雇。
基本上我想跟蹤我的應用程序的通知是否被解雇或者是否在每個通知中沒有任何侵入性代碼的情況下被點擊。
PS NotificationListenerService僅提供onNotificationPosted()和onNotificationRemoved(),但我的要求是知道是否單擊或刪除了通知。
謝謝
當您創建並顯示通知時,您可以為其單擊時提供PendingIntent
(使用.setContentIntent
)。 您還可以定義PendingIntent
何時被解除(使用.setDeleteIntent(PendingIntent)
。
如果您希望能夠跟蹤通知,則需要傳遞PendingIntent(如BroadcastReceiver或IntentService)並傳遞一些參數,如notificationId和isDismissed,並在BroadcastReceiver中完成您的工作。
您可以在此答案中看到完整的代碼。
我認為沒有聽眾。 但是您可以使用PendingIntent
和BroadcastReceiver
以另一種方式實現此邏輯
對於OnClick
添加ContentIntent
和BroadcastReceiver
。 因此,您將知道在BroadcastReceiver
是否單擊了您的通知
Intent onClickIntent = new Intent(this, OnClickBroadcastReceiver.class);
PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, onClickIntent, 0);
mBuilder.setContentIntent(onClickPendingIntent);
在BroadcastReceiver
您可以編寫邏輯
public class OnClickBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Open your activity here
Intent mainIntent = new Intent(context, YourActivity.class);
context.startActivity(mainIntent);
// Do your onClick related logic here
}
}
對於onDismiss
為此,您需要在通知構建器中添加DeleteIntent
Intent onCancelIntent = new Intent(this, OnCancelBroadcastReceiver.class);
PendingIntent onDismissPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, onCancelIntent, 0);
mBuilder.setDeleteIntent(onDismissPendingIntent);
和BroadcastReceiver
就是這樣
public class OnCancelBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Do your logic here
}
}
不要忘記將這些BroadcastReceiver
注冊到AndroidManifest
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.