Rfo*_*rch 4 java notifications android notification-listener
我知道这看起来像是Android NotificationListenerService onNotificationPosted 两次触发的副本,并且NotificationListenerService onNotificationPosted() 当它是分组通知的一部分时为单个 Notification 多次调用,但我已经尝试了他们的解决方案,但它们似乎不起作用。
我想要做的就是拥有一个后台服务,该服务计算一个人通过电话收到的通知数量,然后将其写入文本文件。
它适用于短信和环聊通知(即每个通知只触发一次)但是当我使用 WhatsApp 和 Gmail 测试它时,它被触发两次,因此,对于每个 Gmail 通知,我的文本文件中有两行。
这是我的代码。任何帮助将不胜感激。
public class NotifCounterService extends NotificationListenerService {
public static String TAG = NotifCounterService.class.getSimpleName();
Date dateStart;
private Logger logger;
private Context mContext;
@Override
public void onCreate() {
Log.d(TAG, "Created");
logger = new Logger(TAG);
mContext = getApplicationContext();
}
@Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.d(TAG, "Notification has arrived");
Log.d(TAG, "ID: " + sbn.getId() + " Posted by: " + sbn.getPackageName() + " at: " + sbn.getPostTime() + " ");
logger.i(sbn.getId() + "," + sbn.getPackageName() + "," + sbn.getPostTime(), mContext);
logger.close();
/*
* Log.i(TAG, "ID:" + sbn.getId()); Log.i(TAG, "Posted by:" +
* sbn.getPackageName()); Log.i(TAG, "tickerText:" +
* sbn.getNotification().tickerText);
*/
/*
* for (String key : sbn.getNotification().extras.keySet()) { Log.i(TAG, key +
* "=" + sbn.getNotification().extras.get(key).toString()); }
*/
}
}
Run Code Online (Sandbox Code Playgroud)
Jrs*_*s42 10
发生这种情况是因为 WhatsApp 和 Gmail 会与其他通知一起发送群组摘要通知。
相关标志记录在此处:https : //developer.android.com/reference/android/app/Notification.html#FLAG_GROUP_SUMMARY
您可以像这样忽略带有此标志的通知:
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
//Ignore the notification
return;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
您的代码看起来不错,我认为这更有可能是该应用程序处理通知的方式,您可以做的是如果应用程序尝试同时创建多个通知,则创建一个标志:
public void timeCheck(){
if(timeCheck = true){
timeCheck = false;
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
timeCheck = true;
notificationSamePackage = "";
}
}.start();
}
}
......
......
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
if (notificationFromSamePackage != sbn.getPackageName() && timeCheck){
Log.d(TAG, "Notification has arrived");
Log.d(TAG, "ID: " + sbn.getId() + " Posted by: " + sbn.getPackageName() + " at: " + sbn.getPostTime() + " ");
logger.i(sbn.getId() + "," + sbn.getPackageName() + "," + sbn.getPostTime(), mContext);
logger.close();
notificationSamePackage = sbn.getPackageName();
timeCheck();
}
}
Run Code Online (Sandbox Code Playgroud)
边走边写,代码可能需要检查
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
2452 次 |
| 最近记录: |