NotificationRecord.java revision 52b7a5a5973c05fe59b751b82ee357fdfc1c5ef7
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 */
16package com.android.server.notification;
17
18import android.app.Notification;
19import android.content.Context;
20import android.content.pm.PackageManager.NameNotFoundException;
21import android.content.res.Resources;
22import android.graphics.Bitmap;
23import android.service.notification.StatusBarNotification;
24
25import java.io.PrintWriter;
26import java.lang.reflect.Array;
27import java.util.Arrays;
28
29/**
30 * Holds data about notifications that should not be shared with the
31 * {@link android.service.notification.NotificationListenerService}s.
32 *
33 * <p>These objects should not be mutated unless the code is synchronized
34 * on {@link NotificationManagerService#mNotificationList}, and any
35 * modification should be followed by a sorting of that list.</p>
36 *
37 * <p>Is sortable by {@link NotificationComparator}.</p>
38 *
39 * {@hide}
40 */
41public final class NotificationRecord {
42    final StatusBarNotification sbn;
43    NotificationUsageStats.SingleNotificationStats stats;
44    boolean isCanceled;
45    int score;
46
47    // These members are used by NotificationSignalExtractors
48    // to communicate with the ranking module.
49    private float mContactAffinity;
50    private boolean mRecentlyIntrusive;
51
52    // is this notification currently being intercepted by Zen Mode?
53    private boolean mIntercept;
54    // InterceptedNotifications needs to know if this has been previously evaluated.
55    private boolean mTouchedByZen;
56
57    // The timestamp used for ranking.
58    private long mRankingTimeMs;
59
60    // Is this record an update of an old record?
61    public boolean isUpdate;
62
63    NotificationRecord(StatusBarNotification sbn, int score)
64    {
65        this.sbn = sbn;
66        this.score = score;
67        mRankingTimeMs = calculateRankingTimeMs(0L);
68    }
69
70    // copy any notes that the ranking system may have made before the update
71    public void copyRankingInformation(NotificationRecord previous) {
72        mContactAffinity = previous.mContactAffinity;
73        mRecentlyIntrusive = previous.mRecentlyIntrusive;
74        mTouchedByZen = previous.mTouchedByZen;
75        mIntercept = previous.mIntercept;
76        mRankingTimeMs = calculateRankingTimeMs(previous.getRankingTimeMs());
77    }
78
79    public Notification getNotification() { return sbn.getNotification(); }
80    public int getFlags() { return sbn.getNotification().flags; }
81    public int getUserId() { return sbn.getUserId(); }
82    public String getKey() { return sbn.getKey(); }
83
84    void dump(PrintWriter pw, String prefix, Context baseContext) {
85        final Notification notification = sbn.getNotification();
86        pw.println(prefix + this);
87        pw.println(prefix + "  uid=" + sbn.getUid() + " userId=" + sbn.getUserId());
88        pw.println(prefix + "  icon=0x" + Integer.toHexString(notification.icon)
89                + " / " + idDebugString(baseContext, sbn.getPackageName(), notification.icon));
90        pw.println(prefix + "  pri=" + notification.priority + " score=" + sbn.getScore());
91        pw.println(prefix + "  key=" + sbn.getKey());
92        pw.println(prefix + "  contentIntent=" + notification.contentIntent);
93        pw.println(prefix + "  deleteIntent=" + notification.deleteIntent);
94        pw.println(prefix + "  tickerText=" + notification.tickerText);
95        pw.println(prefix + "  contentView=" + notification.contentView);
96        pw.println(prefix + String.format("  defaults=0x%08x flags=0x%08x",
97                notification.defaults, notification.flags));
98        pw.println(prefix + "  sound=" + notification.sound);
99        pw.println(prefix + String.format("  color=0x%08x", notification.color));
100        pw.println(prefix + "  vibrate=" + Arrays.toString(notification.vibrate));
101        pw.println(prefix + String.format("  led=0x%08x onMs=%d offMs=%d",
102                notification.ledARGB, notification.ledOnMS, notification.ledOffMS));
103        if (notification.actions != null && notification.actions.length > 0) {
104            pw.println(prefix + "  actions={");
105            final int N = notification.actions.length;
106            for (int i=0; i<N; i++) {
107                final Notification.Action action = notification.actions[i];
108                pw.println(String.format("%s    [%d] \"%s\" -> %s",
109                        prefix,
110                        i,
111                        action.title,
112                        action.actionIntent.toString()
113                        ));
114            }
115            pw.println(prefix + "  }");
116        }
117        if (notification.extras != null && notification.extras.size() > 0) {
118            pw.println(prefix + "  extras={");
119            for (String key : notification.extras.keySet()) {
120                pw.print(prefix + "    " + key + "=");
121                Object val = notification.extras.get(key);
122                if (val == null) {
123                    pw.println("null");
124                } else {
125                    pw.print(val.getClass().getSimpleName());
126                    if (val instanceof CharSequence || val instanceof String) {
127                        // redact contents from bugreports
128                    } else if (val instanceof Bitmap) {
129                        pw.print(String.format(" (%dx%d)",
130                                ((Bitmap) val).getWidth(),
131                                ((Bitmap) val).getHeight()));
132                    } else if (val.getClass().isArray()) {
133                        final int N = Array.getLength(val);
134                        pw.println(" (" + N + ")");
135                    } else {
136                        pw.print(" (" + String.valueOf(val) + ")");
137                    }
138                    pw.println();
139                }
140            }
141            pw.println(prefix + "  }");
142        }
143        pw.println(prefix + "  stats=" + stats.toString());
144        pw.println(prefix + "  mContactAffinity=" + mContactAffinity);
145        pw.println(prefix + "  mRecentlyIntrusive=" + mRecentlyIntrusive);
146        pw.println(prefix + "  mIntercept=" + mIntercept);
147        pw.println(prefix + "  mRankingTimeMs=" + mRankingTimeMs);
148    }
149
150
151    static String idDebugString(Context baseContext, String packageName, int id) {
152        Context c;
153
154        if (packageName != null) {
155            try {
156                c = baseContext.createPackageContext(packageName, 0);
157            } catch (NameNotFoundException e) {
158                c = baseContext;
159            }
160        } else {
161            c = baseContext;
162        }
163
164        Resources r = c.getResources();
165        try {
166            return r.getResourceName(id);
167        } catch (Resources.NotFoundException e) {
168            return "<name unknown>";
169        }
170    }
171
172    @Override
173    public final String toString() {
174        return String.format(
175                "NotificationRecord(0x%08x: pkg=%s user=%s id=%d tag=%s score=%d key=%s: %s)",
176                System.identityHashCode(this),
177                this.sbn.getPackageName(), this.sbn.getUser(), this.sbn.getId(),
178                this.sbn.getTag(), this.sbn.getScore(), this.sbn.getKey(),
179                this.sbn.getNotification());
180    }
181
182    public void setContactAffinity(float contactAffinity) {
183        mContactAffinity = contactAffinity;
184    }
185
186    public float getContactAffinity() {
187        return mContactAffinity;
188    }
189
190    public void setRecentlyIntusive(boolean recentlyIntrusive) {
191        mRecentlyIntrusive = recentlyIntrusive;
192    }
193
194    public boolean isRecentlyIntrusive() {
195        return mRecentlyIntrusive;
196    }
197
198    public boolean setIntercepted(boolean intercept) {
199        mIntercept = intercept;
200        return mIntercept;
201    }
202
203    public boolean isIntercepted() {
204        return mIntercept;
205    }
206
207    public boolean wasTouchedByZen() {
208        return mTouchedByZen;
209    }
210
211    public void setTouchedByZen() {
212        mTouchedByZen = true;
213    }
214
215    /**
216     * Returns the timestamp to use for time-based sorting in the ranker.
217     */
218    public long getRankingTimeMs() {
219        return mRankingTimeMs;
220    }
221
222    /**
223     * @param previousRankingTimeMs for updated notifications, {@link #getRankingTimeMs()}
224     *     of the previous notification record, 0 otherwise
225     */
226    private long calculateRankingTimeMs(long previousRankingTimeMs) {
227        Notification n = getNotification();
228        // Take developer provided 'when', unless it's in the future.
229        if (n.when != 0 && n.when <= sbn.getPostTime()) {
230            return n.when;
231        }
232        // If we've ranked a previous instance with a timestamp, inherit it. This case is
233        // important in order to have ranking stability for updating notifications.
234        if (previousRankingTimeMs > 0) {
235            return previousRankingTimeMs;
236        }
237        return sbn.getPostTime();
238    }
239
240}
241