Home | History | Annotate | Download | only in am
      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 
     17 package com.android.server.am;
     18 
     19 import android.annotation.NonNull;
     20 import android.graphics.Bitmap;
     21 import android.graphics.BitmapFactory;
     22 import android.os.Debug;
     23 import android.os.Environment;
     24 import android.os.FileUtils;
     25 import android.os.Process;
     26 import android.os.SystemClock;
     27 import android.util.ArraySet;
     28 import android.util.AtomicFile;
     29 import android.util.Slog;
     30 import android.util.SparseArray;
     31 import android.util.SparseBooleanArray;
     32 import android.util.Xml;
     33 
     34 import com.android.internal.annotations.VisibleForTesting;
     35 import com.android.internal.util.FastXmlSerializer;
     36 import com.android.internal.util.XmlUtils;
     37 import libcore.io.IoUtils;
     38 
     39 import org.xmlpull.v1.XmlPullParser;
     40 import org.xmlpull.v1.XmlPullParserException;
     41 import org.xmlpull.v1.XmlSerializer;
     42 
     43 import java.io.BufferedReader;
     44 import java.io.BufferedWriter;
     45 import java.io.File;
     46 import java.io.FileNotFoundException;
     47 import java.io.FileOutputStream;
     48 import java.io.FileReader;
     49 import java.io.FileWriter;
     50 import java.io.IOException;
     51 import java.io.StringWriter;
     52 import java.util.ArrayList;
     53 import java.util.Collections;
     54 import java.util.Comparator;
     55 import java.util.List;
     56 
     57 public class TaskPersister {
     58     static final String TAG = "TaskPersister";
     59     static final boolean DEBUG = false;
     60 
     61     /** When not flushing don't write out files faster than this */
     62     private static final long INTER_WRITE_DELAY_MS = 500;
     63 
     64     /**
     65      * When not flushing delay this long before writing the first file out. This gives the next task
     66      * being launched a chance to load its resources without this occupying IO bandwidth.
     67      */
     68     private static final long PRE_TASK_DELAY_MS = 3000;
     69 
     70     /** The maximum number of entries to keep in the queue before draining it automatically. */
     71     private static final int MAX_WRITE_QUEUE_LENGTH = 6;
     72 
     73     /** Special value for mWriteTime to mean don't wait, just write */
     74     private static final long FLUSH_QUEUE = -1;
     75 
     76     private static final String RECENTS_FILENAME = "_task";
     77     private static final String TASKS_DIRNAME = "recent_tasks";
     78     private static final String TASK_EXTENSION = ".xml";
     79     private static final String IMAGES_DIRNAME = "recent_images";
     80     private static final String PERSISTED_TASK_IDS_FILENAME = "persisted_taskIds.txt";
     81     static final String IMAGE_EXTENSION = ".png";
     82 
     83     private static final String TAG_TASK = "task";
     84 
     85     private final ActivityManagerService mService;
     86     private final ActivityStackSupervisor mStackSupervisor;
     87     private final RecentTasks mRecentTasks;
     88     private final SparseArray<SparseBooleanArray> mTaskIdsInFile = new SparseArray<>();
     89     private final File mTaskIdsDir;
     90     // To lock file operations in TaskPersister
     91     private final Object mIoLock = new Object();
     92 
     93     /**
     94      * Value determines write delay mode as follows: < 0 We are Flushing. No delays between writes
     95      * until the image queue is drained and all tasks needing persisting are written to disk. There
     96      * is no delay between writes. == 0 We are Idle. Next writes will be delayed by
     97      * #PRE_TASK_DELAY_MS. > 0 We are Actively writing. Next write will be at this time. Subsequent
     98      * writes will be delayed by #INTER_WRITE_DELAY_MS.
     99      */
    100     private long mNextWriteTime = 0;
    101 
    102     private final LazyTaskWriterThread mLazyTaskWriterThread;
    103 
    104     private static class WriteQueueItem {}
    105 
    106     private static class TaskWriteQueueItem extends WriteQueueItem {
    107         final TaskRecord mTask;
    108 
    109         TaskWriteQueueItem(TaskRecord task) {
    110             mTask = task;
    111         }
    112     }
    113 
    114     private static class ImageWriteQueueItem extends WriteQueueItem {
    115         final String mFilePath;
    116         Bitmap mImage;
    117 
    118         ImageWriteQueueItem(String filePath, Bitmap image) {
    119             mFilePath = filePath;
    120             mImage = image;
    121         }
    122     }
    123 
    124     ArrayList<WriteQueueItem> mWriteQueue = new ArrayList<WriteQueueItem>();
    125 
    126     TaskPersister(File systemDir, ActivityStackSupervisor stackSupervisor,
    127             ActivityManagerService service, RecentTasks recentTasks) {
    128 
    129         final File legacyImagesDir = new File(systemDir, IMAGES_DIRNAME);
    130         if (legacyImagesDir.exists()) {
    131             if (!FileUtils.deleteContents(legacyImagesDir) || !legacyImagesDir.delete()) {
    132                 Slog.i(TAG, "Failure deleting legacy images directory: " + legacyImagesDir);
    133             }
    134         }
    135 
    136         final File legacyTasksDir = new File(systemDir, TASKS_DIRNAME);
    137         if (legacyTasksDir.exists()) {
    138             if (!FileUtils.deleteContents(legacyTasksDir) || !legacyTasksDir.delete()) {
    139                 Slog.i(TAG, "Failure deleting legacy tasks directory: " + legacyTasksDir);
    140             }
    141         }
    142 
    143         mTaskIdsDir = new File(Environment.getDataDirectory(), "system_de");
    144         mStackSupervisor = stackSupervisor;
    145         mService = service;
    146         mRecentTasks = recentTasks;
    147         mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThread");
    148     }
    149 
    150     @VisibleForTesting
    151     TaskPersister(File workingDir) {
    152         mTaskIdsDir = workingDir;
    153         mStackSupervisor = null;
    154         mService = null;
    155         mRecentTasks = null;
    156         mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThreadTest");
    157     }
    158 
    159     void startPersisting() {
    160         if (!mLazyTaskWriterThread.isAlive()) {
    161             mLazyTaskWriterThread.start();
    162         }
    163     }
    164 
    165     private void removeThumbnails(TaskRecord task) {
    166         final String taskString = Integer.toString(task.taskId);
    167         for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
    168             final WriteQueueItem item = mWriteQueue.get(queueNdx);
    169             if (item instanceof ImageWriteQueueItem) {
    170                 final File thumbnailFile = new File(((ImageWriteQueueItem) item).mFilePath);
    171                 if (thumbnailFile.getName().startsWith(taskString)) {
    172                     if (DEBUG) {
    173                         Slog.d(TAG, "Removing " + ((ImageWriteQueueItem) item).mFilePath +
    174                                 " from write queue");
    175                     }
    176                     mWriteQueue.remove(queueNdx);
    177                 }
    178             }
    179         }
    180     }
    181 
    182     private void yieldIfQueueTooDeep() {
    183         boolean stall = false;
    184         synchronized (this) {
    185             if (mNextWriteTime == FLUSH_QUEUE) {
    186                 stall = true;
    187             }
    188         }
    189         if (stall) {
    190             Thread.yield();
    191         }
    192     }
    193 
    194     @NonNull
    195     SparseBooleanArray loadPersistedTaskIdsForUser(int userId) {
    196         if (mTaskIdsInFile.get(userId) != null) {
    197             return mTaskIdsInFile.get(userId).clone();
    198         }
    199         final SparseBooleanArray persistedTaskIds = new SparseBooleanArray();
    200         synchronized (mIoLock) {
    201             BufferedReader reader = null;
    202             String line;
    203             try {
    204                 reader = new BufferedReader(new FileReader(getUserPersistedTaskIdsFile(userId)));
    205                 while ((line = reader.readLine()) != null) {
    206                     for (String taskIdString : line.split("\\s+")) {
    207                         int id = Integer.parseInt(taskIdString);
    208                         persistedTaskIds.put(id, true);
    209                     }
    210                 }
    211             } catch (FileNotFoundException e) {
    212                 // File doesn't exist. Ignore.
    213             } catch (Exception e) {
    214                 Slog.e(TAG, "Error while reading taskIds file for user " + userId, e);
    215             } finally {
    216                 IoUtils.closeQuietly(reader);
    217             }
    218         }
    219         mTaskIdsInFile.put(userId, persistedTaskIds);
    220         return persistedTaskIds.clone();
    221     }
    222 
    223 
    224     @VisibleForTesting
    225     void writePersistedTaskIdsForUser(@NonNull SparseBooleanArray taskIds, int userId) {
    226         if (userId < 0) {
    227             return;
    228         }
    229         final File persistedTaskIdsFile = getUserPersistedTaskIdsFile(userId);
    230         synchronized (mIoLock) {
    231             BufferedWriter writer = null;
    232             try {
    233                 writer = new BufferedWriter(new FileWriter(persistedTaskIdsFile));
    234                 for (int i = 0; i < taskIds.size(); i++) {
    235                     if (taskIds.valueAt(i)) {
    236                         writer.write(String.valueOf(taskIds.keyAt(i)));
    237                         writer.newLine();
    238                     }
    239                 }
    240             } catch (Exception e) {
    241                 Slog.e(TAG, "Error while writing taskIds file for user " + userId, e);
    242             } finally {
    243                 IoUtils.closeQuietly(writer);
    244             }
    245         }
    246     }
    247 
    248     void unloadUserDataFromMemory(int userId) {
    249         mTaskIdsInFile.delete(userId);
    250     }
    251 
    252     void wakeup(TaskRecord task, boolean flush) {
    253         synchronized (this) {
    254             if (task != null) {
    255                 int queueNdx;
    256                 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
    257                     final WriteQueueItem item = mWriteQueue.get(queueNdx);
    258                     if (item instanceof TaskWriteQueueItem &&
    259                             ((TaskWriteQueueItem) item).mTask == task) {
    260                         if (!task.inRecents) {
    261                             // This task is being removed.
    262                             removeThumbnails(task);
    263                         }
    264                         break;
    265                     }
    266                 }
    267                 if (queueNdx < 0 && task.isPersistable) {
    268                     mWriteQueue.add(new TaskWriteQueueItem(task));
    269                 }
    270             } else {
    271                 // Dummy. Ensures removeObsoleteFiles is called when LazyTaskThreadWriter is
    272                 // notified.
    273                 mWriteQueue.add(new WriteQueueItem());
    274             }
    275             if (flush || mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
    276                 mNextWriteTime = FLUSH_QUEUE;
    277             } else if (mNextWriteTime == 0) {
    278                 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
    279             }
    280             if (DEBUG) Slog.d(TAG, "wakeup: task=" + task + " flush=" + flush + " mNextWriteTime="
    281                     + mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size()
    282                     + " Callers=" + Debug.getCallers(4));
    283             notifyAll();
    284         }
    285 
    286         yieldIfQueueTooDeep();
    287     }
    288 
    289     void flush() {
    290         synchronized (this) {
    291             mNextWriteTime = FLUSH_QUEUE;
    292             notifyAll();
    293             do {
    294                 try {
    295                     wait();
    296                 } catch (InterruptedException e) {
    297                 }
    298             } while (mNextWriteTime == FLUSH_QUEUE);
    299         }
    300     }
    301 
    302     void saveImage(Bitmap image, String filePath) {
    303         synchronized (this) {
    304             int queueNdx;
    305             for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
    306                 final WriteQueueItem item = mWriteQueue.get(queueNdx);
    307                 if (item instanceof ImageWriteQueueItem) {
    308                     ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
    309                     if (imageWriteQueueItem.mFilePath.equals(filePath)) {
    310                         // replace the Bitmap with the new one.
    311                         imageWriteQueueItem.mImage = image;
    312                         break;
    313                     }
    314                 }
    315             }
    316             if (queueNdx < 0) {
    317                 mWriteQueue.add(new ImageWriteQueueItem(filePath, image));
    318             }
    319             if (mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
    320                 mNextWriteTime = FLUSH_QUEUE;
    321             } else if (mNextWriteTime == 0) {
    322                 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
    323             }
    324             if (DEBUG) Slog.d(TAG, "saveImage: filePath=" + filePath + " now=" +
    325                     SystemClock.uptimeMillis() + " mNextWriteTime=" +
    326                     mNextWriteTime + " Callers=" + Debug.getCallers(4));
    327             notifyAll();
    328         }
    329 
    330         yieldIfQueueTooDeep();
    331     }
    332 
    333     Bitmap getTaskDescriptionIcon(String filePath) {
    334         // See if it is in the write queue
    335         final Bitmap icon = getImageFromWriteQueue(filePath);
    336         if (icon != null) {
    337             return icon;
    338         }
    339         return restoreImage(filePath);
    340     }
    341 
    342     Bitmap getImageFromWriteQueue(String filePath) {
    343         synchronized (this) {
    344             for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
    345                 final WriteQueueItem item = mWriteQueue.get(queueNdx);
    346                 if (item instanceof ImageWriteQueueItem) {
    347                     ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
    348                     if (imageWriteQueueItem.mFilePath.equals(filePath)) {
    349                         return imageWriteQueueItem.mImage;
    350                     }
    351                 }
    352             }
    353             return null;
    354         }
    355     }
    356 
    357     private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException {
    358         if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task);
    359         final XmlSerializer xmlSerializer = new FastXmlSerializer();
    360         StringWriter stringWriter = new StringWriter();
    361         xmlSerializer.setOutput(stringWriter);
    362 
    363         if (DEBUG) xmlSerializer.setFeature(
    364                 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
    365 
    366         // save task
    367         xmlSerializer.startDocument(null, true);
    368 
    369         xmlSerializer.startTag(null, TAG_TASK);
    370         task.saveToXml(xmlSerializer);
    371         xmlSerializer.endTag(null, TAG_TASK);
    372 
    373         xmlSerializer.endDocument();
    374         xmlSerializer.flush();
    375 
    376         return stringWriter;
    377     }
    378 
    379     private String fileToString(File file) {
    380         final String newline = System.lineSeparator();
    381         try {
    382             BufferedReader reader = new BufferedReader(new FileReader(file));
    383             StringBuffer sb = new StringBuffer((int) file.length() * 2);
    384             String line;
    385             while ((line = reader.readLine()) != null) {
    386                 sb.append(line + newline);
    387             }
    388             reader.close();
    389             return sb.toString();
    390         } catch (IOException ioe) {
    391             Slog.e(TAG, "Couldn't read file " + file.getName());
    392             return null;
    393         }
    394     }
    395 
    396     private TaskRecord taskIdToTask(int taskId, ArrayList<TaskRecord> tasks) {
    397         if (taskId < 0) {
    398             return null;
    399         }
    400         for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
    401             final TaskRecord task = tasks.get(taskNdx);
    402             if (task.taskId == taskId) {
    403                 return task;
    404             }
    405         }
    406         Slog.e(TAG, "Restore affiliation error looking for taskId=" + taskId);
    407         return null;
    408     }
    409 
    410     List<TaskRecord> restoreTasksForUserLocked(final int userId) {
    411         final ArrayList<TaskRecord> tasks = new ArrayList<TaskRecord>();
    412         ArraySet<Integer> recoveredTaskIds = new ArraySet<Integer>();
    413 
    414         File userTasksDir = getUserTasksDir(userId);
    415 
    416         File[] recentFiles = userTasksDir.listFiles();
    417         if (recentFiles == null) {
    418             Slog.e(TAG, "restoreTasksForUserLocked: Unable to list files from " + userTasksDir);
    419             return tasks;
    420         }
    421 
    422         for (int taskNdx = 0; taskNdx < recentFiles.length; ++taskNdx) {
    423             File taskFile = recentFiles[taskNdx];
    424             if (DEBUG) {
    425                 Slog.d(TAG, "restoreTasksForUserLocked: userId=" + userId
    426                         + ", taskFile=" + taskFile.getName());
    427             }
    428             BufferedReader reader = null;
    429             boolean deleteFile = false;
    430             try {
    431                 reader = new BufferedReader(new FileReader(taskFile));
    432                 final XmlPullParser in = Xml.newPullParser();
    433                 in.setInput(reader);
    434 
    435                 int event;
    436                 while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
    437                         event != XmlPullParser.END_TAG) {
    438                     final String name = in.getName();
    439                     if (event == XmlPullParser.START_TAG) {
    440                         if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: START_TAG name=" + name);
    441                         if (TAG_TASK.equals(name)) {
    442                             final TaskRecord task = TaskRecord.restoreFromXml(in, mStackSupervisor);
    443                             if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: restored task="
    444                                     + task);
    445                             if (task != null) {
    446                                 // XXX Don't add to write queue... there is no reason to write
    447                                 // out the stuff we just read, if we don't write it we will
    448                                 // read the same thing again.
    449                                 // mWriteQueue.add(new TaskWriteQueueItem(task));
    450 
    451                                 final int taskId = task.taskId;
    452                                 if (mStackSupervisor.anyTaskForIdLocked(taskId,
    453                                         /* restoreFromRecents= */ false, 0) != null) {
    454                                     // Should not happen.
    455                                     Slog.wtf(TAG, "Existing task with taskId " + taskId + "found");
    456                                 } else if (userId != task.userId) {
    457                                     // Should not happen.
    458                                     Slog.wtf(TAG, "Task with userId " + task.userId + " found in "
    459                                             + userTasksDir.getAbsolutePath());
    460                                 } else {
    461                                     // Looks fine.
    462                                     mStackSupervisor.setNextTaskIdForUserLocked(taskId, userId);
    463                                     task.isPersistable = true;
    464                                     tasks.add(task);
    465                                     recoveredTaskIds.add(taskId);
    466                                 }
    467                             } else {
    468                                 Slog.e(TAG, "restoreTasksForUserLocked: Unable to restore taskFile="
    469                                         + taskFile + ": " + fileToString(taskFile));
    470                             }
    471                         } else {
    472                             Slog.wtf(TAG, "restoreTasksForUserLocked: Unknown xml event=" + event
    473                                     + " name=" + name);
    474                         }
    475                     }
    476                     XmlUtils.skipCurrentTag(in);
    477                 }
    478             } catch (Exception e) {
    479                 Slog.wtf(TAG, "Unable to parse " + taskFile + ". Error ", e);
    480                 Slog.e(TAG, "Failing file: " + fileToString(taskFile));
    481                 deleteFile = true;
    482             } finally {
    483                 IoUtils.closeQuietly(reader);
    484                 if (deleteFile) {
    485                     if (DEBUG) Slog.d(TAG, "Deleting file=" + taskFile.getName());
    486                     taskFile.delete();
    487                 }
    488             }
    489         }
    490 
    491         if (!DEBUG) {
    492             removeObsoleteFiles(recoveredTaskIds, userTasksDir.listFiles());
    493         }
    494 
    495         // Fix up task affiliation from taskIds
    496         for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
    497             final TaskRecord task = tasks.get(taskNdx);
    498             task.setPrevAffiliate(taskIdToTask(task.mPrevAffiliateTaskId, tasks));
    499             task.setNextAffiliate(taskIdToTask(task.mNextAffiliateTaskId, tasks));
    500         }
    501 
    502         Collections.sort(tasks, new Comparator<TaskRecord>() {
    503             @Override
    504             public int compare(TaskRecord lhs, TaskRecord rhs) {
    505                 final long diff = rhs.mLastTimeMoved - lhs.mLastTimeMoved;
    506                 if (diff < 0) {
    507                     return -1;
    508                 } else if (diff > 0) {
    509                     return +1;
    510                 } else {
    511                     return 0;
    512                 }
    513             }
    514         });
    515         return tasks;
    516     }
    517 
    518     private static void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds, File[] files) {
    519         if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: persistentTaskIds=" + persistentTaskIds +
    520                 " files=" + files);
    521         if (files == null) {
    522             Slog.e(TAG, "File error accessing recents directory (directory doesn't exist?).");
    523             return;
    524         }
    525         for (int fileNdx = 0; fileNdx < files.length; ++fileNdx) {
    526             File file = files[fileNdx];
    527             String filename = file.getName();
    528             final int taskIdEnd = filename.indexOf('_');
    529             if (taskIdEnd > 0) {
    530                 final int taskId;
    531                 try {
    532                     taskId = Integer.parseInt(filename.substring(0, taskIdEnd));
    533                     if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: Found taskId=" + taskId);
    534                 } catch (Exception e) {
    535                     Slog.wtf(TAG, "removeObsoleteFiles: Can't parse file=" + file.getName());
    536                     file.delete();
    537                     continue;
    538                 }
    539                 if (!persistentTaskIds.contains(taskId)) {
    540                     if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: deleting file=" + file.getName());
    541                     file.delete();
    542                 }
    543             }
    544         }
    545     }
    546 
    547     private void writeTaskIdsFiles() {
    548         SparseArray<SparseBooleanArray> changedTaskIdsPerUser = new SparseArray<>();
    549         synchronized (mService) {
    550             for (int userId : mRecentTasks.usersWithRecentsLoadedLocked()) {
    551                 SparseBooleanArray taskIdsToSave = mRecentTasks.mPersistedTaskIds.get(userId);
    552                 SparseBooleanArray persistedIdsInFile = mTaskIdsInFile.get(userId);
    553                 if (persistedIdsInFile != null && persistedIdsInFile.equals(taskIdsToSave)) {
    554                     continue;
    555                 } else {
    556                     SparseBooleanArray taskIdsToSaveCopy = taskIdsToSave.clone();
    557                     mTaskIdsInFile.put(userId, taskIdsToSaveCopy);
    558                     changedTaskIdsPerUser.put(userId, taskIdsToSaveCopy);
    559                 }
    560             }
    561         }
    562         for (int i = 0; i < changedTaskIdsPerUser.size(); i++) {
    563             writePersistedTaskIdsForUser(changedTaskIdsPerUser.valueAt(i),
    564                     changedTaskIdsPerUser.keyAt(i));
    565         }
    566     }
    567 
    568     private void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds) {
    569         int[] candidateUserIds;
    570         synchronized (mService) {
    571             // Remove only from directories of the users who have recents in memory synchronized
    572             // with persistent storage.
    573             candidateUserIds = mRecentTasks.usersWithRecentsLoadedLocked();
    574         }
    575         for (int userId : candidateUserIds) {
    576             removeObsoleteFiles(persistentTaskIds, getUserImagesDir(userId).listFiles());
    577             removeObsoleteFiles(persistentTaskIds, getUserTasksDir(userId).listFiles());
    578         }
    579     }
    580 
    581     static Bitmap restoreImage(String filename) {
    582         if (DEBUG) Slog.d(TAG, "restoreImage: restoring " + filename);
    583         return BitmapFactory.decodeFile(filename);
    584     }
    585 
    586     private File getUserPersistedTaskIdsFile(int userId) {
    587         File userTaskIdsDir = new File(mTaskIdsDir, String.valueOf(userId));
    588         if (!userTaskIdsDir.exists() && !userTaskIdsDir.mkdirs()) {
    589             Slog.e(TAG, "Error while creating user directory: " + userTaskIdsDir);
    590         }
    591         return new File(userTaskIdsDir, PERSISTED_TASK_IDS_FILENAME);
    592     }
    593 
    594     static File getUserTasksDir(int userId) {
    595         File userTasksDir = new File(Environment.getDataSystemCeDirectory(userId), TASKS_DIRNAME);
    596 
    597         if (!userTasksDir.exists()) {
    598             if (!userTasksDir.mkdir()) {
    599                 Slog.e(TAG, "Failure creating tasks directory for user " + userId + ": "
    600                         + userTasksDir);
    601             }
    602         }
    603         return userTasksDir;
    604     }
    605 
    606     static File getUserImagesDir(int userId) {
    607         return new File(Environment.getDataSystemCeDirectory(userId), IMAGES_DIRNAME);
    608     }
    609 
    610     private static boolean createParentDirectory(String filePath) {
    611         File parentDir = new File(filePath).getParentFile();
    612         return parentDir.exists() || parentDir.mkdirs();
    613     }
    614 
    615     private class LazyTaskWriterThread extends Thread {
    616 
    617         LazyTaskWriterThread(String name) {
    618             super(name);
    619         }
    620 
    621         @Override
    622         public void run() {
    623             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    624             ArraySet<Integer> persistentTaskIds = new ArraySet<Integer>();
    625             while (true) {
    626                 // We can't lock mService while holding TaskPersister.this, but we don't want to
    627                 // call removeObsoleteFiles every time through the loop, only the last time before
    628                 // going to sleep. The risk is that we call removeObsoleteFiles() successively.
    629                 final boolean probablyDone;
    630                 synchronized (TaskPersister.this) {
    631                     probablyDone = mWriteQueue.isEmpty();
    632                 }
    633                 if (probablyDone) {
    634                     if (DEBUG) Slog.d(TAG, "Looking for obsolete files.");
    635                     persistentTaskIds.clear();
    636                     synchronized (mService) {
    637                         if (DEBUG) Slog.d(TAG, "mRecents=" + mRecentTasks);
    638                         for (int taskNdx = mRecentTasks.size() - 1; taskNdx >= 0; --taskNdx) {
    639                             final TaskRecord task = mRecentTasks.get(taskNdx);
    640                             if (DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task +
    641                                     " persistable=" + task.isPersistable);
    642                             if ((task.isPersistable || task.inRecents)
    643                                     && (task.stack == null || !task.stack.isHomeStack())) {
    644                                 if (DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
    645                                 persistentTaskIds.add(task.taskId);
    646                             } else {
    647                                 if (DEBUG) Slog.d(TAG,
    648                                         "omitting from persistentTaskIds task=" + task);
    649                             }
    650                         }
    651                     }
    652                     removeObsoleteFiles(persistentTaskIds);
    653                 }
    654                 writeTaskIdsFiles();
    655 
    656                 // If mNextWriteTime, then don't delay between each call to saveToXml().
    657                 final WriteQueueItem item;
    658                 synchronized (TaskPersister.this) {
    659                     if (mNextWriteTime != FLUSH_QUEUE) {
    660                         // The next write we don't have to wait so long.
    661                         mNextWriteTime = SystemClock.uptimeMillis() + INTER_WRITE_DELAY_MS;
    662                         if (DEBUG) Slog.d(TAG, "Next write time may be in " +
    663                                 INTER_WRITE_DELAY_MS + " msec. (" + mNextWriteTime + ")");
    664                     }
    665 
    666                     while (mWriteQueue.isEmpty()) {
    667                         if (mNextWriteTime != 0) {
    668                             mNextWriteTime = 0; // idle.
    669                             TaskPersister.this.notifyAll(); // wake up flush() if needed.
    670                         }
    671                         try {
    672                             if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting indefinitely.");
    673                             TaskPersister.this.wait();
    674                         } catch (InterruptedException e) {
    675                         }
    676                         // Invariant: mNextWriteTime is either FLUSH_QUEUE or PRE_WRITE_DELAY_MS
    677                         // from now.
    678                     }
    679                     item = mWriteQueue.remove(0);
    680 
    681                     long now = SystemClock.uptimeMillis();
    682                     if (DEBUG) Slog.d(TAG, "LazyTaskWriter: now=" + now + " mNextWriteTime=" +
    683                             mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size());
    684                     while (now < mNextWriteTime) {
    685                         try {
    686                             if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting " +
    687                                     (mNextWriteTime - now));
    688                             TaskPersister.this.wait(mNextWriteTime - now);
    689                         } catch (InterruptedException e) {
    690                         }
    691                         now = SystemClock.uptimeMillis();
    692                     }
    693 
    694                     // Got something to do.
    695                 }
    696 
    697                 if (item instanceof ImageWriteQueueItem) {
    698                     ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
    699                     final String filePath = imageWriteQueueItem.mFilePath;
    700                     if (!createParentDirectory(filePath)) {
    701                         Slog.e(TAG, "Error while creating images directory for file: " + filePath);
    702                         continue;
    703                     }
    704                     final Bitmap bitmap = imageWriteQueueItem.mImage;
    705                     if (DEBUG) Slog.d(TAG, "writing bitmap: filename=" + filePath);
    706                     FileOutputStream imageFile = null;
    707                     try {
    708                         imageFile = new FileOutputStream(new File(filePath));
    709                         bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageFile);
    710                     } catch (Exception e) {
    711                         Slog.e(TAG, "saveImage: unable to save " + filePath, e);
    712                     } finally {
    713                         IoUtils.closeQuietly(imageFile);
    714                     }
    715                 } else if (item instanceof TaskWriteQueueItem) {
    716                     // Write out one task.
    717                     StringWriter stringWriter = null;
    718                     TaskRecord task = ((TaskWriteQueueItem) item).mTask;
    719                     if (DEBUG) Slog.d(TAG, "Writing task=" + task);
    720                     synchronized (mService) {
    721                         if (task.inRecents) {
    722                             // Still there.
    723                             try {
    724                                 if (DEBUG) Slog.d(TAG, "Saving task=" + task);
    725                                 stringWriter = saveToXml(task);
    726                             } catch (IOException e) {
    727                             } catch (XmlPullParserException e) {
    728                             }
    729                         }
    730                     }
    731                     if (stringWriter != null) {
    732                         // Write out xml file while not holding mService lock.
    733                         FileOutputStream file = null;
    734                         AtomicFile atomicFile = null;
    735                         try {
    736                             atomicFile = new AtomicFile(new File(
    737                                     getUserTasksDir(task.userId),
    738                                     String.valueOf(task.taskId) + RECENTS_FILENAME
    739                                     + TASK_EXTENSION));
    740                             file = atomicFile.startWrite();
    741                             file.write(stringWriter.toString().getBytes());
    742                             file.write('\n');
    743                             atomicFile.finishWrite(file);
    744 
    745                         } catch (IOException e) {
    746                             if (file != null) {
    747                                 atomicFile.failWrite(file);
    748                             }
    749                             Slog.e(TAG,
    750                                     "Unable to open " + atomicFile + " for persisting. " + e);
    751                         }
    752                     }
    753                 }
    754             }
    755         }
    756     }
    757 }
    758