Handle pids coming and going in the memory tracker.

Change-Id: If705e62c876243299adc7ed451a419c552b556b2
diff --git a/src/com/android/launcher3/WeightWatcher.java b/src/com/android/launcher3/WeightWatcher.java
index 91d79a8..410856a 100644
--- a/src/com/android/launcher3/WeightWatcher.java
+++ b/src/com/android/launcher3/WeightWatcher.java
@@ -46,6 +46,13 @@
     private static final int MSG_STOP = 2;
     private static final int MSG_UPDATE = 3;
 
+    static int indexOf(int[] a, int x) {
+        for (int i=0; i<a.length; i++) {
+            if (a[i] == x) return i;
+        }
+        return -1;
+    }
+
     Handler mHandler = new Handler() {
         @Override
         public void handleMessage(Message m) {
@@ -57,9 +64,17 @@
                     mHandler.removeMessages(MSG_UPDATE);
                     break;
                 case MSG_UPDATE:
+                    int[] pids = mMemoryService.getTrackedProcesses();
+
                     final int N = getChildCount();
-                    for (int i=0; i<N; i++) {
-                        ((ProcessWatcher) getChildAt(i)).update();
+                    if (pids.length != N) initViews();
+                    else for (int i=0; i<N; i++) {
+                        ProcessWatcher pw = ((ProcessWatcher) getChildAt(i));
+                        if (indexOf(pids, pw.getPid()) < 0) {
+                            initViews();
+                            break;
+                        }
+                        pw.update();
                     }
                     mHandler.sendEmptyMessageDelayed(MSG_UPDATE, UPDATE_RATE);
                     break;
@@ -90,6 +105,7 @@
     }
 
     public void initViews() {
+        removeAllViews();
         int[] processes = mMemoryService.getTrackedProcesses();
         for (int i=0; i<processes.length; i++) {
             final ProcessWatcher v = new ProcessWatcher(getContext());
@@ -184,6 +200,14 @@
         public void setPid(int pid) {
             mPid = pid;
             mMemInfo = mMemoryService.getMemInfo(mPid);
+            if (mMemInfo == null) {
+                Log.v("WeightWatcher", "Missing info for pid " + mPid + ", removing view: " + this);
+                initViews();
+            }
+        }
+
+        public int getPid() {
+            return mPid;
         }
 
         public void update() {