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