Home » Android » android – Is there any way to get the device notification history?

android – Is there any way to get the device notification history?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m developing an usage statistics app and I’m wondering how other apps can access to the devices notification history.

Right now I’m working with NotificationListenerService, but this only can handle the new notifications received, not the past ones.
I’ve checked Android DOC and found some methods which are ‘system only’ , like getHistoricalNotifications(), or that require ACCESS_NOTIFICATION permission.

The thing is that there are a few apps out there which actually can access to notification history data.

Android DOC also shows a new API on Android Q called NotificationStats but is not available at the moment.

Any tips? Is this even possible in a non-hacky way?

How to&Answers:

ActionDash shows this enter image description here

As mentioned by you getHistoricalNotifications is a system-level API only accessed by system apps, so Google Digital Wellbeing being a system app can show these.

So I think there is no way to get a history of notifications for 3rd party apps.

/**
         * System-only API for getting a list of recent (cleared, no longer shown) notifications.
         *
         * Requires ACCESS_NOTIFICATIONS which is signature|system.
         */
        @Override
        public StatusBarNotification[] getHistoricalNotifications(String callingPkg, int count) {
            // enforce() will ensure the calling uid has the correct permission
            getContext().enforceCallingOrSelfPermission(
                    android.Manifest.permission.ACCESS_NOTIFICATIONS,
                    "NotificationManagerService.getHistoricalNotifications");

            StatusBarNotification[] tmp = null;
            int uid = Binder.getCallingUid();

            // noteOp will check to make sure the callingPkg matches the uid
            if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
                    == AppOpsManager.MODE_ALLOWED) {
                synchronized (mArchive) {
                    tmp = mArchive.getArray(count);
                }
            }
            return tmp;
        }

Answer:

You should store the app notification data when notification is received into the sql database and when you want the history of the respective application’s notification, you can easily get all notification by putting a query into the sql database.