• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 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 
17 package com.android.settings.notification;
18 
19 import android.app.Activity;
20 import android.app.ActivityManager;
21 import android.app.INotificationManager;
22 import android.app.Notification;
23 import android.content.ComponentName;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.pm.ApplicationInfo;
27 import android.content.pm.PackageManager;
28 import android.content.res.Resources;
29 import android.graphics.drawable.Drawable;
30 import android.net.Uri;
31 import android.os.Bundle;
32 import android.os.Handler;
33 import android.os.RemoteException;
34 import android.os.ServiceManager;
35 import android.os.UserHandle;
36 import android.service.notification.NotificationListenerService;
37 import android.service.notification.StatusBarNotification;
38 import android.util.Log;
39 import android.view.LayoutInflater;
40 import android.view.View;
41 import android.view.View.OnClickListener;
42 import android.view.ViewGroup;
43 import android.widget.ArrayAdapter;
44 import android.widget.DateTimeView;
45 import android.widget.ImageView;
46 import android.widget.ListView;
47 import android.widget.TextView;
48 
49 import com.android.internal.logging.MetricsLogger;
50 import com.android.settings.R;
51 import com.android.settings.SettingsPreferenceFragment;
52 import com.android.settings.Utils;
53 
54 import java.util.ArrayList;
55 import java.util.Comparator;
56 import java.util.List;
57 
58 public class NotificationStation extends SettingsPreferenceFragment {
59     private static final String TAG = NotificationStation.class.getSimpleName();
60 
61     private static final boolean DEBUG = false;
62 
63     private static class HistoricalNotificationInfo {
64         public String pkg;
65         public Drawable pkgicon;
66         public CharSequence pkgname;
67         public Drawable icon;
68         public CharSequence title;
69         public int priority;
70         public int user;
71         public long timestamp;
72         public boolean active;
73     }
74 
75     private PackageManager mPm;
76     private INotificationManager mNoMan;
77 
78     private Runnable mRefreshListRunnable = new Runnable() {
79         @Override
80         public void run() {
81             refreshList();
82         }
83     };
84 
85     private NotificationListenerService mListener = new NotificationListenerService() {
86         @Override
87         public void onNotificationPosted(StatusBarNotification notification) {
88             logd("onNotificationPosted: %s", notification);
89             final Handler h = getListView().getHandler();
90             h.removeCallbacks(mRefreshListRunnable);
91             h.postDelayed(mRefreshListRunnable, 100);
92         }
93 
94         @Override
95         public void onNotificationRemoved(StatusBarNotification notification) {
96             final Handler h = getListView().getHandler();
97             h.removeCallbacks(mRefreshListRunnable);
98             h.postDelayed(mRefreshListRunnable, 100);
99         }
100     };
101 
102     private NotificationHistoryAdapter mAdapter;
103     private Context mContext;
104 
105     private final Comparator<HistoricalNotificationInfo> mNotificationSorter
106             = new Comparator<HistoricalNotificationInfo>() {
107                 @Override
108                 public int compare(HistoricalNotificationInfo lhs,
109                                    HistoricalNotificationInfo rhs) {
110                     return (int)(rhs.timestamp - lhs.timestamp);
111                 }
112             };
113 
114     @Override
onAttach(Activity activity)115     public void onAttach(Activity activity) {
116         logd("onAttach(%s)", activity.getClass().getSimpleName());
117         super.onAttach(activity);
118         mContext = activity;
119         mPm = mContext.getPackageManager();
120         mNoMan = INotificationManager.Stub.asInterface(
121                 ServiceManager.getService(Context.NOTIFICATION_SERVICE));
122         try {
123             mListener.registerAsSystemService(mContext, new ComponentName(mContext.getPackageName(),
124                     this.getClass().getCanonicalName()), ActivityManager.getCurrentUser());
125         } catch (RemoteException e) {
126             Log.e(TAG, "Cannot register listener", e);
127         }
128     }
129 
130     @Override
onDetach()131     public void onDetach() {
132         try {
133             mListener.unregisterAsSystemService();
134         } catch (RemoteException e) {
135             Log.e(TAG, "Cannot unregister listener", e);
136         }
137         super.onDetach();
138     }
139 
140     @Override
getMetricsCategory()141     protected int getMetricsCategory() {
142         return MetricsLogger.NOTIFICATION_STATION;
143     }
144 
145     @Override
onActivityCreated(Bundle savedInstanceState)146     public void onActivityCreated(Bundle savedInstanceState) {
147         logd("onActivityCreated(%s)", savedInstanceState);
148         super.onActivityCreated(savedInstanceState);
149 
150         ListView listView = getListView();
151         Utils.forceCustomPadding(listView, false /* non additive padding */);
152 
153         mAdapter = new NotificationHistoryAdapter(mContext);
154         listView.setAdapter(mAdapter);
155     }
156 
157     @Override
onResume()158     public void onResume() {
159         logd("onResume()");
160         super.onResume();
161         refreshList();
162     }
163 
refreshList()164     private void refreshList() {
165         List<HistoricalNotificationInfo> infos = loadNotifications();
166         if (infos != null) {
167             logd("adding %d infos", infos.size());
168             mAdapter.clear();
169             mAdapter.addAll(infos);
170             mAdapter.sort(mNotificationSorter);
171         }
172     }
173 
logd(String msg, Object... args)174     private static void logd(String msg, Object... args) {
175         if (DEBUG) {
176             Log.d(TAG, args == null || args.length == 0 ? msg : String.format(msg, args));
177         }
178     }
179 
loadNotifications()180     private List<HistoricalNotificationInfo> loadNotifications() {
181         final int currentUserId = ActivityManager.getCurrentUser();
182         try {
183             StatusBarNotification[] active = mNoMan.getActiveNotifications(
184                     mContext.getPackageName());
185             StatusBarNotification[] dismissed = mNoMan.getHistoricalNotifications(
186                     mContext.getPackageName(), 50);
187 
188             List<HistoricalNotificationInfo> list
189                     = new ArrayList<HistoricalNotificationInfo>(active.length + dismissed.length);
190 
191             for (StatusBarNotification[] resultset
192                     : new StatusBarNotification[][] { active, dismissed }) {
193                 for (StatusBarNotification sbn : resultset) {
194                     final HistoricalNotificationInfo info = new HistoricalNotificationInfo();
195                     info.pkg = sbn.getPackageName();
196                     info.user = sbn.getUserId();
197                     info.icon = loadIconDrawable(info.pkg, info.user, sbn.getNotification().icon);
198                     info.pkgicon = loadPackageIconDrawable(info.pkg, info.user);
199                     info.pkgname = loadPackageName(info.pkg);
200                     if (sbn.getNotification().extras != null) {
201                         info.title = sbn.getNotification().extras.getString(
202                                 Notification.EXTRA_TITLE);
203                         if (info.title == null || "".equals(info.title)) {
204                             info.title = sbn.getNotification().extras.getString(
205                                     Notification.EXTRA_TEXT);
206                         }
207                     }
208                     if (info.title == null || "".equals(info.title)) {
209                         info.title = sbn.getNotification().tickerText;
210                     }
211                     // still nothing? come on, give us something!
212                     if (info.title == null || "".equals(info.title)) {
213                         info.title = info.pkgname;
214                     }
215                     info.timestamp = sbn.getPostTime();
216                     info.priority = sbn.getNotification().priority;
217                     logd("   [%d] %s: %s", info.timestamp, info.pkg, info.title);
218 
219                     info.active = (resultset == active);
220 
221                     if (info.user == UserHandle.USER_ALL
222                             || info.user == currentUserId) {
223                         list.add(info);
224                     }
225                 }
226             }
227 
228             return list;
229         } catch (RemoteException e) {
230             Log.e(TAG, "Cannot load Notifications: ", e);
231         }
232         return null;
233     }
234 
getResourcesForUserPackage(String pkg, int userId)235     private Resources getResourcesForUserPackage(String pkg, int userId) {
236         Resources r = null;
237 
238         if (pkg != null) {
239             try {
240                 if (userId == UserHandle.USER_ALL) {
241                     userId = UserHandle.USER_OWNER;
242                 }
243                 r = mPm.getResourcesForApplicationAsUser(pkg, userId);
244             } catch (PackageManager.NameNotFoundException ex) {
245                 Log.e(TAG, "Icon package not found: " + pkg, ex);
246                 return null;
247             }
248         } else {
249             r = mContext.getResources();
250         }
251         return r;
252     }
253 
loadPackageIconDrawable(String pkg, int userId)254     private Drawable loadPackageIconDrawable(String pkg, int userId) {
255         Drawable icon = null;
256         try {
257             icon = mPm.getApplicationIcon(pkg);
258         } catch (PackageManager.NameNotFoundException e) {
259             Log.e(TAG, "Cannot get application icon", e);
260         }
261 
262         return icon;
263     }
264 
loadPackageName(String pkg)265     private CharSequence loadPackageName(String pkg) {
266         try {
267             ApplicationInfo info = mPm.getApplicationInfo(pkg,
268                     PackageManager.GET_UNINSTALLED_PACKAGES);
269             if (info != null) return mPm.getApplicationLabel(info);
270         } catch (PackageManager.NameNotFoundException e) {
271             Log.e(TAG, "Cannot load package name", e);
272         }
273         return pkg;
274     }
275 
loadIconDrawable(String pkg, int userId, int resId)276     private Drawable loadIconDrawable(String pkg, int userId, int resId) {
277         Resources r = getResourcesForUserPackage(pkg, userId);
278 
279         if (resId == 0) {
280             return null;
281         }
282 
283         try {
284             return r.getDrawable(resId, null);
285         } catch (RuntimeException e) {
286             Log.w(TAG, "Icon not found in "
287                     + (pkg != null ? resId : "<system>")
288                     + ": " + Integer.toHexString(resId), e);
289         }
290 
291         return null;
292     }
293 
294     private class NotificationHistoryAdapter extends ArrayAdapter<HistoricalNotificationInfo> {
295         private final LayoutInflater mInflater;
296 
NotificationHistoryAdapter(Context context)297         public NotificationHistoryAdapter(Context context) {
298             super(context, 0);
299             mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
300         }
301 
302         @Override
getView(int position, View convertView, ViewGroup parent)303         public View getView(int position, View convertView, ViewGroup parent) {
304             final HistoricalNotificationInfo info = getItem(position);
305             logd("getView(%s/%s)", info.pkg, info.title);
306 
307             final View row = convertView != null ? convertView : createRow(parent);
308             row.setTag(info);
309 
310             // bind icon
311             if (info.icon != null) {
312                 ((ImageView) row.findViewById(android.R.id.icon)).setImageDrawable(info.icon);
313             }
314             if (info.pkgicon != null) {
315                 ((ImageView) row.findViewById(R.id.pkgicon)).setImageDrawable(info.pkgicon);
316             }
317 
318             ((DateTimeView) row.findViewById(R.id.timestamp)).setTime(info.timestamp);
319             ((TextView) row.findViewById(android.R.id.title)).setText(info.title);
320             ((TextView) row.findViewById(R.id.pkgname)).setText(info.pkgname);
321 
322             row.findViewById(R.id.extra).setVisibility(View.GONE);
323             row.setAlpha(info.active ? 1.0f : 0.5f);
324 
325             // set up click handler
326             row.setOnClickListener(new OnClickListener(){
327                 @Override
328                 public void onClick(View v) {
329                     v.setPressed(true);
330                     startApplicationDetailsActivity(info.pkg);
331                 }});
332 
333             return row;
334         }
335 
createRow(ViewGroup parent)336         private View createRow(ViewGroup parent) {
337             return mInflater.inflate(R.layout.notification_log_row, parent, false);
338         }
339 
340     }
341 
startApplicationDetailsActivity(String packageName)342     private void startApplicationDetailsActivity(String packageName) {
343         Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
344                 Uri.fromParts("package", packageName, null));
345         intent.setComponent(intent.resolveActivity(mPm));
346         startActivity(intent);
347     }
348 }
349