2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.actionbarsherlock.widget;
19 import android.content.ComponentName;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.pm.ResolveInfo;
23 import android.database.DataSetObservable;
24 import android.os.Handler;
25 import android.text.TextUtils;
26 import android.util.Log;
27 import android.util.Xml;
29 import org.xmlpull.v1.XmlPullParser;
30 import org.xmlpull.v1.XmlPullParserException;
31 import org.xmlpull.v1.XmlSerializer;
33 import java.io.FileInputStream;
34 import java.io.FileNotFoundException;
35 import java.io.FileOutputStream;
36 import java.io.IOException;
37 import java.math.BigDecimal;
38 import java.util.ArrayList;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.LinkedHashSet;
42 import java.util.LinkedList;
43 import java.util.List;
46 import java.util.concurrent.Executor;
50 * This class represents a data model for choosing a component for handing a
51 * given {@link Intent}. The model is responsible for querying the system for
52 * activities that can handle the given intent and order found activities
53 * based on historical data of previous choices. The historical data is stored
54 * in an application private file. If a client does not want to have persistent
55 * choice history the file can be omitted, thus the activities will be ordered
56 * based on historical usage for the current session.
59 * For each backing history file there is a singleton instance of this class. Thus,
60 * several clients that specify the same history file will share the same model. Note
61 * that if multiple clients are sharing the same model they should implement semantically
62 * equivalent functionality since setting the model intent will change the found
63 * activities and they may be inconsistent with the functionality of some of the clients.
64 * For example, choosing a share activity can be implemented by a single backing
65 * model and two different views for performing the selection. If however, one of the
66 * views is used for sharing but the other for importing, for example, then each
67 * view should be backed by a separate model.
70 * The way clients interact with this class is as follows:
75 * // Get a model and set it to a couple of clients with semantically similar function.
76 * ActivityChooserModel dataModel =
77 * ActivityChooserModel.get(context, "task_specific_history_file_name.xml");
79 * ActivityChooserModelClient modelClient1 = getActivityChooserModelClient1();
80 * modelClient1.setActivityChooserModel(dataModel);
82 * ActivityChooserModelClient modelClient2 = getActivityChooserModelClient2();
83 * modelClient2.setActivityChooserModel(dataModel);
85 * // Set an intent to choose a an activity for.
86 * dataModel.setIntent(intent);
91 * <strong>Note:</strong> This class is thread safe.
96 class ActivityChooserModel extends DataSetObservable {
99 * Client that utilizes an {@link ActivityChooserModel}.
101 public interface ActivityChooserModelClient {
104 * Sets the {@link ActivityChooserModel}.
106 * @param dataModel The model.
108 public void setActivityChooserModel(ActivityChooserModel dataModel);
112 * Defines a sorter that is responsible for sorting the activities
113 * based on the provided historical choices and an intent.
115 public interface ActivitySorter {
118 * Sorts the <code>activities</code> in descending order of relevance
119 * based on previous history and an intent.
121 * @param intent The {@link Intent}.
122 * @param activities Activities to be sorted.
123 * @param historicalRecords Historical records.
125 // This cannot be done by a simple comparator since an Activity weight
126 // is computed from history. Note that Activity implements Comparable.
127 public void sort(Intent intent, List<ActivityResolveInfo> activities,
128 List<HistoricalRecord> historicalRecords);
132 * Listener for choosing an activity.
134 public interface OnChooseActivityListener {
137 * Called when an activity has been chosen. The client can decide whether
138 * an activity can be chosen and if so the caller of
139 * {@link ActivityChooserModel#chooseActivity(int)} will receive and {@link Intent}
142 * <strong>Note:</strong> Modifying the intent is not permitted and
143 * any changes to the latter will be ignored.
146 * @param host The listener's host model.
147 * @param intent The intent for launching the chosen activity.
148 * @return Whether the intent is handled and should not be delivered to clients.
150 * @see ActivityChooserModel#chooseActivity(int)
152 public boolean onChooseActivity(ActivityChooserModel host, Intent intent);
156 * Flag for selecting debug mode.
158 private static final boolean DEBUG = false;
161 * Tag used for logging.
163 private static final String LOG_TAG = ActivityChooserModel.class.getSimpleName();
166 * The root tag in the history file.
168 private static final String TAG_HISTORICAL_RECORDS = "historical-records";
171 * The tag for a record in the history file.
173 private static final String TAG_HISTORICAL_RECORD = "historical-record";
176 * Attribute for the activity.
178 private static final String ATTRIBUTE_ACTIVITY = "activity";
181 * Attribute for the choice time.
183 private static final String ATTRIBUTE_TIME = "time";
186 * Attribute for the choice weight.
188 private static final String ATTRIBUTE_WEIGHT = "weight";
191 * The default name of the choice history file.
193 public static final String DEFAULT_HISTORY_FILE_NAME =
194 "activity_choser_model_history.xml";
197 * The default maximal length of the choice history.
199 public static final int DEFAULT_HISTORY_MAX_LENGTH = 50;
202 * The amount with which to inflate a chosen activity when set as default.
204 private static final int DEFAULT_ACTIVITY_INFLATION = 5;
207 * Default weight for a choice record.
209 private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = 1.0f;
212 * The extension of the history file.
214 private static final String HISTORY_FILE_EXTENSION = ".xml";
217 * An invalid item index.
219 private static final int INVALID_INDEX = -1;
222 * Lock to guard the model registry.
224 private static final Object sRegistryLock = new Object();
227 * This the registry for data models.
229 private static final Map<String, ActivityChooserModel> sDataModelRegistry =
230 new HashMap<String, ActivityChooserModel>();
233 * Lock for synchronizing on this instance.
235 private final Object mInstanceLock = new Object();
238 * List of activities that can handle the current intent.
240 private final List<ActivityResolveInfo> mActivites = new ArrayList<ActivityResolveInfo>();
243 * List with historical choice records.
245 private final List<HistoricalRecord> mHistoricalRecords = new ArrayList<HistoricalRecord>();
248 * Context for accessing resources.
250 private final Context mContext;
253 * The name of the history file that backs this model.
255 private final String mHistoryFileName;
258 * The intent for which a activity is being chosen.
260 private Intent mIntent;
263 * The sorter for ordering activities based on intent and past choices.
265 private ActivitySorter mActivitySorter = new DefaultSorter();
268 * The maximal length of the choice history.
270 private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH;
273 * Flag whether choice history can be read. In general many clients can
274 * share the same data model and {@link #readHistoricalData()} may be called
275 * by arbitrary of them any number of times. Therefore, this class guarantees
276 * that the very first read succeeds and subsequent reads can be performed
277 * only after a call to {@link #persistHistoricalData()} followed by change
278 * of the share records.
280 private boolean mCanReadHistoricalData = true;
283 * Flag whether the choice history was read. This is used to enforce that
284 * before calling {@link #persistHistoricalData()} a call to
285 * {@link #persistHistoricalData()} has been made. This aims to avoid a
286 * scenario in which a choice history file exits, it is not read yet and
287 * it is overwritten. Note that always all historical records are read in
288 * full and the file is rewritten. This is necessary since we need to
289 * purge old records that are outside of the sliding window of past choices.
291 private boolean mReadShareHistoryCalled = false;
294 * Flag whether the choice records have changed. In general many clients can
295 * share the same data model and {@link #persistHistoricalData()} may be called
296 * by arbitrary of them any number of times. Therefore, this class guarantees
297 * that choice history will be persisted only if it has changed.
299 private boolean mHistoricalRecordsChanged = true;
302 * Hander for scheduling work on client tread.
304 private final Handler mHandler = new Handler();
307 * Policy for controlling how the model handles chosen activities.
309 private OnChooseActivityListener mActivityChoserModelPolicy;
312 * Gets the data model backed by the contents of the provided file with historical data.
313 * Note that only one data model is backed by a given file, thus multiple calls with
314 * the same file name will return the same model instance. If no such instance is present
317 * <strong>Note:</strong> To use the default historical data file clients should explicitly
318 * pass as file name {@link #DEFAULT_HISTORY_FILE_NAME}. If no persistence of the choice
319 * history is desired clients should pass <code>null</code> for the file name. In such
320 * case a new model is returned for each invocation.
324 * <strong>Always use difference historical data files for semantically different actions.
325 * For example, sharing is different from importing.</strong>
328 * @param context Context for loading resources.
329 * @param historyFileName File name with choice history, <code>null</code>
330 * if the model should not be backed by a file. In this case the activities
331 * will be ordered only by data from the current session.
335 public static ActivityChooserModel get(Context context, String historyFileName) {
336 synchronized (sRegistryLock) {
337 ActivityChooserModel dataModel = sDataModelRegistry.get(historyFileName);
338 if (dataModel == null) {
339 dataModel = new ActivityChooserModel(context, historyFileName);
340 sDataModelRegistry.put(historyFileName, dataModel);
342 dataModel.readHistoricalData();
348 * Creates a new instance.
350 * @param context Context for loading resources.
351 * @param historyFileName The history XML file.
353 private ActivityChooserModel(Context context, String historyFileName) {
354 mContext = context.getApplicationContext();
355 if (!TextUtils.isEmpty(historyFileName)
356 && !historyFileName.endsWith(HISTORY_FILE_EXTENSION)) {
357 mHistoryFileName = historyFileName + HISTORY_FILE_EXTENSION;
359 mHistoryFileName = historyFileName;
364 * Sets an intent for which to choose a activity.
366 * <strong>Note:</strong> Clients must set only semantically similar
367 * intents for each data model.
370 * @param intent The intent.
372 public void setIntent(Intent intent) {
373 synchronized (mInstanceLock) {
374 if (mIntent == intent) {
378 loadActivitiesLocked();
383 * Gets the intent for which a activity is being chosen.
385 * @return The intent.
387 public Intent getIntent() {
388 synchronized (mInstanceLock) {
394 * Gets the number of activities that can handle the intent.
396 * @return The activity count.
398 * @see #setIntent(Intent)
400 public int getActivityCount() {
401 synchronized (mInstanceLock) {
402 return mActivites.size();
407 * Gets an activity at a given index.
409 * @return The activity.
411 * @see ActivityResolveInfo
412 * @see #setIntent(Intent)
414 public ResolveInfo getActivity(int index) {
415 synchronized (mInstanceLock) {
416 return mActivites.get(index).resolveInfo;
421 * Gets the index of a the given activity.
423 * @param activity The activity index.
425 * @return The index if found, -1 otherwise.
427 public int getActivityIndex(ResolveInfo activity) {
428 List<ActivityResolveInfo> activities = mActivites;
429 final int activityCount = activities.size();
430 for (int i = 0; i < activityCount; i++) {
431 ActivityResolveInfo currentActivity = activities.get(i);
432 if (currentActivity.resolveInfo == activity) {
436 return INVALID_INDEX;
440 * Chooses a activity to handle the current intent. This will result in
441 * adding a historical record for that action and construct intent with
442 * its component name set such that it can be immediately started by the
445 * <strong>Note:</strong> By calling this method the client guarantees
446 * that the returned intent will be started. This intent is returned to
447 * the client solely to let additional customization before the start.
450 * @return An {@link Intent} for launching the activity or null if the
451 * policy has consumed the intent.
453 * @see HistoricalRecord
454 * @see OnChooseActivityListener
456 public Intent chooseActivity(int index) {
457 ActivityResolveInfo chosenActivity = mActivites.get(index);
459 ComponentName chosenName = new ComponentName(
460 chosenActivity.resolveInfo.activityInfo.packageName,
461 chosenActivity.resolveInfo.activityInfo.name);
463 Intent choiceIntent = new Intent(mIntent);
464 choiceIntent.setComponent(chosenName);
466 if (mActivityChoserModelPolicy != null) {
467 // Do not allow the policy to change the intent.
468 Intent choiceIntentCopy = new Intent(choiceIntent);
469 final boolean handled = mActivityChoserModelPolicy.onChooseActivity(this,
476 HistoricalRecord historicalRecord = new HistoricalRecord(chosenName,
477 System.currentTimeMillis(), DEFAULT_HISTORICAL_RECORD_WEIGHT);
478 addHisoricalRecord(historicalRecord);
484 * Sets the listener for choosing an activity.
486 * @param listener The listener.
488 public void setOnChooseActivityListener(OnChooseActivityListener listener) {
489 mActivityChoserModelPolicy = listener;
493 * Gets the default activity, The default activity is defined as the one
494 * with highest rank i.e. the first one in the list of activities that can
497 * @return The default activity, <code>null</code> id not activities.
499 * @see #getActivity(int)
501 public ResolveInfo getDefaultActivity() {
502 synchronized (mInstanceLock) {
503 if (!mActivites.isEmpty()) {
504 return mActivites.get(0).resolveInfo;
511 * Sets the default activity. The default activity is set by adding a
512 * historical record with weight high enough that this activity will
513 * become the highest ranked. Such a strategy guarantees that the default
514 * will eventually change if not used. Also the weight of the record for
515 * setting a default is inflated with a constant amount to guarantee that
516 * it will stay as default for awhile.
518 * @param index The index of the activity to set as default.
520 public void setDefaultActivity(int index) {
521 ActivityResolveInfo newDefaultActivity = mActivites.get(index);
522 ActivityResolveInfo oldDefaultActivity = mActivites.get(0);
525 if (oldDefaultActivity != null) {
526 // Add a record with weight enough to boost the chosen at the top.
527 weight = oldDefaultActivity.weight - newDefaultActivity.weight
528 + DEFAULT_ACTIVITY_INFLATION;
530 weight = DEFAULT_HISTORICAL_RECORD_WEIGHT;
533 ComponentName defaultName = new ComponentName(
534 newDefaultActivity.resolveInfo.activityInfo.packageName,
535 newDefaultActivity.resolveInfo.activityInfo.name);
536 HistoricalRecord historicalRecord = new HistoricalRecord(defaultName,
537 System.currentTimeMillis(), weight);
538 addHisoricalRecord(historicalRecord);
542 * Reads the history data from the backing file if the latter
543 * was provided. Calling this method more than once before a call
544 * to {@link #persistHistoricalData()} has been made has no effect.
546 * <strong>Note:</strong> Historical data is read asynchronously and
547 * as soon as the reading is completed any registered
548 * {@link DataSetObserver}s will be notified. Also no historical
549 * data is read until this method is invoked.
552 private void readHistoricalData() {
553 synchronized (mInstanceLock) {
554 if (!mCanReadHistoricalData || !mHistoricalRecordsChanged) {
557 mCanReadHistoricalData = false;
558 mReadShareHistoryCalled = true;
559 if (!TextUtils.isEmpty(mHistoryFileName)) {
560 /*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryLoader());
565 private static final SerialExecutor SERIAL_EXECUTOR = new SerialExecutor();
567 private static class SerialExecutor implements Executor {
568 final LinkedList<Runnable> mTasks = new LinkedList<Runnable>();
571 public synchronized void execute(final Runnable r) {
572 mTasks.offer(new Runnable() {
581 if (mActive == null) {
586 protected synchronized void scheduleNext() {
587 if ((mActive = mTasks.poll()) != null) {
594 * Persists the history data to the backing file if the latter
595 * was provided. Calling this method before a call to {@link #readHistoricalData()}
596 * throws an exception. Calling this method more than one without choosing an
597 * activity has not effect.
599 * @throws IllegalStateException If this method is called before a call to
600 * {@link #readHistoricalData()}.
602 private void persistHistoricalData() {
603 synchronized (mInstanceLock) {
604 if (!mReadShareHistoryCalled) {
605 throw new IllegalStateException("No preceding call to #readHistoricalData");
607 if (!mHistoricalRecordsChanged) {
610 mHistoricalRecordsChanged = false;
611 mCanReadHistoricalData = true;
612 if (!TextUtils.isEmpty(mHistoryFileName)) {
613 /*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryPersister());
619 * Sets the sorter for ordering activities based on historical data and an intent.
621 * @param activitySorter The sorter.
623 * @see ActivitySorter
625 public void setActivitySorter(ActivitySorter activitySorter) {
626 synchronized (mInstanceLock) {
627 if (mActivitySorter == activitySorter) {
630 mActivitySorter = activitySorter;
636 * Sorts the activities based on history and an intent. If
637 * a sorter is not specified this a default implementation is used.
639 * @see #setActivitySorter(ActivitySorter)
641 private void sortActivities() {
642 synchronized (mInstanceLock) {
643 if (mActivitySorter != null && !mActivites.isEmpty()) {
644 mActivitySorter.sort(mIntent, mActivites,
645 Collections.unmodifiableList(mHistoricalRecords));
652 * Sets the maximal size of the historical data. Defaults to
653 * {@link #DEFAULT_HISTORY_MAX_LENGTH}
655 * <strong>Note:</strong> Setting this property will immediately
656 * enforce the specified max history size by dropping enough old
657 * historical records to enforce the desired size. Thus, any
658 * records that exceed the history size will be discarded and
662 * @param historyMaxSize The max history size.
664 public void setHistoryMaxSize(int historyMaxSize) {
665 synchronized (mInstanceLock) {
666 if (mHistoryMaxSize == historyMaxSize) {
669 mHistoryMaxSize = historyMaxSize;
670 pruneExcessiveHistoricalRecordsLocked();
676 * Gets the history max size.
678 * @return The history max size.
680 public int getHistoryMaxSize() {
681 synchronized (mInstanceLock) {
682 return mHistoryMaxSize;
687 * Gets the history size.
689 * @return The history size.
691 public int getHistorySize() {
692 synchronized (mInstanceLock) {
693 return mHistoricalRecords.size();
698 * Adds a historical record.
700 * @param historicalRecord The record to add.
701 * @return True if the record was added.
703 private boolean addHisoricalRecord(HistoricalRecord historicalRecord) {
704 synchronized (mInstanceLock) {
705 final boolean added = mHistoricalRecords.add(historicalRecord);
707 mHistoricalRecordsChanged = true;
708 pruneExcessiveHistoricalRecordsLocked();
709 persistHistoricalData();
717 * Prunes older excessive records to guarantee {@link #mHistoryMaxSize}.
719 private void pruneExcessiveHistoricalRecordsLocked() {
720 List<HistoricalRecord> choiceRecords = mHistoricalRecords;
721 final int pruneCount = choiceRecords.size() - mHistoryMaxSize;
722 if (pruneCount <= 0) {
725 mHistoricalRecordsChanged = true;
726 for (int i = 0; i < pruneCount; i++) {
727 HistoricalRecord prunedRecord = choiceRecords.remove(0);
729 Log.i(LOG_TAG, "Pruned: " + prunedRecord);
735 * Loads the activities.
737 private void loadActivitiesLocked() {
739 if (mIntent != null) {
740 List<ResolveInfo> resolveInfos =
741 mContext.getPackageManager().queryIntentActivities(mIntent, 0);
742 final int resolveInfoCount = resolveInfos.size();
743 for (int i = 0; i < resolveInfoCount; i++) {
744 ResolveInfo resolveInfo = resolveInfos.get(i);
745 mActivites.add(new ActivityResolveInfo(resolveInfo));
754 * Represents a record in the history.
756 public final static class HistoricalRecord {
761 public final ComponentName activity;
766 public final long time;
771 public final float weight;
774 * Creates a new instance.
776 * @param activityName The activity component name flattened to string.
777 * @param time The time the activity was chosen.
778 * @param weight The weight of the record.
780 public HistoricalRecord(String activityName, long time, float weight) {
781 this(ComponentName.unflattenFromString(activityName), time, weight);
785 * Creates a new instance.
787 * @param activityName The activity name.
788 * @param time The time the activity was chosen.
789 * @param weight The weight of the record.
791 public HistoricalRecord(ComponentName activityName, long time, float weight) {
792 this.activity = activityName;
794 this.weight = weight;
798 public int hashCode() {
799 final int prime = 31;
801 result = prime * result + ((activity == null) ? 0 : activity.hashCode());
802 result = prime * result + (int) (time ^ (time >>> 32));
803 result = prime * result + Float.floatToIntBits(weight);
808 public boolean equals(Object obj) {
815 if (getClass() != obj.getClass()) {
818 HistoricalRecord other = (HistoricalRecord) obj;
819 if (activity == null) {
820 if (other.activity != null) {
823 } else if (!activity.equals(other.activity)) {
826 if (time != other.time) {
829 if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
836 public String toString() {
837 StringBuilder builder = new StringBuilder();
839 builder.append("; activity:").append(activity);
840 builder.append("; time:").append(time);
841 builder.append("; weight:").append(new BigDecimal(weight));
843 return builder.toString();
848 * Represents an activity.
850 public final class ActivityResolveInfo implements Comparable<ActivityResolveInfo> {
853 * The {@link ResolveInfo} of the activity.
855 public final ResolveInfo resolveInfo;
858 * Weight of the activity. Useful for sorting.
863 * Creates a new instance.
865 * @param resolveInfo activity {@link ResolveInfo}.
867 public ActivityResolveInfo(ResolveInfo resolveInfo) {
868 this.resolveInfo = resolveInfo;
872 public int hashCode() {
873 return 31 + Float.floatToIntBits(weight);
877 public boolean equals(Object obj) {
884 if (getClass() != obj.getClass()) {
887 ActivityResolveInfo other = (ActivityResolveInfo) obj;
888 if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
894 public int compareTo(ActivityResolveInfo another) {
895 return Float.floatToIntBits(another.weight) - Float.floatToIntBits(weight);
899 public String toString() {
900 StringBuilder builder = new StringBuilder();
902 builder.append("resolveInfo:").append(resolveInfo.toString());
903 builder.append("; weight:").append(new BigDecimal(weight));
905 return builder.toString();
910 * Default activity sorter implementation.
912 private final class DefaultSorter implements ActivitySorter {
913 private static final float WEIGHT_DECAY_COEFFICIENT = 0.95f;
915 private final Map<String, ActivityResolveInfo> mPackageNameToActivityMap =
916 new HashMap<String, ActivityResolveInfo>();
918 public void sort(Intent intent, List<ActivityResolveInfo> activities,
919 List<HistoricalRecord> historicalRecords) {
920 Map<String, ActivityResolveInfo> packageNameToActivityMap =
921 mPackageNameToActivityMap;
922 packageNameToActivityMap.clear();
924 final int activityCount = activities.size();
925 for (int i = 0; i < activityCount; i++) {
926 ActivityResolveInfo activity = activities.get(i);
927 activity.weight = 0.0f;
928 String packageName = activity.resolveInfo.activityInfo.packageName;
929 packageNameToActivityMap.put(packageName, activity);
932 final int lastShareIndex = historicalRecords.size() - 1;
933 float nextRecordWeight = 1;
934 for (int i = lastShareIndex; i >= 0; i--) {
935 HistoricalRecord historicalRecord = historicalRecords.get(i);
936 String packageName = historicalRecord.activity.getPackageName();
937 ActivityResolveInfo activity = packageNameToActivityMap.get(packageName);
938 if (activity != null) {
939 activity.weight += historicalRecord.weight * nextRecordWeight;
940 nextRecordWeight = nextRecordWeight * WEIGHT_DECAY_COEFFICIENT;
944 Collections.sort(activities);
947 for (int i = 0; i < activityCount; i++) {
948 Log.i(LOG_TAG, "Sorted: " + activities.get(i));
955 * Command for reading the historical records from a file off the UI thread.
957 private final class HistoryLoader implements Runnable {
960 FileInputStream fis = null;
962 fis = mContext.openFileInput(mHistoryFileName);
963 } catch (FileNotFoundException fnfe) {
965 Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName);
970 XmlPullParser parser = Xml.newPullParser();
971 parser.setInput(fis, null);
973 int type = XmlPullParser.START_DOCUMENT;
974 while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
975 type = parser.next();
978 if (!TAG_HISTORICAL_RECORDS.equals(parser.getName())) {
979 throw new XmlPullParserException("Share records file does not start with "
980 + TAG_HISTORICAL_RECORDS + " tag.");
983 List<HistoricalRecord> readRecords = new ArrayList<HistoricalRecord>();
986 type = parser.next();
987 if (type == XmlPullParser.END_DOCUMENT) {
990 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
993 String nodeName = parser.getName();
994 if (!TAG_HISTORICAL_RECORD.equals(nodeName)) {
995 throw new XmlPullParserException("Share records file not well-formed.");
998 String activity = parser.getAttributeValue(null, ATTRIBUTE_ACTIVITY);
1000 Long.parseLong(parser.getAttributeValue(null, ATTRIBUTE_TIME));
1001 final float weight =
1002 Float.parseFloat(parser.getAttributeValue(null, ATTRIBUTE_WEIGHT));
1004 HistoricalRecord readRecord = new HistoricalRecord(activity, time,
1006 readRecords.add(readRecord);
1009 Log.i(LOG_TAG, "Read " + readRecord.toString());
1014 Log.i(LOG_TAG, "Read " + readRecords.size() + " historical records.");
1017 synchronized (mInstanceLock) {
1018 Set<HistoricalRecord> uniqueShareRecords =
1019 new LinkedHashSet<HistoricalRecord>(readRecords);
1021 // Make sure no duplicates. Example: Read a file with
1022 // one record, add one record, persist the two records,
1023 // add a record, read the persisted records - the
1024 // read two records should not be added again.
1025 List<HistoricalRecord> historicalRecords = mHistoricalRecords;
1026 final int historicalRecordsCount = historicalRecords.size();
1027 for (int i = historicalRecordsCount - 1; i >= 0; i--) {
1028 HistoricalRecord historicalRecord = historicalRecords.get(i);
1029 uniqueShareRecords.add(historicalRecord);
1032 if (historicalRecords.size() == uniqueShareRecords.size()) {
1036 // Make sure the oldest records go to the end.
1037 historicalRecords.clear();
1038 historicalRecords.addAll(uniqueShareRecords);
1040 mHistoricalRecordsChanged = true;
1042 // Do this on the client thread since the client may be on the UI
1043 // thread, wait for data changes which happen during sorting, and
1044 // perform UI modification based on the data change.
1045 mHandler.post(new Runnable() {
1047 pruneExcessiveHistoricalRecordsLocked();
1052 } catch (XmlPullParserException xppe) {
1053 Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, xppe);
1054 } catch (IOException ioe) {
1055 Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, ioe);
1060 } catch (IOException ioe) {
1069 * Command for persisting the historical records to a file off the UI thread.
1071 private final class HistoryPersister implements Runnable {
1074 FileOutputStream fos = null;
1075 List<HistoricalRecord> records = null;
1077 synchronized (mInstanceLock) {
1078 records = new ArrayList<HistoricalRecord>(mHistoricalRecords);
1082 fos = mContext.openFileOutput(mHistoryFileName, Context.MODE_PRIVATE);
1083 } catch (FileNotFoundException fnfe) {
1084 Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, fnfe);
1088 XmlSerializer serializer = Xml.newSerializer();
1091 serializer.setOutput(fos, null);
1092 serializer.startDocument("UTF-8", true);
1093 serializer.startTag(null, TAG_HISTORICAL_RECORDS);
1095 final int recordCount = records.size();
1096 for (int i = 0; i < recordCount; i++) {
1097 HistoricalRecord record = records.remove(0);
1098 serializer.startTag(null, TAG_HISTORICAL_RECORD);
1099 serializer.attribute(null, ATTRIBUTE_ACTIVITY, record.activity.flattenToString());
1100 serializer.attribute(null, ATTRIBUTE_TIME, String.valueOf(record.time));
1101 serializer.attribute(null, ATTRIBUTE_WEIGHT, String.valueOf(record.weight));
1102 serializer.endTag(null, TAG_HISTORICAL_RECORD);
1104 Log.i(LOG_TAG, "Wrote " + record.toString());
1108 serializer.endTag(null, TAG_HISTORICAL_RECORDS);
1109 serializer.endDocument();
1112 Log.i(LOG_TAG, "Wrote " + recordCount + " historical records.");
1114 } catch (IllegalArgumentException iae) {
1115 Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, iae);
1116 } catch (IllegalStateException ise) {
1117 Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ise);
1118 } catch (IOException ioe) {
1119 Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ioe);
1124 } catch (IOException e) {