NotificationUsageStats.java revision 1c3f81fde944d615d566db6fbc493b25e6d2f472
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.notification;
18
19import com.android.server.notification.NotificationManagerService.NotificationRecord;
20
21import android.content.ContentValues;
22import android.content.Context;
23import android.database.Cursor;
24import android.database.sqlite.SQLiteDatabase;
25import android.database.sqlite.SQLiteOpenHelper;
26import android.os.Handler;
27import android.os.HandlerThread;
28import android.os.Message;
29import android.os.SystemClock;
30import android.service.notification.StatusBarNotification;
31import android.util.Log;
32
33import java.io.PrintWriter;
34import java.util.HashMap;
35import java.util.Map;
36
37/**
38 * Keeps track of notification activity, display, and user interaction.
39 *
40 * <p>This class receives signals from NoMan and keeps running stats of
41 * notification usage. Some metrics are updated as events occur. Others, namely
42 * those involving durations, are updated as the notification is canceled.</p>
43 *
44 * <p>This class is thread-safe.</p>
45 *
46 * {@hide}
47 */
48public class NotificationUsageStats {
49    // Guarded by synchronized(this).
50    private final Map<String, AggregatedStats> mStats = new HashMap<String, AggregatedStats>();
51    private final SQLiteLog mSQLiteLog;
52
53    public NotificationUsageStats(Context context) {
54        mSQLiteLog = new SQLiteLog(context);
55    }
56
57    /**
58     * Called when a notification has been posted.
59     */
60    public synchronized void registerPostedByApp(NotificationRecord notification) {
61        notification.stats.posttimeElapsedMs = SystemClock.elapsedRealtime();
62        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
63            stats.numPostedByApp++;
64        }
65        mSQLiteLog.logPosted(notification);
66    }
67
68    /**
69     * Called when a notification has been updated.
70     */
71    public void registerUpdatedByApp(NotificationRecord notification) {
72        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
73            stats.numUpdatedByApp++;
74        }
75    }
76
77    /**
78     * Called when the originating app removed the notification programmatically.
79     */
80    public synchronized void registerRemovedByApp(NotificationRecord notification) {
81        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
82            stats.numRemovedByApp++;
83            stats.collect(notification.stats);
84        }
85        mSQLiteLog.logRemoved(notification);
86    }
87
88    /**
89     * Called when the user dismissed the notification via the UI.
90     */
91    public synchronized void registerDismissedByUser(NotificationRecord notification) {
92        notification.stats.onDismiss();
93        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
94            stats.numDismissedByUser++;
95            stats.collect(notification.stats);
96        }
97        mSQLiteLog.logDismissed(notification);
98    }
99
100    /**
101     * Called when the user clicked the notification in the UI.
102     */
103    public synchronized void registerClickedByUser(NotificationRecord notification) {
104        notification.stats.onClick();
105        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
106            stats.numClickedByUser++;
107        }
108        mSQLiteLog.logClicked(notification);
109    }
110
111    /**
112     * Called when the notification is canceled because the user clicked it.
113     *
114     * <p>Called after {@link #registerClickedByUser(NotificationRecord)}.</p>
115     */
116    public synchronized void registerCancelDueToClick(NotificationRecord notification) {
117        // No explicit stats for this (the click has already been registered in
118        // registerClickedByUser), just make sure the single notification stats
119        // are folded up into aggregated stats.
120        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
121            stats.collect(notification.stats);
122        }
123    }
124
125    /**
126     * Called when the notification is canceled due to unknown reasons.
127     *
128     * <p>Called for notifications of apps being uninstalled, for example.</p>
129     */
130    public synchronized void registerCancelUnknown(NotificationRecord notification) {
131        // Fold up individual stats.
132        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
133            stats.collect(notification.stats);
134        }
135    }
136
137    // Locked by this.
138    private AggregatedStats[] getAggregatedStatsLocked(NotificationRecord record) {
139        StatusBarNotification n = record.sbn;
140
141        String user = String.valueOf(n.getUserId());
142        String userPackage = user + ":" + n.getPackageName();
143
144        // TODO: Use pool of arrays.
145        return new AggregatedStats[] {
146                getOrCreateAggregatedStatsLocked(user),
147                getOrCreateAggregatedStatsLocked(userPackage),
148                getOrCreateAggregatedStatsLocked(n.getKey()),
149        };
150    }
151
152    // Locked by this.
153    private AggregatedStats getOrCreateAggregatedStatsLocked(String key) {
154        AggregatedStats result = mStats.get(key);
155        if (result == null) {
156            result = new AggregatedStats(key);
157            mStats.put(key, result);
158        }
159        return result;
160    }
161
162    public synchronized void dump(PrintWriter pw, String indent) {
163        for (AggregatedStats as : mStats.values()) {
164            as.dump(pw, indent);
165        }
166        mSQLiteLog.dump(pw, indent);
167    }
168
169    /**
170     * Aggregated notification stats.
171     */
172    private static class AggregatedStats {
173        public final String key;
174
175        // ---- Updated as the respective events occur.
176        public int numPostedByApp;
177        public int numUpdatedByApp;
178        public int numRemovedByApp;
179        public int numClickedByUser;
180        public int numDismissedByUser;
181
182        // ----  Updated when a notification is canceled.
183        public final Aggregate posttimeMs = new Aggregate();
184        public final Aggregate posttimeToDismissMs = new Aggregate();
185        public final Aggregate posttimeToFirstClickMs = new Aggregate();
186
187        public AggregatedStats(String key) {
188            this.key = key;
189        }
190
191        public void collect(SingleNotificationStats singleNotificationStats) {
192            posttimeMs.addSample(
193	            SystemClock.elapsedRealtime() - singleNotificationStats.posttimeElapsedMs);
194            if (singleNotificationStats.posttimeToDismissMs >= 0) {
195                posttimeToDismissMs.addSample(singleNotificationStats.posttimeToDismissMs);
196            }
197            if (singleNotificationStats.posttimeToFirstClickMs >= 0) {
198                posttimeToFirstClickMs.addSample(singleNotificationStats.posttimeToFirstClickMs);
199            }
200        }
201
202        public void dump(PrintWriter pw, String indent) {
203            pw.println(toStringWithIndent(indent));
204        }
205
206        @Override
207        public String toString() {
208            return toStringWithIndent("");
209        }
210
211        private String toStringWithIndent(String indent) {
212            return indent + "AggregatedStats{\n" +
213                    indent + "  key='" + key + "',\n" +
214                    indent + "  numPostedByApp=" + numPostedByApp + ",\n" +
215                    indent + "  numUpdatedByApp=" + numUpdatedByApp + ",\n" +
216                    indent + "  numRemovedByApp=" + numRemovedByApp + ",\n" +
217                    indent + "  numClickedByUser=" + numClickedByUser + ",\n" +
218                    indent + "  numDismissedByUser=" + numDismissedByUser + ",\n" +
219                    indent + "  posttimeMs=" + posttimeMs + ",\n" +
220                    indent + "  posttimeToDismissMs=" + posttimeToDismissMs + ",\n" +
221                    indent + "  posttimeToFirstClickMs=" + posttimeToFirstClickMs + ",\n" +
222                    indent + "}";
223        }
224    }
225
226    /**
227     * Tracks usage of an individual notification that is currently active.
228     */
229    public static class SingleNotificationStats {
230        /** SystemClock.elapsedRealtime() when the notification was posted. */
231        public long posttimeElapsedMs = -1;
232        /** Elapsed time since the notification was posted until it was first clicked, or -1. */
233        public long posttimeToFirstClickMs = -1;
234        /** Elpased time since the notification was posted until it was dismissed by the user. */
235        public long posttimeToDismissMs = -1;
236
237        /**
238         * Called when the user clicked the notification.
239         */
240        public void onClick() {
241            if (posttimeToFirstClickMs < 0) {
242                posttimeToFirstClickMs = SystemClock.elapsedRealtime() - posttimeElapsedMs;
243            }
244        }
245
246        /**
247         * Called when the user removed the notification.
248         */
249        public void onDismiss() {
250            if (posttimeToDismissMs < 0) {
251                posttimeToDismissMs = SystemClock.elapsedRealtime() - posttimeElapsedMs;
252            }
253        }
254
255        @Override
256        public String toString() {
257            return "SingleNotificationStats{" +
258                    "posttimeElapsedMs=" + posttimeElapsedMs +
259                    ", posttimeToFirstClickMs=" + posttimeToFirstClickMs +
260                    ", posttimeToDismissMs=" + posttimeToDismissMs +
261                    '}';
262        }
263    }
264
265    /**
266     * Aggregates long samples to sum and averages.
267     */
268    public static class Aggregate {
269        long numSamples;
270        double avg;
271        double sum2;
272        double var;
273
274        public void addSample(long sample) {
275            // Welford's "Method for Calculating Corrected Sums of Squares"
276            // http://www.jstor.org/stable/1266577?seq=2
277            numSamples++;
278            final double n = numSamples;
279            final double delta = sample - avg;
280            avg += (1.0 / n) * delta;
281            sum2 += ((n - 1) / n) * delta * delta;
282            final double divisor = numSamples == 1 ? 1.0 : n - 1.0;
283            var = sum2 / divisor;
284        }
285
286        @Override
287        public String toString() {
288            return "Aggregate{" +
289                    "numSamples=" + numSamples +
290                    ", avg=" + avg +
291                    ", var=" + var +
292                    '}';
293        }
294    }
295
296    private static class SQLiteLog {
297        private static final String TAG = "NotificationSQLiteLog";
298
299        // Message types passed to the background handler.
300        private static final int MSG_POST = 1;
301        private static final int MSG_CLICK = 2;
302        private static final int MSG_REMOVE = 3;
303        private static final int MSG_DISMISS = 4;
304
305        private static final String DB_NAME = "notification_log.db";
306        private static final int DB_VERSION = 1;
307
308        /** Age in ms after which events are pruned from the DB. */
309        private static final long HORIZON_MS = 7 * 24 * 60 * 60 * 1000L;  // 1 week
310        /** Delay between pruning the DB. Used to throttle pruning. */
311        private static final long PRUNE_MIN_DELAY_MS = 6 * 60 * 60 * 1000L;  // 6 hours
312        /** Mininum number of writes between pruning the DB. Used to throttle pruning. */
313        private static final long PRUNE_MIN_WRITES = 1024;
314
315        // Table 'log'
316        private static final String TAB_LOG = "log";
317        private static final String COL_EVENT_USER_ID = "event_user_id";
318        private static final String COL_EVENT_TYPE = "event_type";
319        private static final String COL_EVENT_TIME = "event_time_ms";
320        private static final String COL_KEY = "key";
321        private static final String COL_PKG = "pkg";
322        private static final String COL_NOTIFICATION_ID = "nid";
323        private static final String COL_TAG = "tag";
324        private static final String COL_WHEN_MS = "when_ms";
325        private static final String COL_DEFAULTS = "defaults";
326        private static final String COL_FLAGS = "flags";
327        private static final String COL_PRIORITY = "priority";
328        private static final String COL_CATEGORY = "category";
329        private static final String COL_ACTION_COUNT = "action_count";
330
331        private static final int EVENT_TYPE_POST = 1;
332        private static final int EVENT_TYPE_CLICK = 2;
333        private static final int EVENT_TYPE_REMOVE = 3;
334        private static final int EVENT_TYPE_DISMISS = 4;
335
336        private static long sLastPruneMs;
337        private static long sNumWrites;
338
339        private final SQLiteOpenHelper mHelper;
340        private final Handler mWriteHandler;
341
342        private static final long DAY_MS = 24 * 60 * 60 * 1000;
343
344        public SQLiteLog(Context context) {
345            HandlerThread backgroundThread = new HandlerThread("notification-sqlite-log",
346                    android.os.Process.THREAD_PRIORITY_BACKGROUND);
347            backgroundThread.start();
348            mWriteHandler = new Handler(backgroundThread.getLooper()) {
349                @Override
350                public void handleMessage(Message msg) {
351                    NotificationRecord r = (NotificationRecord) msg.obj;
352                    long nowMs = System.currentTimeMillis();
353                    switch (msg.what) {
354                        case MSG_POST:
355                            writeEvent(r.sbn.getPostTime(), EVENT_TYPE_POST, r, true);
356                            break;
357                        case MSG_CLICK:
358                            writeEvent(nowMs, EVENT_TYPE_CLICK, r, false);
359                            break;
360                        case MSG_REMOVE:
361                            writeEvent(nowMs, EVENT_TYPE_REMOVE, r, false);
362                            break;
363                        case MSG_DISMISS:
364                            writeEvent(nowMs, EVENT_TYPE_DISMISS, r, false);
365                            break;
366                        default:
367                            Log.wtf(TAG, "Unknown message type: " + msg.what);
368                            break;
369                    }
370                }
371            };
372            mHelper = new SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
373                @Override
374                public void onCreate(SQLiteDatabase db) {
375                    db.execSQL("CREATE TABLE " + TAB_LOG + " (" +
376                            "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
377                            COL_EVENT_USER_ID + " INT," +
378                            COL_EVENT_TYPE + " INT," +
379                            COL_EVENT_TIME + " INT," +
380                            COL_KEY + " TEXT," +
381                            COL_PKG + " TEXT," +
382                            COL_NOTIFICATION_ID + " INT," +
383                            COL_TAG + " TEXT," +
384                            COL_WHEN_MS + " INT," +
385                            COL_DEFAULTS + " INT," +
386                            COL_FLAGS + " INT," +
387                            COL_PRIORITY + " INT," +
388                            COL_CATEGORY + " TEXT," +
389                            COL_ACTION_COUNT + " INT" +
390                            ")");
391                }
392
393                @Override
394                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
395                    db.execSQL("DROP TABLE IF EXISTS " + TAB_LOG);
396                    onCreate(db);
397                }
398            };
399        }
400
401        public void logPosted(NotificationRecord notification) {
402            mWriteHandler.sendMessage(mWriteHandler.obtainMessage(MSG_POST, notification));
403        }
404
405        public void logClicked(NotificationRecord notification) {
406            mWriteHandler.sendMessage(mWriteHandler.obtainMessage(MSG_CLICK, notification));
407        }
408
409        public void logRemoved(NotificationRecord notification) {
410            mWriteHandler.sendMessage(mWriteHandler.obtainMessage(MSG_REMOVE, notification));
411        }
412
413        public void logDismissed(NotificationRecord notification) {
414            mWriteHandler.sendMessage(mWriteHandler.obtainMessage(MSG_DISMISS, notification));
415        }
416
417        public void printPostFrequencies(PrintWriter pw, String indent) {
418            SQLiteDatabase db = mHelper.getReadableDatabase();
419            long nowMs = System.currentTimeMillis();
420            String q = "SELECT " +
421                    COL_EVENT_USER_ID + ", " +
422                    COL_PKG + ", " +
423                    // Bucket by day by looking at 'floor((nowMs - eventTimeMs) / dayMs)'
424                    "CAST(((" + nowMs + " - " + COL_EVENT_TIME + ") / " + DAY_MS + ") AS int) " +
425                        "AS day, " +
426                    "COUNT(*) AS cnt " +
427                    "FROM " + TAB_LOG + " " +
428                    "WHERE " +
429                    COL_EVENT_TYPE + "=" + EVENT_TYPE_POST + " " +
430                    "GROUP BY " + COL_EVENT_USER_ID + ", day, " + COL_PKG;
431            Cursor cursor = db.rawQuery(q, null);
432            try {
433                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
434                    int userId = cursor.getInt(0);
435                    String pkg = cursor.getString(1);
436                    int day = cursor.getInt(2);
437                    int count = cursor.getInt(3);
438                    pw.println(indent + "post_frequency{user_id=" + userId + ",pkg=" + pkg +
439                            ",day=" + day + ",count=" + count + "}");
440                }
441            } finally {
442                cursor.close();
443            }
444        }
445
446        private void writeEvent(long eventTimeMs, int eventType, NotificationRecord r,
447                boolean populateNotificationDetails) {
448            ContentValues cv = new ContentValues();
449            cv.put(COL_EVENT_USER_ID, r.sbn.getUser().getIdentifier());
450            cv.put(COL_EVENT_TIME, eventTimeMs);
451            cv.put(COL_EVENT_TYPE, eventType);
452            putNotificationIdentifiers(r, cv);
453            if (populateNotificationDetails) {
454                putNotificationDetails(r, cv);
455            }
456            SQLiteDatabase db = mHelper.getWritableDatabase();
457            if (db.insert(TAB_LOG, null, cv) < 0) {
458                Log.wtf(TAG, "Error while trying to insert values: " + cv);
459            }
460            sNumWrites++;
461            pruneIfNecessary(db);
462        }
463
464        private void pruneIfNecessary(SQLiteDatabase db) {
465            // Prune if we haven't in a while.
466            long nowMs = System.currentTimeMillis();
467            if (sNumWrites > PRUNE_MIN_WRITES ||
468                    nowMs - sLastPruneMs > PRUNE_MIN_DELAY_MS) {
469                sNumWrites = 0;
470                sLastPruneMs = nowMs;
471                long horizonStartMs = nowMs - HORIZON_MS;
472                int deletedRows = db.delete(TAB_LOG, COL_EVENT_TIME + " < ?",
473                        new String[] { String.valueOf(horizonStartMs) });
474                Log.d(TAG, "Pruned event entries: " + deletedRows);
475            }
476        }
477
478        private static void putNotificationIdentifiers(NotificationRecord r, ContentValues outCv) {
479            outCv.put(COL_KEY, r.sbn.getKey());
480            outCv.put(COL_PKG, r.sbn.getPackageName());
481        }
482
483        private static void putNotificationDetails(NotificationRecord r, ContentValues outCv) {
484            outCv.put(COL_NOTIFICATION_ID, r.sbn.getId());
485            if (r.sbn.getTag() != null) {
486                outCv.put(COL_TAG, r.sbn.getTag());
487            }
488            outCv.put(COL_WHEN_MS, r.sbn.getPostTime());
489            outCv.put(COL_FLAGS, r.getNotification().flags);
490            outCv.put(COL_PRIORITY, r.getNotification().priority);
491            if (r.getNotification().category != null) {
492                outCv.put(COL_CATEGORY, r.getNotification().category);
493            }
494            outCv.put(COL_ACTION_COUNT, r.getNotification().actions != null ?
495                    r.getNotification().actions.length : 0);
496        }
497
498        public void dump(PrintWriter pw, String indent) {
499            printPostFrequencies(pw, indent);
500        }
501    }
502}
503