blob: 6cdabaac361f5ec91347fb5133ed3f6bdec3e75b [file] [log] [blame]
Craig Mautner21d24a22014-04-23 11:45:37 -07001/*
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
17package com.android.server.am;
18
Suprabh Shukla4bccb462016-02-10 18:45:12 -080019import android.annotation.NonNull;
Winsonb258f6a2016-08-25 15:00:14 -070020import android.content.ContentResolver;
Craig Mautner21d24a22014-04-23 11:45:37 -070021import android.graphics.Bitmap;
22import android.graphics.BitmapFactory;
23import android.os.Debug;
Suprabh Shukla23593142015-11-03 17:31:15 -080024import android.os.Environment;
25import android.os.FileUtils;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080026import android.os.Process;
Craig Mautner21d24a22014-04-23 11:45:37 -070027import android.os.SystemClock;
Winsonb258f6a2016-08-25 15:00:14 -070028import android.provider.Settings;
Craig Mautner21d24a22014-04-23 11:45:37 -070029import android.util.ArraySet;
30import android.util.AtomicFile;
31import android.util.Slog;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080032import android.util.SparseArray;
33import android.util.SparseBooleanArray;
Craig Mautner21d24a22014-04-23 11:45:37 -070034import android.util.Xml;
Wale Ogunwale18795a22014-12-03 11:38:33 -080035
Suprabh Shukla4bccb462016-02-10 18:45:12 -080036import com.android.internal.annotations.VisibleForTesting;
Craig Mautner21d24a22014-04-23 11:45:37 -070037import com.android.internal.util.FastXmlSerializer;
38import com.android.internal.util.XmlUtils;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080039import libcore.io.IoUtils;
40
Craig Mautner21d24a22014-04-23 11:45:37 -070041import org.xmlpull.v1.XmlPullParser;
42import org.xmlpull.v1.XmlPullParserException;
43import org.xmlpull.v1.XmlSerializer;
44
45import java.io.BufferedReader;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080046import java.io.BufferedWriter;
Craig Mautner21d24a22014-04-23 11:45:37 -070047import java.io.File;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080048import java.io.FileNotFoundException;
Craig Mautner21d24a22014-04-23 11:45:37 -070049import java.io.FileOutputStream;
50import java.io.FileReader;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080051import java.io.FileWriter;
Craig Mautner21d24a22014-04-23 11:45:37 -070052import java.io.IOException;
53import java.io.StringWriter;
54import java.util.ArrayList;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080055import java.util.Collections;
Craig Mautner21d24a22014-04-23 11:45:37 -070056import java.util.Comparator;
Suprabh Shukla23593142015-11-03 17:31:15 -080057import java.util.List;
Wale Ogunwale18795a22014-12-03 11:38:33 -080058
Craig Mautner21d24a22014-04-23 11:45:37 -070059public class TaskPersister {
60 static final String TAG = "TaskPersister";
Stefan Kuhnee88d1e52015-05-18 10:33:45 -070061 static final boolean DEBUG = false;
Craig Mautner21d24a22014-04-23 11:45:37 -070062
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070063 /** When not flushing don't write out files faster than this */
64 private static final long INTER_WRITE_DELAY_MS = 500;
65
Suprabh Shukla23593142015-11-03 17:31:15 -080066 /**
67 * When not flushing delay this long before writing the first file out. This gives the next task
68 * being launched a chance to load its resources without this occupying IO bandwidth.
69 */
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070070 private static final long PRE_TASK_DELAY_MS = 3000;
Craig Mautner21d24a22014-04-23 11:45:37 -070071
Craig Mautner63f10902014-09-16 23:57:21 -070072 /** The maximum number of entries to keep in the queue before draining it automatically. */
73 private static final int MAX_WRITE_QUEUE_LENGTH = 6;
74
75 /** Special value for mWriteTime to mean don't wait, just write */
76 private static final long FLUSH_QUEUE = -1;
77
Craig Mautner21d24a22014-04-23 11:45:37 -070078 private static final String RECENTS_FILENAME = "_task";
79 private static final String TASKS_DIRNAME = "recent_tasks";
80 private static final String TASK_EXTENSION = ".xml";
81 private static final String IMAGES_DIRNAME = "recent_images";
Suprabh Shukla4bccb462016-02-10 18:45:12 -080082 private static final String PERSISTED_TASK_IDS_FILENAME = "persisted_taskIds.txt";
Craig Mautnerc0ffce52014-07-01 12:38:52 -070083 static final String IMAGE_EXTENSION = ".png";
Craig Mautner21d24a22014-04-23 11:45:37 -070084
Winsonb258f6a2016-08-25 15:00:14 -070085 @VisibleForTesting static final String TAG_TASK = "task";
Craig Mautner21d24a22014-04-23 11:45:37 -070086
Craig Mautner21d24a22014-04-23 11:45:37 -070087 private final ActivityManagerService mService;
88 private final ActivityStackSupervisor mStackSupervisor;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080089 private final RecentTasks mRecentTasks;
Suprabh Shukla4bccb462016-02-10 18:45:12 -080090 private final SparseArray<SparseBooleanArray> mTaskIdsInFile = new SparseArray<>();
Suprabh Shuklaf50b4582016-02-23 17:44:22 -080091 private final File mTaskIdsDir;
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -070092 // To lock file operations in TaskPersister
93 private final Object mIoLock = new Object();
Craig Mautner21d24a22014-04-23 11:45:37 -070094
Suprabh Shukla23593142015-11-03 17:31:15 -080095 /**
96 * Value determines write delay mode as follows: < 0 We are Flushing. No delays between writes
97 * until the image queue is drained and all tasks needing persisting are written to disk. There
98 * is no delay between writes. == 0 We are Idle. Next writes will be delayed by
99 * #PRE_TASK_DELAY_MS. > 0 We are Actively writing. Next write will be at this time. Subsequent
100 * writes will be delayed by #INTER_WRITE_DELAY_MS.
101 */
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700102 private long mNextWriteTime = 0;
Craig Mautner21d24a22014-04-23 11:45:37 -0700103
104 private final LazyTaskWriterThread mLazyTaskWriterThread;
105
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700106 private static class WriteQueueItem {}
Suprabh Shukla23593142015-11-03 17:31:15 -0800107
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700108 private static class TaskWriteQueueItem extends WriteQueueItem {
109 final TaskRecord mTask;
Winsonc809cbb2015-11-02 12:06:15 -0800110
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700111 TaskWriteQueueItem(TaskRecord task) {
112 mTask = task;
113 }
114 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800115
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700116 private static class ImageWriteQueueItem extends WriteQueueItem {
Suprabh Shukla23593142015-11-03 17:31:15 -0800117 final String mFilePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700118 Bitmap mImage;
Winsonc809cbb2015-11-02 12:06:15 -0800119
Suprabh Shukla23593142015-11-03 17:31:15 -0800120 ImageWriteQueueItem(String filePath, Bitmap image) {
121 mFilePath = filePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700122 mImage = image;
123 }
124 }
125
126 ArrayList<WriteQueueItem> mWriteQueue = new ArrayList<WriteQueueItem>();
127
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800128 TaskPersister(File systemDir, ActivityStackSupervisor stackSupervisor,
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800129 ActivityManagerService service, RecentTasks recentTasks) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800130
131 final File legacyImagesDir = new File(systemDir, IMAGES_DIRNAME);
132 if (legacyImagesDir.exists()) {
133 if (!FileUtils.deleteContents(legacyImagesDir) || !legacyImagesDir.delete()) {
134 Slog.i(TAG, "Failure deleting legacy images directory: " + legacyImagesDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700135 }
136 }
137
Suprabh Shukla23593142015-11-03 17:31:15 -0800138 final File legacyTasksDir = new File(systemDir, TASKS_DIRNAME);
139 if (legacyTasksDir.exists()) {
140 if (!FileUtils.deleteContents(legacyTasksDir) || !legacyTasksDir.delete()) {
141 Slog.i(TAG, "Failure deleting legacy tasks directory: " + legacyTasksDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700142 }
143 }
144
Suprabh Shuklaf50b4582016-02-23 17:44:22 -0800145 mTaskIdsDir = new File(Environment.getDataDirectory(), "system_de");
Craig Mautner21d24a22014-04-23 11:45:37 -0700146 mStackSupervisor = stackSupervisor;
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800147 mService = service;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800148 mRecentTasks = recentTasks;
Craig Mautner21d24a22014-04-23 11:45:37 -0700149 mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThread");
150 }
151
Suprabh Shuklaf50b4582016-02-23 17:44:22 -0800152 @VisibleForTesting
153 TaskPersister(File workingDir) {
154 mTaskIdsDir = workingDir;
155 mStackSupervisor = null;
156 mService = null;
157 mRecentTasks = null;
158 mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThreadTest");
159 }
160
Craig Mautner21d24a22014-04-23 11:45:37 -0700161 void startPersisting() {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800162 if (!mLazyTaskWriterThread.isAlive()) {
163 mLazyTaskWriterThread.start();
164 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700165 }
166
Craig Mautner63f10902014-09-16 23:57:21 -0700167 private void removeThumbnails(TaskRecord task) {
168 final String taskString = Integer.toString(task.taskId);
169 for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
170 final WriteQueueItem item = mWriteQueue.get(queueNdx);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800171 if (item instanceof ImageWriteQueueItem) {
172 final File thumbnailFile = new File(((ImageWriteQueueItem) item).mFilePath);
173 if (thumbnailFile.getName().startsWith(taskString)) {
174 if (DEBUG) {
175 Slog.d(TAG, "Removing " + ((ImageWriteQueueItem) item).mFilePath +
176 " from write queue");
177 }
178 mWriteQueue.remove(queueNdx);
179 }
Craig Mautner63f10902014-09-16 23:57:21 -0700180 }
181 }
182 }
183
184 private void yieldIfQueueTooDeep() {
185 boolean stall = false;
186 synchronized (this) {
187 if (mNextWriteTime == FLUSH_QUEUE) {
188 stall = true;
189 }
190 }
191 if (stall) {
192 Thread.yield();
193 }
194 }
195
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800196 @NonNull
197 SparseBooleanArray loadPersistedTaskIdsForUser(int userId) {
198 if (mTaskIdsInFile.get(userId) != null) {
199 return mTaskIdsInFile.get(userId).clone();
200 }
201 final SparseBooleanArray persistedTaskIds = new SparseBooleanArray();
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700202 synchronized (mIoLock) {
203 BufferedReader reader = null;
204 String line;
205 try {
206 reader = new BufferedReader(new FileReader(getUserPersistedTaskIdsFile(userId)));
207 while ((line = reader.readLine()) != null) {
208 for (String taskIdString : line.split("\\s+")) {
209 int id = Integer.parseInt(taskIdString);
210 persistedTaskIds.put(id, true);
211 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800212 }
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700213 } catch (FileNotFoundException e) {
214 // File doesn't exist. Ignore.
215 } catch (Exception e) {
216 Slog.e(TAG, "Error while reading taskIds file for user " + userId, e);
217 } finally {
218 IoUtils.closeQuietly(reader);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800219 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800220 }
221 mTaskIdsInFile.put(userId, persistedTaskIds);
222 return persistedTaskIds.clone();
223 }
224
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700225
Suprabh Shuklaf50b4582016-02-23 17:44:22 -0800226 @VisibleForTesting
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700227 void writePersistedTaskIdsForUser(@NonNull SparseBooleanArray taskIds, int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800228 if (userId < 0) {
229 return;
230 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800231 final File persistedTaskIdsFile = getUserPersistedTaskIdsFile(userId);
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700232 synchronized (mIoLock) {
233 BufferedWriter writer = null;
234 try {
235 writer = new BufferedWriter(new FileWriter(persistedTaskIdsFile));
236 for (int i = 0; i < taskIds.size(); i++) {
237 if (taskIds.valueAt(i)) {
238 writer.write(String.valueOf(taskIds.keyAt(i)));
239 writer.newLine();
240 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800241 }
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700242 } catch (Exception e) {
243 Slog.e(TAG, "Error while writing taskIds file for user " + userId, e);
244 } finally {
245 IoUtils.closeQuietly(writer);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800246 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800247 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800248 }
249
250 void unloadUserDataFromMemory(int userId) {
251 mTaskIdsInFile.delete(userId);
252 }
253
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700254 void wakeup(TaskRecord task, boolean flush) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700255 synchronized (this) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700256 if (task != null) {
257 int queueNdx;
258 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
259 final WriteQueueItem item = mWriteQueue.get(queueNdx);
260 if (item instanceof TaskWriteQueueItem &&
261 ((TaskWriteQueueItem) item).mTask == task) {
Craig Mautner63f10902014-09-16 23:57:21 -0700262 if (!task.inRecents) {
263 // This task is being removed.
264 removeThumbnails(task);
265 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700266 break;
267 }
268 }
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700269 if (queueNdx < 0 && task.isPersistable) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700270 mWriteQueue.add(new TaskWriteQueueItem(task));
271 }
272 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800273 // Dummy. Ensures removeObsoleteFiles is called when LazyTaskThreadWriter is
274 // notified.
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700275 mWriteQueue.add(new WriteQueueItem());
276 }
Craig Mautner63f10902014-09-16 23:57:21 -0700277 if (flush || mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
278 mNextWriteTime = FLUSH_QUEUE;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700279 } else if (mNextWriteTime == 0) {
280 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
281 }
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700282 if (DEBUG) Slog.d(TAG, "wakeup: task=" + task + " flush=" + flush + " mNextWriteTime="
283 + mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size()
284 + " Callers=" + Debug.getCallers(4));
Craig Mautner21d24a22014-04-23 11:45:37 -0700285 notifyAll();
286 }
Craig Mautner63f10902014-09-16 23:57:21 -0700287
288 yieldIfQueueTooDeep();
Craig Mautner21d24a22014-04-23 11:45:37 -0700289 }
290
Dianne Hackbornce0fd762014-09-19 12:58:15 -0700291 void flush() {
292 synchronized (this) {
293 mNextWriteTime = FLUSH_QUEUE;
294 notifyAll();
295 do {
296 try {
297 wait();
298 } catch (InterruptedException e) {
299 }
300 } while (mNextWriteTime == FLUSH_QUEUE);
301 }
302 }
303
Suprabh Shukla23593142015-11-03 17:31:15 -0800304 void saveImage(Bitmap image, String filePath) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700305 synchronized (this) {
306 int queueNdx;
307 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
308 final WriteQueueItem item = mWriteQueue.get(queueNdx);
309 if (item instanceof ImageWriteQueueItem) {
310 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800311 if (imageWriteQueueItem.mFilePath.equals(filePath)) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700312 // replace the Bitmap with the new one.
313 imageWriteQueueItem.mImage = image;
314 break;
315 }
316 }
317 }
318 if (queueNdx < 0) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800319 mWriteQueue.add(new ImageWriteQueueItem(filePath, image));
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700320 }
Craig Mautner63f10902014-09-16 23:57:21 -0700321 if (mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
322 mNextWriteTime = FLUSH_QUEUE;
323 } else if (mNextWriteTime == 0) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700324 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
325 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800326 if (DEBUG) Slog.d(TAG, "saveImage: filePath=" + filePath + " now=" +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700327 SystemClock.uptimeMillis() + " mNextWriteTime=" +
328 mNextWriteTime + " Callers=" + Debug.getCallers(4));
329 notifyAll();
330 }
Craig Mautner63f10902014-09-16 23:57:21 -0700331
332 yieldIfQueueTooDeep();
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700333 }
334
Suprabh Shukla23593142015-11-03 17:31:15 -0800335 Bitmap getTaskDescriptionIcon(String filePath) {
Craig Mautner648f69b2014-09-18 14:16:26 -0700336 // See if it is in the write queue
Suprabh Shukla23593142015-11-03 17:31:15 -0800337 final Bitmap icon = getImageFromWriteQueue(filePath);
Craig Mautner648f69b2014-09-18 14:16:26 -0700338 if (icon != null) {
339 return icon;
340 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800341 return restoreImage(filePath);
Craig Mautner648f69b2014-09-18 14:16:26 -0700342 }
343
Suprabh Shukla23593142015-11-03 17:31:15 -0800344 Bitmap getImageFromWriteQueue(String filePath) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700345 synchronized (this) {
346 for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
347 final WriteQueueItem item = mWriteQueue.get(queueNdx);
348 if (item instanceof ImageWriteQueueItem) {
349 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800350 if (imageWriteQueueItem.mFilePath.equals(filePath)) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700351 return imageWriteQueueItem.mImage;
352 }
353 }
354 }
355 return null;
356 }
357 }
358
Craig Mautner21d24a22014-04-23 11:45:37 -0700359 private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700360 if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task);
Craig Mautner21d24a22014-04-23 11:45:37 -0700361 final XmlSerializer xmlSerializer = new FastXmlSerializer();
362 StringWriter stringWriter = new StringWriter();
363 xmlSerializer.setOutput(stringWriter);
364
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700365 if (DEBUG) xmlSerializer.setFeature(
Suprabh Shukla23593142015-11-03 17:31:15 -0800366 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
Craig Mautner21d24a22014-04-23 11:45:37 -0700367
368 // save task
369 xmlSerializer.startDocument(null, true);
370
371 xmlSerializer.startTag(null, TAG_TASK);
372 task.saveToXml(xmlSerializer);
373 xmlSerializer.endTag(null, TAG_TASK);
374
375 xmlSerializer.endDocument();
376 xmlSerializer.flush();
377
378 return stringWriter;
379 }
380
Craig Mautner77b04262014-06-27 15:22:12 -0700381 private String fileToString(File file) {
382 final String newline = System.lineSeparator();
383 try {
384 BufferedReader reader = new BufferedReader(new FileReader(file));
385 StringBuffer sb = new StringBuffer((int) file.length() * 2);
386 String line;
387 while ((line = reader.readLine()) != null) {
388 sb.append(line + newline);
389 }
390 reader.close();
391 return sb.toString();
392 } catch (IOException ioe) {
393 Slog.e(TAG, "Couldn't read file " + file.getName());
394 return null;
395 }
396 }
397
Craig Mautnera228ae92014-07-09 05:44:55 -0700398 private TaskRecord taskIdToTask(int taskId, ArrayList<TaskRecord> tasks) {
399 if (taskId < 0) {
400 return null;
401 }
402 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
403 final TaskRecord task = tasks.get(taskNdx);
404 if (task.taskId == taskId) {
405 return task;
406 }
407 }
408 Slog.e(TAG, "Restore affiliation error looking for taskId=" + taskId);
409 return null;
410 }
411
Winsonb258f6a2016-08-25 15:00:14 -0700412 @VisibleForTesting
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800413 List<TaskRecord> restoreTasksForUserLocked(final int userId) {
414 final ArrayList<TaskRecord> tasks = new ArrayList<TaskRecord>();
Craig Mautner21d24a22014-04-23 11:45:37 -0700415 ArraySet<Integer> recoveredTaskIds = new ArraySet<Integer>();
416
Suprabh Shukla23593142015-11-03 17:31:15 -0800417 File userTasksDir = getUserTasksDir(userId);
Suprabh Shukla23593142015-11-03 17:31:15 -0800418 File[] recentFiles = userTasksDir.listFiles();
Craig Mautner21d24a22014-04-23 11:45:37 -0700419 if (recentFiles == null) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800420 Slog.e(TAG, "restoreTasksForUserLocked: Unable to list files from " + userTasksDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700421 return tasks;
422 }
423
Winsonb258f6a2016-08-25 15:00:14 -0700424 // Get the last persist uptime so we know how to adjust the first/last active times for each
425 // task
426 ContentResolver cr = mService.mContext.getContentResolver();
427 long lastPersistUptime = Settings.Secure.getLong(cr,
428 Settings.Secure.TASK_PERSISTER_LAST_WRITE_UPTIME, 0);
429 if (DEBUG) {
430 Slog.d(TaskPersister.TAG, "restoreTasksForUserLocked: lastPersistUptime=" +
431 lastPersistUptime);
432 }
433
434 // Adjust the overview last visible task active time as we adjust the task active times when
435 // loading. See TaskRecord.restoreFromXml(). If we have not migrated yet, SystemUI will
436 // migrate the old value into the system setting.
437 if (lastPersistUptime > 0) {
438 long overviewLastActiveTime = Settings.Secure.getLongForUser(cr,
439 Settings.Secure.OVERVIEW_LAST_VISIBLE_TASK_ACTIVE_UPTIME, 0, userId);
440 if (DEBUG) {
441 Slog.d(TaskPersister.TAG, "restoreTasksForUserLocked: overviewLastActiveTime=" +
442 overviewLastActiveTime + " lastPersistUptime=" + lastPersistUptime);
443 }
444 Settings.Secure.putLongForUser(cr,
445 Settings.Secure.OVERVIEW_LAST_VISIBLE_TASK_ACTIVE_UPTIME,
446 -lastPersistUptime + overviewLastActiveTime, userId);
447 }
448
Craig Mautner21d24a22014-04-23 11:45:37 -0700449 for (int taskNdx = 0; taskNdx < recentFiles.length; ++taskNdx) {
450 File taskFile = recentFiles[taskNdx];
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800451 if (DEBUG) {
452 Slog.d(TAG, "restoreTasksForUserLocked: userId=" + userId
453 + ", taskFile=" + taskFile.getName());
454 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700455 BufferedReader reader = null;
Craig Mautnere0129b32014-05-25 16:41:09 -0700456 boolean deleteFile = false;
Craig Mautner21d24a22014-04-23 11:45:37 -0700457 try {
458 reader = new BufferedReader(new FileReader(taskFile));
459 final XmlPullParser in = Xml.newPullParser();
460 in.setInput(reader);
461
462 int event;
463 while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
464 event != XmlPullParser.END_TAG) {
465 final String name = in.getName();
466 if (event == XmlPullParser.START_TAG) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800467 if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: START_TAG name=" + name);
Craig Mautner21d24a22014-04-23 11:45:37 -0700468 if (TAG_TASK.equals(name)) {
Winsonb258f6a2016-08-25 15:00:14 -0700469 final TaskRecord task = TaskRecord.restoreFromXml(in, mService,
470 mStackSupervisor, lastPersistUptime);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800471 if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: restored task="
Suprabh Shukla23593142015-11-03 17:31:15 -0800472 + task);
Craig Mautner21d24a22014-04-23 11:45:37 -0700473 if (task != null) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700474 final int taskId = task.taskId;
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800475 if (mStackSupervisor.anyTaskForIdLocked(taskId,
476 /* restoreFromRecents= */ false, 0) != null) {
477 // Should not happen.
478 Slog.wtf(TAG, "Existing task with taskId " + taskId + "found");
479 } else if (userId != task.userId) {
480 // Should not happen.
481 Slog.wtf(TAG, "Task with userId " + task.userId + " found in "
482 + userTasksDir.getAbsolutePath());
483 } else {
484 // Looks fine.
485 mStackSupervisor.setNextTaskIdForUserLocked(taskId, userId);
Amith Yamasani515d4062015-09-28 11:30:06 -0700486 task.isPersistable = true;
487 tasks.add(task);
488 recoveredTaskIds.add(taskId);
Winsonb258f6a2016-08-25 15:00:14 -0700489
490 // We've shifted the first and last active times, so we need to
491 // persist the new task data to disk otherwise they will not
492 // have the updated values. This is only done once whenever
493 // the recents are first loaded for the user.
494 wakeup(task, false);
Amith Yamasani515d4062015-09-28 11:30:06 -0700495 }
Craig Mautner77b04262014-06-27 15:22:12 -0700496 } else {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800497 Slog.e(TAG, "restoreTasksForUserLocked: Unable to restore taskFile="
Suprabh Shukla23593142015-11-03 17:31:15 -0800498 + taskFile + ": " + fileToString(taskFile));
Craig Mautner21d24a22014-04-23 11:45:37 -0700499 }
500 } else {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800501 Slog.wtf(TAG, "restoreTasksForUserLocked: Unknown xml event=" + event
Suprabh Shukla23593142015-11-03 17:31:15 -0800502 + " name=" + name);
Craig Mautner21d24a22014-04-23 11:45:37 -0700503 }
504 }
505 XmlUtils.skipCurrentTag(in);
506 }
Craig Mautnere0129b32014-05-25 16:41:09 -0700507 } catch (Exception e) {
Craig Mautnera228ae92014-07-09 05:44:55 -0700508 Slog.wtf(TAG, "Unable to parse " + taskFile + ". Error ", e);
Craig Mautner77b04262014-06-27 15:22:12 -0700509 Slog.e(TAG, "Failing file: " + fileToString(taskFile));
Craig Mautnere0129b32014-05-25 16:41:09 -0700510 deleteFile = true;
Craig Mautner21d24a22014-04-23 11:45:37 -0700511 } finally {
Wale Ogunwale18795a22014-12-03 11:38:33 -0800512 IoUtils.closeQuietly(reader);
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700513 if (deleteFile) {
514 if (DEBUG) Slog.d(TAG, "Deleting file=" + taskFile.getName());
Craig Mautnere0129b32014-05-25 16:41:09 -0700515 taskFile.delete();
516 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700517 }
518 }
519
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700520 if (!DEBUG) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800521 removeObsoleteFiles(recoveredTaskIds, userTasksDir.listFiles());
522 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700523
Suprabh Shukla23593142015-11-03 17:31:15 -0800524 // Fix up task affiliation from taskIds
Craig Mautnera228ae92014-07-09 05:44:55 -0700525 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
526 final TaskRecord task = tasks.get(taskNdx);
527 task.setPrevAffiliate(taskIdToTask(task.mPrevAffiliateTaskId, tasks));
528 task.setNextAffiliate(taskIdToTask(task.mNextAffiliateTaskId, tasks));
529 }
530
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800531 Collections.sort(tasks, new Comparator<TaskRecord>() {
Craig Mautner21d24a22014-04-23 11:45:37 -0700532 @Override
533 public int compare(TaskRecord lhs, TaskRecord rhs) {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700534 final long diff = rhs.mLastTimeMoved - lhs.mLastTimeMoved;
Craig Mautner21d24a22014-04-23 11:45:37 -0700535 if (diff < 0) {
536 return -1;
537 } else if (diff > 0) {
538 return +1;
539 } else {
540 return 0;
541 }
542 }
543 });
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800544 return tasks;
Craig Mautner21d24a22014-04-23 11:45:37 -0700545 }
546
Craig Mautnere0129b32014-05-25 16:41:09 -0700547 private static void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds, File[] files) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800548 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: persistentTaskIds=" + persistentTaskIds +
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700549 " files=" + files);
Craig Mautnera5badf02014-09-11 12:47:03 -0700550 if (files == null) {
Suprabh Shukladc4b80d2016-04-20 15:24:31 -0700551 Slog.e(TAG, "File error accessing recents directory (directory doesn't exist?).");
Craig Mautnera5badf02014-09-11 12:47:03 -0700552 return;
553 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700554 for (int fileNdx = 0; fileNdx < files.length; ++fileNdx) {
555 File file = files[fileNdx];
556 String filename = file.getName();
Craig Mautnerffcfcaa2014-06-05 09:54:38 -0700557 final int taskIdEnd = filename.indexOf('_');
Craig Mautner21d24a22014-04-23 11:45:37 -0700558 if (taskIdEnd > 0) {
559 final int taskId;
560 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +0100561 taskId = Integer.parseInt(filename.substring(0, taskIdEnd));
Suprabh Shukla23593142015-11-03 17:31:15 -0800562 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: Found taskId=" + taskId);
Craig Mautner21d24a22014-04-23 11:45:37 -0700563 } catch (Exception e) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800564 Slog.wtf(TAG, "removeObsoleteFiles: Can't parse file=" + file.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700565 file.delete();
566 continue;
567 }
568 if (!persistentTaskIds.contains(taskId)) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800569 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: deleting file=" + file.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700570 file.delete();
571 }
572 }
573 }
574 }
575
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800576 private void writeTaskIdsFiles() {
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700577 SparseArray<SparseBooleanArray> changedTaskIdsPerUser = new SparseArray<>();
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800578 synchronized (mService) {
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700579 for (int userId : mRecentTasks.usersWithRecentsLoadedLocked()) {
580 SparseBooleanArray taskIdsToSave = mRecentTasks.mPersistedTaskIds.get(userId);
581 SparseBooleanArray persistedIdsInFile = mTaskIdsInFile.get(userId);
582 if (persistedIdsInFile != null && persistedIdsInFile.equals(taskIdsToSave)) {
583 continue;
584 } else {
585 SparseBooleanArray taskIdsToSaveCopy = taskIdsToSave.clone();
586 mTaskIdsInFile.put(userId, taskIdsToSaveCopy);
587 changedTaskIdsPerUser.put(userId, taskIdsToSaveCopy);
588 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800589 }
Suprabh Shuklafd0bd4f2016-08-24 14:08:29 -0700590 }
591 for (int i = 0; i < changedTaskIdsPerUser.size(); i++) {
592 writePersistedTaskIdsForUser(changedTaskIdsPerUser.valueAt(i),
593 changedTaskIdsPerUser.keyAt(i));
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800594 }
595 }
596
Craig Mautner21d24a22014-04-23 11:45:37 -0700597 private void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800598 int[] candidateUserIds;
599 synchronized (mService) {
600 // Remove only from directories of the users who have recents in memory synchronized
601 // with persistent storage.
602 candidateUserIds = mRecentTasks.usersWithRecentsLoadedLocked();
603 }
604 for (int userId : candidateUserIds) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800605 removeObsoleteFiles(persistentTaskIds, getUserImagesDir(userId).listFiles());
606 removeObsoleteFiles(persistentTaskIds, getUserTasksDir(userId).listFiles());
607 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700608 }
609
610 static Bitmap restoreImage(String filename) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700611 if (DEBUG) Slog.d(TAG, "restoreImage: restoring " + filename);
Suprabh Shukla23593142015-11-03 17:31:15 -0800612 return BitmapFactory.decodeFile(filename);
613 }
614
Suprabh Shuklaf50b4582016-02-23 17:44:22 -0800615 private File getUserPersistedTaskIdsFile(int userId) {
616 File userTaskIdsDir = new File(mTaskIdsDir, String.valueOf(userId));
617 if (!userTaskIdsDir.exists() && !userTaskIdsDir.mkdirs()) {
618 Slog.e(TAG, "Error while creating user directory: " + userTaskIdsDir);
619 }
620 return new File(userTaskIdsDir, PERSISTED_TASK_IDS_FILENAME);
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800621 }
622
Suprabh Shukla23593142015-11-03 17:31:15 -0800623 static File getUserTasksDir(int userId) {
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800624 File userTasksDir = new File(Environment.getDataSystemCeDirectory(userId), TASKS_DIRNAME);
Suprabh Shukla23593142015-11-03 17:31:15 -0800625
626 if (!userTasksDir.exists()) {
627 if (!userTasksDir.mkdir()) {
628 Slog.e(TAG, "Failure creating tasks directory for user " + userId + ": "
629 + userTasksDir);
630 }
631 }
632 return userTasksDir;
633 }
634
635 static File getUserImagesDir(int userId) {
Suprabh Shukladc4b80d2016-04-20 15:24:31 -0700636 return new File(Environment.getDataSystemCeDirectory(userId), IMAGES_DIRNAME);
637 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800638
Suprabh Shukladc4b80d2016-04-20 15:24:31 -0700639 private static boolean createParentDirectory(String filePath) {
640 File parentDir = new File(filePath).getParentFile();
641 return parentDir.exists() || parentDir.mkdirs();
Craig Mautner21d24a22014-04-23 11:45:37 -0700642 }
643
644 private class LazyTaskWriterThread extends Thread {
Craig Mautner21d24a22014-04-23 11:45:37 -0700645
646 LazyTaskWriterThread(String name) {
647 super(name);
648 }
649
650 @Override
651 public void run() {
Riley Andrewsf16c2e82015-06-02 18:24:48 -0700652 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Craig Mautner21d24a22014-04-23 11:45:37 -0700653 ArraySet<Integer> persistentTaskIds = new ArraySet<Integer>();
654 while (true) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700655 // We can't lock mService while holding TaskPersister.this, but we don't want to
656 // call removeObsoleteFiles every time through the loop, only the last time before
657 // going to sleep. The risk is that we call removeObsoleteFiles() successively.
658 final boolean probablyDone;
Craig Mautner21d24a22014-04-23 11:45:37 -0700659 synchronized (TaskPersister.this) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700660 probablyDone = mWriteQueue.isEmpty();
661 }
662 if (probablyDone) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700663 if (DEBUG) Slog.d(TAG, "Looking for obsolete files.");
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700664 persistentTaskIds.clear();
665 synchronized (mService) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700666 if (DEBUG) Slog.d(TAG, "mRecents=" + mRecentTasks);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800667 for (int taskNdx = mRecentTasks.size() - 1; taskNdx >= 0; --taskNdx) {
668 final TaskRecord task = mRecentTasks.get(taskNdx);
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700669 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task +
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700670 " persistable=" + task.isPersistable);
671 if ((task.isPersistable || task.inRecents)
Wale Ogunwale18795a22014-12-03 11:38:33 -0800672 && (task.stack == null || !task.stack.isHomeStack())) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700673 if (DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700674 persistentTaskIds.add(task.taskId);
675 } else {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700676 if (DEBUG) Slog.d(TAG,
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700677 "omitting from persistentTaskIds task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700678 }
679 }
680 }
681 removeObsoleteFiles(persistentTaskIds);
682 }
Suprabh Shukla4bccb462016-02-10 18:45:12 -0800683 writeTaskIdsFiles();
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700684
685 // If mNextWriteTime, then don't delay between each call to saveToXml().
686 final WriteQueueItem item;
687 synchronized (TaskPersister.this) {
Craig Mautner63f10902014-09-16 23:57:21 -0700688 if (mNextWriteTime != FLUSH_QUEUE) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700689 // The next write we don't have to wait so long.
690 mNextWriteTime = SystemClock.uptimeMillis() + INTER_WRITE_DELAY_MS;
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700691 if (DEBUG) Slog.d(TAG, "Next write time may be in " +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700692 INTER_WRITE_DELAY_MS + " msec. (" + mNextWriteTime + ")");
693 }
694
695 while (mWriteQueue.isEmpty()) {
Dianne Hackbornce0fd762014-09-19 12:58:15 -0700696 if (mNextWriteTime != 0) {
697 mNextWriteTime = 0; // idle.
698 TaskPersister.this.notifyAll(); // wake up flush() if needed.
699 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700700 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700701 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting indefinitely.");
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700702 TaskPersister.this.wait();
703 } catch (InterruptedException e) {
704 }
Craig Mautner63f10902014-09-16 23:57:21 -0700705 // Invariant: mNextWriteTime is either FLUSH_QUEUE or PRE_WRITE_DELAY_MS
706 // from now.
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700707 }
708 item = mWriteQueue.remove(0);
709
Craig Mautner21d24a22014-04-23 11:45:37 -0700710 long now = SystemClock.uptimeMillis();
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700711 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: now=" + now + " mNextWriteTime=" +
712 mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size());
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700713 while (now < mNextWriteTime) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700714 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700715 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting " +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700716 (mNextWriteTime - now));
717 TaskPersister.this.wait(mNextWriteTime - now);
Craig Mautner21d24a22014-04-23 11:45:37 -0700718 } catch (InterruptedException e) {
719 }
720 now = SystemClock.uptimeMillis();
721 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700722
723 // Got something to do.
Craig Mautner21d24a22014-04-23 11:45:37 -0700724 }
725
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700726 if (item instanceof ImageWriteQueueItem) {
727 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800728 final String filePath = imageWriteQueueItem.mFilePath;
Suprabh Shukladc4b80d2016-04-20 15:24:31 -0700729 if (!createParentDirectory(filePath)) {
730 Slog.e(TAG, "Error while creating images directory for file: " + filePath);
731 continue;
732 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700733 final Bitmap bitmap = imageWriteQueueItem.mImage;
Suprabh Shukla23593142015-11-03 17:31:15 -0800734 if (DEBUG) Slog.d(TAG, "writing bitmap: filename=" + filePath);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700735 FileOutputStream imageFile = null;
736 try {
Suprabh Shukla23593142015-11-03 17:31:15 -0800737 imageFile = new FileOutputStream(new File(filePath));
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700738 bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageFile);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700739 } catch (Exception e) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800740 Slog.e(TAG, "saveImage: unable to save " + filePath, e);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700741 } finally {
Wale Ogunwale18795a22014-12-03 11:38:33 -0800742 IoUtils.closeQuietly(imageFile);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700743 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700744 } else if (item instanceof TaskWriteQueueItem) {
745 // Write out one task.
746 StringWriter stringWriter = null;
747 TaskRecord task = ((TaskWriteQueueItem) item).mTask;
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700748 if (DEBUG) Slog.d(TAG, "Writing task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700749 synchronized (mService) {
Craig Mautner63f10902014-09-16 23:57:21 -0700750 if (task.inRecents) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700751 // Still there.
Craig Mautner21d24a22014-04-23 11:45:37 -0700752 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700753 if (DEBUG) Slog.d(TAG, "Saving task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700754 stringWriter = saveToXml(task);
755 } catch (IOException e) {
756 } catch (XmlPullParserException e) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700757 }
758 }
Dianne Hackborn852975d2014-08-22 17:42:43 -0700759 }
760 if (stringWriter != null) {
761 // Write out xml file while not holding mService lock.
762 FileOutputStream file = null;
763 AtomicFile atomicFile = null;
764 try {
Suprabh Shukla23593142015-11-03 17:31:15 -0800765 atomicFile = new AtomicFile(new File(
766 getUserTasksDir(task.userId),
767 String.valueOf(task.taskId) + RECENTS_FILENAME
768 + TASK_EXTENSION));
Dianne Hackborn852975d2014-08-22 17:42:43 -0700769 file = atomicFile.startWrite();
770 file.write(stringWriter.toString().getBytes());
771 file.write('\n');
772 atomicFile.finishWrite(file);
Suprabh Shukla23593142015-11-03 17:31:15 -0800773
Dianne Hackborn852975d2014-08-22 17:42:43 -0700774 } catch (IOException e) {
775 if (file != null) {
776 atomicFile.failWrite(file);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700777 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800778 Slog.e(TAG,
779 "Unable to open " + atomicFile + " for persisting. " + e);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700780 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700781 }
782 }
Winsonb258f6a2016-08-25 15:00:14 -0700783
784 // Always update the task persister uptime when updating any tasks
785 if (DEBUG) {
786 Slog.d(TAG, "LazyTaskWriter: Updating last write uptime=" +
787 SystemClock.elapsedRealtime());
788 }
789 Settings.Secure.putLong(mService.mContext.getContentResolver(),
790 Settings.Secure.TASK_PERSISTER_LAST_WRITE_UPTIME,
791 SystemClock.elapsedRealtime());
Craig Mautner21d24a22014-04-23 11:45:37 -0700792 }
793 }
794 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700795}