NotificationUsageStats.java revision 711259a9e4ce842265874f76ee391e1734dd9b5b
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    private static final boolean ENABLE_SQLITE_LOG = false;
50
51    // Guarded by synchronized(this).
52    private final Map<String, AggregatedStats> mStats = new HashMap<String, AggregatedStats>();
53    private final SQLiteLog mSQLiteLog;
54
55    public NotificationUsageStats(Context context) {
56        mSQLiteLog = ENABLE_SQLITE_LOG ? new SQLiteLog(context) : null;
57    }
58
59    /**
60     * Called when a notification has been posted.
61     */
62    public synchronized void registerPostedByApp(NotificationRecord notification) {
63        notification.stats = new SingleNotificationStats();
64        notification.stats.posttimeElapsedMs = SystemClock.elapsedRealtime();
65        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
66            stats.numPostedByApp++;
67        }
68        if (ENABLE_SQLITE_LOG) {
69            mSQLiteLog.logPosted(notification);
70        }
71    }
72
73    /**
74     * Called when a notification has been updated.
75     */
76    public void registerUpdatedByApp(NotificationRecord notification, NotificationRecord old) {
77        notification.stats = old.stats;
78        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
79            stats.numUpdatedByApp++;
80        }
81    }
82
83    /**
84     * Called when the originating app removed the notification programmatically.
85     */
86    public synchronized void registerRemovedByApp(NotificationRecord notification) {
87        notification.stats.onRemoved();
88        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
89            stats.numRemovedByApp++;
90            stats.collect(notification.stats);
91        }
92        if (ENABLE_SQLITE_LOG) {
93            mSQLiteLog.logRemoved(notification);
94        }
95    }
96
97    /**
98     * Called when the user dismissed the notification via the UI.
99     */
100    public synchronized void registerDismissedByUser(NotificationRecord notification) {
101        notification.stats.onDismiss();
102        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
103            stats.numDismissedByUser++;
104            stats.collect(notification.stats);
105        }
106        if (ENABLE_SQLITE_LOG) {
107            mSQLiteLog.logDismissed(notification);
108        }
109    }
110
111    /**
112     * Called when the user clicked the notification in the UI.
113     */
114    public synchronized void registerClickedByUser(NotificationRecord notification) {
115        notification.stats.onClick();
116        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
117            stats.numClickedByUser++;
118        }
119        if (ENABLE_SQLITE_LOG) {
120            mSQLiteLog.logClicked(notification);
121        }
122    }
123
124    /**
125     * Called when the notification is canceled because the user clicked it.
126     *
127     * <p>Called after {@link #registerClickedByUser(NotificationRecord)}.</p>
128     */
129    public synchronized void registerCancelDueToClick(NotificationRecord notification) {
130        notification.stats.onCancel();
131        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
132            stats.collect(notification.stats);
133        }
134    }
135
136    /**
137     * Called when the notification is canceled due to unknown reasons.
138     *
139     * <p>Called for notifications of apps being uninstalled, for example.</p>
140     */
141    public synchronized void registerCancelUnknown(NotificationRecord notification) {
142        notification.stats.onCancel();
143        for (AggregatedStats stats : getAggregatedStatsLocked(notification)) {
144            stats.collect(notification.stats);
145        }
146    }
147
148    // Locked by this.
149    private AggregatedStats[] getAggregatedStatsLocked(NotificationRecord record) {
150        StatusBarNotification n = record.sbn;
151
152        String user = String.valueOf(n.getUserId());
153        String userPackage = user + ":" + n.getPackageName();
154
155        // TODO: Use pool of arrays.
156        return new AggregatedStats[] {
157                getOrCreateAggregatedStatsLocked(user),
158                getOrCreateAggregatedStatsLocked(userPackage),
159                getOrCreateAggregatedStatsLocked(n.getKey()),
160        };
161    }
162
163    // Locked by this.
164    private AggregatedStats getOrCreateAggregatedStatsLocked(String key) {
165        AggregatedStats result = mStats.get(key);
166        if (result == null) {
167            result = new AggregatedStats(key);
168            mStats.put(key, result);
169        }
170        return result;
171    }
172
173    public synchronized void dump(PrintWriter pw, String indent) {
174        for (AggregatedStats as : mStats.values()) {
175            as.dump(pw, indent);
176        }
177        if (ENABLE_SQLITE_LOG) {
178            mSQLiteLog.dump(pw, indent);
179        }
180    }
181
182    /**
183     * Aggregated notification stats.
184     */
185    private static class AggregatedStats {
186        public final String key;
187
188        // ---- Updated as the respective events occur.
189        public int numPostedByApp;
190        public int numUpdatedByApp;
191        public int numRemovedByApp;
192        public int numClickedByUser;
193        public int numDismissedByUser;
194
195        // ----  Updated when a notification is canceled.
196        public final Aggregate posttimeMs = new Aggregate();
197        public final Aggregate posttimeToDismissMs = new Aggregate();
198        public final Aggregate posttimeToFirstClickMs = new Aggregate();
199        public final Aggregate airtimeCount = new Aggregate();
200        public final Aggregate airtimeMs = new Aggregate();
201        public final Aggregate posttimeToFirstAirtimeMs = new Aggregate();
202
203        public AggregatedStats(String key) {
204            this.key = key;
205        }
206
207        public void collect(SingleNotificationStats singleNotificationStats) {
208            posttimeMs.addSample(
209	            SystemClock.elapsedRealtime() - singleNotificationStats.posttimeElapsedMs);
210            if (singleNotificationStats.posttimeToDismissMs >= 0) {
211                posttimeToDismissMs.addSample(singleNotificationStats.posttimeToDismissMs);
212            }
213            if (singleNotificationStats.posttimeToFirstClickMs >= 0) {
214                posttimeToFirstClickMs.addSample(singleNotificationStats.posttimeToFirstClickMs);
215            }
216            airtimeCount.addSample(singleNotificationStats.airtimeCount);
217            if (singleNotificationStats.airtimeMs >= 0) {
218                airtimeMs.addSample(singleNotificationStats.airtimeMs);
219            }
220            if (singleNotificationStats.posttimeToFirstAirtimeMs >= 0) {
221                posttimeToFirstAirtimeMs.addSample(
222                        singleNotificationStats.posttimeToFirstAirtimeMs);
223            }
224        }
225
226        public void dump(PrintWriter pw, String indent) {
227            pw.println(toStringWithIndent(indent));
228        }
229
230        @Override
231        public String toString() {
232            return toStringWithIndent("");
233        }
234
235        private String toStringWithIndent(String indent) {
236            return indent + "AggregatedStats{\n" +
237                    indent + "  key='" + key + "',\n" +
238                    indent + "  numPostedByApp=" + numPostedByApp + ",\n" +
239                    indent + "  numUpdatedByApp=" + numUpdatedByApp + ",\n" +
240                    indent + "  numRemovedByApp=" + numRemovedByApp + ",\n" +
241                    indent + "  numClickedByUser=" + numClickedByUser + ",\n" +
242                    indent + "  numDismissedByUser=" + numDismissedByUser + ",\n" +
243                    indent + "  posttimeMs=" + posttimeMs + ",\n" +
244                    indent + "  posttimeToDismissMs=" + posttimeToDismissMs + ",\n" +
245                    indent + "  posttimeToFirstClickMs=" + posttimeToFirstClickMs + ",\n" +
246                    indent + "  airtimeCount=" + airtimeCount + ",\n" +
247                    indent + "  airtimeMs=" + airtimeMs + ",\n" +
248                    indent + "  posttimeToFirstAirtimeMs=" + posttimeToFirstAirtimeMs + ",\n" +
249                    indent + "}";
250        }
251    }
252
253    /**
254     * Tracks usage of an individual notification that is currently active.
255     */
256    public static class SingleNotificationStats {
257        /** SystemClock.elapsedRealtime() when the notification was posted. */
258        public long posttimeElapsedMs = -1;
259        /** Elapsed time since the notification was posted until it was first clicked, or -1. */
260        public long posttimeToFirstClickMs = -1;
261        /** Elpased time since the notification was posted until it was dismissed by the user. */
262        public long posttimeToDismissMs = -1;
263        /** Number of times the notification has been made visible. */
264        public long airtimeCount = 0;
265        /** Time in ms between the notification was posted and first shown; -1 if never shown. */
266        public long posttimeToFirstAirtimeMs = -1;
267        /**
268         * If currently visible, SystemClock.elapsedRealtime() when the notification was made
269         * visible; -1 otherwise.
270         */
271        public long currentAirtimeStartElapsedMs = -1;
272        /** Accumulated visible time. */
273        public long airtimeMs = 0;
274
275        public long getCurrentPosttimeMs() {
276            if (posttimeElapsedMs < 0) {
277                return 0;
278            }
279            return SystemClock.elapsedRealtime() - posttimeElapsedMs;
280        }
281
282        public long getCurrentAirtimeMs() {
283            long result = airtimeMs;
284            // Add incomplete airtime if currently shown.
285            if (currentAirtimeStartElapsedMs >= 0) {
286                result+= (SystemClock.elapsedRealtime() - currentAirtimeStartElapsedMs);
287            }
288            return result;
289        }
290
291        /**
292         * Called when the user clicked the notification.
293         */
294        public void onClick() {
295            if (posttimeToFirstClickMs < 0) {
296                posttimeToFirstClickMs = SystemClock.elapsedRealtime() - posttimeElapsedMs;
297            }
298        }
299
300        /**
301         * Called when the user removed the notification.
302         */
303        public void onDismiss() {
304            if (posttimeToDismissMs < 0) {
305                posttimeToDismissMs = SystemClock.elapsedRealtime() - posttimeElapsedMs;
306            }
307            finish();
308        }
309
310        public void onCancel() {
311            finish();
312        }
313
314        public void onRemoved() {
315            finish();
316        }
317
318        public void onVisibilityChanged(boolean visible) {
319            long elapsedNowMs = SystemClock.elapsedRealtime();
320            if (visible) {
321                if (currentAirtimeStartElapsedMs < 0) {
322                    airtimeCount++;
323                    currentAirtimeStartElapsedMs = elapsedNowMs;
324                }
325                if (posttimeToFirstAirtimeMs < 0) {
326                    posttimeToFirstAirtimeMs = elapsedNowMs - posttimeElapsedMs;
327                }
328            } else {
329                if (currentAirtimeStartElapsedMs >= 0) {
330                    airtimeMs += (elapsedNowMs - currentAirtimeStartElapsedMs);
331                    currentAirtimeStartElapsedMs = -1;
332                }
333            }
334        }
335
336        /** The notification is leaving the system. Finalize. */
337        public void finish() {
338            onVisibilityChanged(false);
339        }
340
341        @Override
342        public String toString() {
343            return "SingleNotificationStats{" +
344                    "posttimeElapsedMs=" + posttimeElapsedMs +
345                    ", posttimeToFirstClickMs=" + posttimeToFirstClickMs +
346                    ", posttimeToDismissMs=" + posttimeToDismissMs +
347                    ", airtimeCount=" + airtimeCount +
348                    ", airtimeMs=" + airtimeMs +
349                    ", currentAirtimeStartElapsedMs=" + currentAirtimeStartElapsedMs +
350                    '}';
351        }
352    }
353
354    /**
355     * Aggregates long samples to sum and averages.
356     */
357    public static class Aggregate {
358        long numSamples;
359        double avg;
360        double sum2;
361        double var;
362
363        public void addSample(long sample) {
364            // Welford's "Method for Calculating Corrected Sums of Squares"
365            // http://www.jstor.org/stable/1266577?seq=2
366            numSamples++;
367            final double n = numSamples;
368            final double delta = sample - avg;
369            avg += (1.0 / n) * delta;
370            sum2 += ((n - 1) / n) * delta * delta;
371            final double divisor = numSamples == 1 ? 1.0 : n - 1.0;
372            var = sum2 / divisor;
373        }
374
375        @Override
376        public String toString() {
377            return "Aggregate{" +
378                    "numSamples=" + numSamples +
379                    ", avg=" + avg +
380                    ", var=" + var +
381                    '}';
382        }
383    }
384
385    private static class SQLiteLog {
386        private static final String TAG = "NotificationSQLiteLog";
387
388        // Message types passed to the background handler.
389        private static final int MSG_POST = 1;
390        private static final int MSG_CLICK = 2;
391        private static final int MSG_REMOVE = 3;
392        private static final int MSG_DISMISS = 4;
393
394        private static final String DB_NAME = "notification_log.db";
395        private static final int DB_VERSION = 2;
396
397        /** Age in ms after which events are pruned from the DB. */
398        private static final long HORIZON_MS = 7 * 24 * 60 * 60 * 1000L;  // 1 week
399        /** Delay between pruning the DB. Used to throttle pruning. */
400        private static final long PRUNE_MIN_DELAY_MS = 6 * 60 * 60 * 1000L;  // 6 hours
401        /** Mininum number of writes between pruning the DB. Used to throttle pruning. */
402        private static final long PRUNE_MIN_WRITES = 1024;
403
404        // Table 'log'
405        private static final String TAB_LOG = "log";
406        private static final String COL_EVENT_USER_ID = "event_user_id";
407        private static final String COL_EVENT_TYPE = "event_type";
408        private static final String COL_EVENT_TIME = "event_time_ms";
409        private static final String COL_KEY = "key";
410        private static final String COL_PKG = "pkg";
411        private static final String COL_NOTIFICATION_ID = "nid";
412        private static final String COL_TAG = "tag";
413        private static final String COL_WHEN_MS = "when_ms";
414        private static final String COL_DEFAULTS = "defaults";
415        private static final String COL_FLAGS = "flags";
416        private static final String COL_PRIORITY = "priority";
417        private static final String COL_CATEGORY = "category";
418        private static final String COL_ACTION_COUNT = "action_count";
419        private static final String COL_POSTTIME_MS = "posttime_ms";
420        private static final String COL_AIRTIME_MS = "airtime_ms";
421
422        private static final int EVENT_TYPE_POST = 1;
423        private static final int EVENT_TYPE_CLICK = 2;
424        private static final int EVENT_TYPE_REMOVE = 3;
425        private static final int EVENT_TYPE_DISMISS = 4;
426
427        private static long sLastPruneMs;
428        private static long sNumWrites;
429
430        private final SQLiteOpenHelper mHelper;
431        private final Handler mWriteHandler;
432
433        private static final long DAY_MS = 24 * 60 * 60 * 1000;
434
435        public SQLiteLog(Context context) {
436            HandlerThread backgroundThread = new HandlerThread("notification-sqlite-log",
437                    android.os.Process.THREAD_PRIORITY_BACKGROUND);
438            backgroundThread.start();
439            mWriteHandler = new Handler(backgroundThread.getLooper()) {
440                @Override
441                public void handleMessage(Message msg) {
442                    NotificationRecord r = (NotificationRecord) msg.obj;
443                    long nowMs = System.currentTimeMillis();
444                    switch (msg.what) {
445                        case MSG_POST:
446                            writeEvent(r.sbn.getPostTime(), EVENT_TYPE_POST, r);
447                            break;
448                        case MSG_CLICK:
449                            writeEvent(nowMs, EVENT_TYPE_CLICK, r);
450                            break;
451                        case MSG_REMOVE:
452                            writeEvent(nowMs, EVENT_TYPE_REMOVE, r);
453                            break;
454                        case MSG_DISMISS:
455                            writeEvent(nowMs, EVENT_TYPE_DISMISS, r);
456                            break;
457                        default:
458                            Log.wtf(TAG, "Unknown message type: " + msg.what);
459                            break;
460                    }
461                }
462            };
463            mHelper = new SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
464                @Override
465                public void onCreate(SQLiteDatabase db) {
466                    db.execSQL("CREATE TABLE " + TAB_LOG + " (" +
467                            "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
468                            COL_EVENT_USER_ID + " INT," +
469                            COL_EVENT_TYPE + " INT," +
470                            COL_EVENT_TIME + " INT," +
471                            COL_KEY + " TEXT," +
472                            COL_PKG + " TEXT," +
473                            COL_NOTIFICATION_ID + " INT," +
474                            COL_TAG + " TEXT," +
475                            COL_WHEN_MS + " INT," +
476                            COL_DEFAULTS + " INT," +
477                            COL_FLAGS + " INT," +
478                            COL_PRIORITY + " INT," +
479                            COL_CATEGORY + " TEXT," +
480                            COL_ACTION_COUNT + " INT," +
481                            COL_POSTTIME_MS + " INT," +
482                            COL_AIRTIME_MS + " INT" +
483                            ")");
484                }
485
486                @Override
487                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
488                    switch (oldVersion) {
489                        case 1:
490                            // Add COL_POSTTIME_MS, COL_AIRTIME_MS columns,
491                            db.execSQL("ALTER TABLE " + TAB_LOG + " ADD COLUMN " +
492                                    COL_POSTTIME_MS + " INT");
493                            db.execSQL("ALTER TABLE " + TAB_LOG + " ADD COLUMN " +
494                                    COL_AIRTIME_MS + " INT");
495                    }
496                }
497            };
498        }
499
500        public void logPosted(NotificationRecord notification) {
501            mWriteHandler.sendMessage(mWriteHandler.obtainMessage(MSG_POST, notification));
502        }
503
504        public void logClicked(NotificationRecord notification) {
505            mWriteHandler.sendMessage(mWriteHandler.obtainMessage(MSG_CLICK, notification));
506        }
507
508        public void logRemoved(NotificationRecord notification) {
509            mWriteHandler.sendMessage(mWriteHandler.obtainMessage(MSG_REMOVE, notification));
510        }
511
512        public void logDismissed(NotificationRecord notification) {
513            mWriteHandler.sendMessage(mWriteHandler.obtainMessage(MSG_DISMISS, notification));
514        }
515
516        public void printPostFrequencies(PrintWriter pw, String indent) {
517            SQLiteDatabase db = mHelper.getReadableDatabase();
518            long nowMs = System.currentTimeMillis();
519            String q = "SELECT " +
520                    COL_EVENT_USER_ID + ", " +
521                    COL_PKG + ", " +
522                    // Bucket by day by looking at 'floor((nowMs - eventTimeMs) / dayMs)'
523                    "CAST(((" + nowMs + " - " + COL_EVENT_TIME + ") / " + DAY_MS + ") AS int) " +
524                        "AS day, " +
525                    "COUNT(*) AS cnt " +
526                    "FROM " + TAB_LOG + " " +
527                    "WHERE " +
528                    COL_EVENT_TYPE + "=" + EVENT_TYPE_POST + " " +
529                    "GROUP BY " + COL_EVENT_USER_ID + ", day, " + COL_PKG;
530            Cursor cursor = db.rawQuery(q, null);
531            try {
532                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
533                    int userId = cursor.getInt(0);
534                    String pkg = cursor.getString(1);
535                    int day = cursor.getInt(2);
536                    int count = cursor.getInt(3);
537                    pw.println(indent + "post_frequency{user_id=" + userId + ",pkg=" + pkg +
538                            ",day=" + day + ",count=" + count + "}");
539                }
540            } finally {
541                cursor.close();
542            }
543        }
544
545        private void writeEvent(long eventTimeMs, int eventType, NotificationRecord r) {
546            ContentValues cv = new ContentValues();
547            cv.put(COL_EVENT_USER_ID, r.sbn.getUser().getIdentifier());
548            cv.put(COL_EVENT_TIME, eventTimeMs);
549            cv.put(COL_EVENT_TYPE, eventType);
550            putNotificationIdentifiers(r, cv);
551            if (eventType == EVENT_TYPE_POST) {
552                putNotificationDetails(r, cv);
553            } else {
554                putPosttimeAirtime(r, cv);
555            }
556            SQLiteDatabase db = mHelper.getWritableDatabase();
557            if (db.insert(TAB_LOG, null, cv) < 0) {
558                Log.wtf(TAG, "Error while trying to insert values: " + cv);
559            }
560            sNumWrites++;
561            pruneIfNecessary(db);
562        }
563
564        private void pruneIfNecessary(SQLiteDatabase db) {
565            // Prune if we haven't in a while.
566            long nowMs = System.currentTimeMillis();
567            if (sNumWrites > PRUNE_MIN_WRITES ||
568                    nowMs - sLastPruneMs > PRUNE_MIN_DELAY_MS) {
569                sNumWrites = 0;
570                sLastPruneMs = nowMs;
571                long horizonStartMs = nowMs - HORIZON_MS;
572                int deletedRows = db.delete(TAB_LOG, COL_EVENT_TIME + " < ?",
573                        new String[] { String.valueOf(horizonStartMs) });
574                Log.d(TAG, "Pruned event entries: " + deletedRows);
575            }
576        }
577
578        private static void putNotificationIdentifiers(NotificationRecord r, ContentValues outCv) {
579            outCv.put(COL_KEY, r.sbn.getKey());
580            outCv.put(COL_PKG, r.sbn.getPackageName());
581        }
582
583        private static void putNotificationDetails(NotificationRecord r, ContentValues outCv) {
584            outCv.put(COL_NOTIFICATION_ID, r.sbn.getId());
585            if (r.sbn.getTag() != null) {
586                outCv.put(COL_TAG, r.sbn.getTag());
587            }
588            outCv.put(COL_WHEN_MS, r.sbn.getPostTime());
589            outCv.put(COL_FLAGS, r.getNotification().flags);
590            outCv.put(COL_PRIORITY, r.getNotification().priority);
591            if (r.getNotification().category != null) {
592                outCv.put(COL_CATEGORY, r.getNotification().category);
593            }
594            outCv.put(COL_ACTION_COUNT, r.getNotification().actions != null ?
595                    r.getNotification().actions.length : 0);
596        }
597
598        private static void putPosttimeAirtime(NotificationRecord r, ContentValues outCv) {
599            outCv.put(COL_POSTTIME_MS, r.stats.getCurrentPosttimeMs());
600            outCv.put(COL_AIRTIME_MS, r.stats.getCurrentAirtimeMs());
601        }
602
603        public void dump(PrintWriter pw, String indent) {
604            printPostFrequencies(pw, indent);
605        }
606    }
607}
608