ActivityChooserModel.java revision e290ed32f85ff6307a53922a78684b31d30b8dc5
1/*
2 * Copyright (C) 2013 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 android.support.v7.internal.widget;
18
19import android.content.ComponentName;
20import android.content.Context;
21import android.content.Intent;
22import android.content.pm.ResolveInfo;
23import android.database.DataSetObservable;
24import android.os.AsyncTask;
25import android.os.Build;
26import android.text.TextUtils;
27import android.util.Log;
28import android.util.Xml;
29
30import org.xmlpull.v1.XmlPullParser;
31import org.xmlpull.v1.XmlPullParserException;
32import org.xmlpull.v1.XmlSerializer;
33
34import java.io.FileInputStream;
35import java.io.FileNotFoundException;
36import java.io.FileOutputStream;
37import java.io.IOException;
38import java.math.BigDecimal;
39import java.util.ArrayList;
40import java.util.Collections;
41import java.util.HashMap;
42import java.util.List;
43import java.util.Map;
44
45/**
46 * <p>
47 * This class represents a data model for choosing a component for handing a
48 * given {@link Intent}. The model is responsible for querying the system for
49 * activities that can handle the given intent and order found activities
50 * based on historical data of previous choices. The historical data is stored
51 * in an application private file. If a client does not want to have persistent
52 * choice history the file can be omitted, thus the activities will be ordered
53 * based on historical usage for the current session.
54 * <p>
55 * </p>
56 * For each backing history file there is a singleton instance of this class. Thus,
57 * several clients that specify the same history file will share the same model. Note
58 * that if multiple clients are sharing the same model they should implement semantically
59 * equivalent functionality since setting the model intent will change the found
60 * activities and they may be inconsistent with the functionality of some of the clients.
61 * For example, choosing a share activity can be implemented by a single backing
62 * model and two different views for performing the selection. If however, one of the
63 * views is used for sharing but the other for importing, for example, then each
64 * view should be backed by a separate model.
65 * </p>
66 * <p>
67 * The way clients interact with this class is as follows:
68 * </p>
69 * <p>
70 * <pre>
71 * <code>
72 *  // Get a model and set it to a couple of clients with semantically similar function.
73 *  ActivityChooserModel dataModel =
74 *      ActivityChooserModel.get(context, "task_specific_history_file_name.xml");
75 *
76 *  ActivityChooserModelClient modelClient1 = getActivityChooserModelClient1();
77 *  modelClient1.setActivityChooserModel(dataModel);
78 *
79 *  ActivityChooserModelClient modelClient2 = getActivityChooserModelClient2();
80 *  modelClient2.setActivityChooserModel(dataModel);
81 *
82 *  // Set an intent to choose a an activity for.
83 *  dataModel.setIntent(intent);
84 * <pre>
85 * <code>
86 * </p>
87 * <p>
88 * <strong>Note:</strong> This class is thread safe.
89 * </p>
90 *
91 * @hide
92 */
93public class ActivityChooserModel extends DataSetObservable {
94
95    /**
96     * Client that utilizes an {@link ActivityChooserModel}.
97     */
98    public interface ActivityChooserModelClient {
99
100        /**
101         * Sets the {@link ActivityChooserModel}.
102         *
103         * @param dataModel The model.
104         */
105        public void setActivityChooserModel(ActivityChooserModel dataModel);
106    }
107
108    /**
109     * Defines a sorter that is responsible for sorting the activities
110     * based on the provided historical choices and an intent.
111     */
112    public interface ActivitySorter {
113
114        /**
115         * Sorts the <code>activities</code> in descending order of relevance
116         * based on previous history and an intent.
117         *
118         * @param intent The {@link Intent}.
119         * @param activities Activities to be sorted.
120         * @param historicalRecords Historical records.
121         */
122        // This cannot be done by a simple comparator since an Activity weight
123        // is computed from history. Note that Activity implements Comparable.
124        public void sort(Intent intent, List<ActivityResolveInfo> activities,
125                List<HistoricalRecord> historicalRecords);
126    }
127
128    /**
129     * Listener for choosing an activity.
130     */
131    public interface OnChooseActivityListener {
132
133        /**
134         * Called when an activity has been chosen. The client can decide whether
135         * an activity can be chosen and if so the caller of
136         * {@link ActivityChooserModel#chooseActivity(int)} will receive and {@link Intent}
137         * for launching it.
138         * <p>
139         * <strong>Note:</strong> Modifying the intent is not permitted and
140         *     any changes to the latter will be ignored.
141         * </p>
142         *
143         * @param host The listener's host model.
144         * @param intent The intent for launching the chosen activity.
145         * @return Whether the intent is handled and should not be delivered to clients.
146         *
147         * @see ActivityChooserModel#chooseActivity(int)
148         */
149        public boolean onChooseActivity(ActivityChooserModel host, Intent intent);
150    }
151
152    /**
153     * Flag for selecting debug mode.
154     */
155    private static final boolean DEBUG = false;
156
157    /**
158     * Tag used for logging.
159     */
160    private static final String LOG_TAG = ActivityChooserModel.class.getSimpleName();
161
162    /**
163     * The root tag in the history file.
164     */
165    private static final String TAG_HISTORICAL_RECORDS = "historical-records";
166
167    /**
168     * The tag for a record in the history file.
169     */
170    private static final String TAG_HISTORICAL_RECORD = "historical-record";
171
172    /**
173     * Attribute for the activity.
174     */
175    private static final String ATTRIBUTE_ACTIVITY = "activity";
176
177    /**
178     * Attribute for the choice time.
179     */
180    private static final String ATTRIBUTE_TIME = "time";
181
182    /**
183     * Attribute for the choice weight.
184     */
185    private static final String ATTRIBUTE_WEIGHT = "weight";
186
187    /**
188     * The default name of the choice history file.
189     */
190    public static final String DEFAULT_HISTORY_FILE_NAME =
191            "activity_choser_model_history.xml";
192
193    /**
194     * The default maximal length of the choice history.
195     */
196    public static final int DEFAULT_HISTORY_MAX_LENGTH = 50;
197
198    /**
199     * The amount with which to inflate a chosen activity when set as default.
200     */
201    private static final int DEFAULT_ACTIVITY_INFLATION = 5;
202
203    /**
204     * Default weight for a choice record.
205     */
206    private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = 1.0f;
207
208    /**
209     * The extension of the history file.
210     */
211    private static final String HISTORY_FILE_EXTENSION = ".xml";
212
213    /**
214     * An invalid item index.
215     */
216    private static final int INVALID_INDEX = -1;
217
218    /**
219     * Lock to guard the model registry.
220     */
221    private static final Object sRegistryLock = new Object();
222
223    /**
224     * This the registry for data models.
225     */
226    private static final Map<String, ActivityChooserModel> sDataModelRegistry =
227            new HashMap<String, ActivityChooserModel>();
228
229    /**
230     * Lock for synchronizing on this instance.
231     */
232    private final Object mInstanceLock = new Object();
233
234    /**
235     * List of activities that can handle the current intent.
236     */
237    private final List<ActivityResolveInfo> mActivities = new ArrayList<ActivityResolveInfo>();
238
239    /**
240     * List with historical choice records.
241     */
242    private final List<HistoricalRecord> mHistoricalRecords = new ArrayList<HistoricalRecord>();
243
244    /**
245     * Context for accessing resources.
246     */
247    private final Context mContext;
248
249    /**
250     * The name of the history file that backs this model.
251     */
252    private final String mHistoryFileName;
253
254    /**
255     * The intent for which a activity is being chosen.
256     */
257    private Intent mIntent;
258
259    /**
260     * The sorter for ordering activities based on intent and past choices.
261     */
262    private ActivitySorter mActivitySorter = new DefaultSorter();
263
264    /**
265     * The maximal length of the choice history.
266     */
267    private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH;
268
269    /**
270     * Flag whether choice history can be read. In general many clients can
271     * share the same data model and {@link #readHistoricalDataIfNeeded()} may be called
272     * by arbitrary of them any number of times. Therefore, this class guarantees
273     * that the very first read succeeds and subsequent reads can be performed
274     * only after a call to {@link #persistHistoricalDataIfNeeded()} followed by change
275     * of the share records.
276     */
277    private boolean mCanReadHistoricalData = true;
278
279    /**
280     * Flag whether the choice history was read. This is used to enforce that
281     * before calling {@link #persistHistoricalDataIfNeeded()} a call to
282     * {@link #persistHistoricalDataIfNeeded()} has been made. This aims to avoid a
283     * scenario in which a choice history file exits, it is not read yet and
284     * it is overwritten. Note that always all historical records are read in
285     * full and the file is rewritten. This is necessary since we need to
286     * purge old records that are outside of the sliding window of past choices.
287     */
288    private boolean mReadShareHistoryCalled = false;
289
290    /**
291     * Flag whether the choice records have changed. In general many clients can
292     * share the same data model and {@link #persistHistoricalDataIfNeeded()} may be called
293     * by arbitrary of them any number of times. Therefore, this class guarantees
294     * that choice history will be persisted only if it has changed.
295     */
296    private boolean mHistoricalRecordsChanged = true;
297
298    /**
299     * Flag whether to reload the activities for the current intent.
300     */
301    private boolean mReloadActivities = false;
302
303    /**
304     * Policy for controlling how the model handles chosen activities.
305     */
306    private OnChooseActivityListener mActivityChoserModelPolicy;
307
308    /**
309     * Gets the data model backed by the contents of the provided file with historical data.
310     * Note that only one data model is backed by a given file, thus multiple calls with
311     * the same file name will return the same model instance. If no such instance is present
312     * it is created.
313     * <p>
314     * <strong>Note:</strong> To use the default historical data file clients should explicitly
315     * pass as file name {@link #DEFAULT_HISTORY_FILE_NAME}. If no persistence of the choice
316     * history is desired clients should pass <code>null</code> for the file name. In such
317     * case a new model is returned for each invocation.
318     * </p>
319     *
320     * <p>
321     * <strong>Always use difference historical data files for semantically different actions.
322     * For example, sharing is different from importing.</strong>
323     * </p>
324     *
325     * @param context Context for loading resources.
326     * @param historyFileName File name with choice history, <code>null</code>
327     *        if the model should not be backed by a file. In this case the activities
328     *        will be ordered only by data from the current session.
329     *
330     * @return The model.
331     */
332    public static ActivityChooserModel get(Context context, String historyFileName) {
333        synchronized (sRegistryLock) {
334            ActivityChooserModel dataModel = sDataModelRegistry.get(historyFileName);
335            if (dataModel == null) {
336                dataModel = new ActivityChooserModel(context, historyFileName);
337                sDataModelRegistry.put(historyFileName, dataModel);
338            }
339            return dataModel;
340        }
341    }
342
343    /**
344     * Creates a new instance.
345     *
346     * @param context Context for loading resources.
347     * @param historyFileName The history XML file.
348     */
349    private ActivityChooserModel(Context context, String historyFileName) {
350        mContext = context.getApplicationContext();
351        if (!TextUtils.isEmpty(historyFileName)
352                && !historyFileName.endsWith(HISTORY_FILE_EXTENSION)) {
353            mHistoryFileName = historyFileName + HISTORY_FILE_EXTENSION;
354        } else {
355            mHistoryFileName = historyFileName;
356        }
357    }
358
359    /**
360     * Sets an intent for which to choose a activity.
361     * <p>
362     * <strong>Note:</strong> Clients must set only semantically similar
363     * intents for each data model.
364     * <p>
365     *
366     * @param intent The intent.
367     */
368    public void setIntent(Intent intent) {
369        synchronized (mInstanceLock) {
370            if (mIntent == intent) {
371                return;
372            }
373            mIntent = intent;
374            mReloadActivities = true;
375            ensureConsistentState();
376        }
377    }
378
379    /**
380     * Gets the intent for which a activity is being chosen.
381     *
382     * @return The intent.
383     */
384    public Intent getIntent() {
385        synchronized (mInstanceLock) {
386            return mIntent;
387        }
388    }
389
390    /**
391     * Gets the number of activities that can handle the intent.
392     *
393     * @return The activity count.
394     *
395     * @see #setIntent(Intent)
396     */
397    public int getActivityCount() {
398        synchronized (mInstanceLock) {
399            ensureConsistentState();
400            return mActivities.size();
401        }
402    }
403
404    /**
405     * Gets an activity at a given index.
406     *
407     * @return The activity.
408     *
409     * @see ActivityResolveInfo
410     * @see #setIntent(Intent)
411     */
412    public ResolveInfo getActivity(int index) {
413        synchronized (mInstanceLock) {
414            ensureConsistentState();
415            return mActivities.get(index).resolveInfo;
416        }
417    }
418
419    /**
420     * Gets the index of a the given activity.
421     *
422     * @param activity The activity index.
423     *
424     * @return The index if found, -1 otherwise.
425     */
426    public int getActivityIndex(ResolveInfo activity) {
427        synchronized (mInstanceLock) {
428            ensureConsistentState();
429            List<ActivityResolveInfo> activities = mActivities;
430            final int activityCount = activities.size();
431            for (int i = 0; i < activityCount; i++) {
432                ActivityResolveInfo currentActivity = activities.get(i);
433                if (currentActivity.resolveInfo == activity) {
434                    return i;
435                }
436            }
437            return INVALID_INDEX;
438        }
439    }
440
441    /**
442     * Chooses a activity to handle the current intent. This will result in
443     * adding a historical record for that action and construct intent with
444     * its component name set such that it can be immediately started by the
445     * client.
446     * <p>
447     * <strong>Note:</strong> By calling this method the client guarantees
448     * that the returned intent will be started. This intent is returned to
449     * the client solely to let additional customization before the start.
450     * </p>
451     *
452     * @return An {@link Intent} for launching the activity or null if the
453     *         policy has consumed the intent or there is not current intent
454     *         set via {@link #setIntent(Intent)}.
455     *
456     * @see HistoricalRecord
457     * @see OnChooseActivityListener
458     */
459    public Intent chooseActivity(int index) {
460        synchronized (mInstanceLock) {
461            if (mIntent == null) {
462                return null;
463            }
464
465            ensureConsistentState();
466
467            ActivityResolveInfo chosenActivity = mActivities.get(index);
468
469            ComponentName chosenName = new ComponentName(
470                    chosenActivity.resolveInfo.activityInfo.packageName,
471                    chosenActivity.resolveInfo.activityInfo.name);
472
473            Intent choiceIntent = new Intent(mIntent);
474            choiceIntent.setComponent(chosenName);
475
476            if (mActivityChoserModelPolicy != null) {
477                // Do not allow the policy to change the intent.
478                Intent choiceIntentCopy = new Intent(choiceIntent);
479                final boolean handled = mActivityChoserModelPolicy.onChooseActivity(this,
480                        choiceIntentCopy);
481                if (handled) {
482                    return null;
483                }
484            }
485
486            HistoricalRecord historicalRecord = new HistoricalRecord(chosenName,
487                    System.currentTimeMillis(), DEFAULT_HISTORICAL_RECORD_WEIGHT);
488            addHisoricalRecord(historicalRecord);
489
490            return choiceIntent;
491        }
492    }
493
494    /**
495     * Sets the listener for choosing an activity.
496     *
497     * @param listener The listener.
498     */
499    public void setOnChooseActivityListener(OnChooseActivityListener listener) {
500        synchronized (mInstanceLock) {
501            mActivityChoserModelPolicy = listener;
502        }
503    }
504
505    /**
506     * Gets the default activity, The default activity is defined as the one
507     * with highest rank i.e. the first one in the list of activities that can
508     * handle the intent.
509     *
510     * @return The default activity, <code>null</code> id not activities.
511     *
512     * @see #getActivity(int)
513     */
514    public ResolveInfo getDefaultActivity() {
515        synchronized (mInstanceLock) {
516            ensureConsistentState();
517            if (!mActivities.isEmpty()) {
518                return mActivities.get(0).resolveInfo;
519            }
520        }
521        return null;
522    }
523
524    /**
525     * Sets the default activity. The default activity is set by adding a
526     * historical record with weight high enough that this activity will
527     * become the highest ranked. Such a strategy guarantees that the default
528     * will eventually change if not used. Also the weight of the record for
529     * setting a default is inflated with a constant amount to guarantee that
530     * it will stay as default for awhile.
531     *
532     * @param index The index of the activity to set as default.
533     */
534    public void setDefaultActivity(int index) {
535        synchronized (mInstanceLock) {
536            ensureConsistentState();
537
538            ActivityResolveInfo newDefaultActivity = mActivities.get(index);
539            ActivityResolveInfo oldDefaultActivity = mActivities.get(0);
540
541            final float weight;
542            if (oldDefaultActivity != null) {
543                // Add a record with weight enough to boost the chosen at the top.
544                weight = oldDefaultActivity.weight - newDefaultActivity.weight
545                        + DEFAULT_ACTIVITY_INFLATION;
546            } else {
547                weight = DEFAULT_HISTORICAL_RECORD_WEIGHT;
548            }
549
550            ComponentName defaultName = new ComponentName(
551                    newDefaultActivity.resolveInfo.activityInfo.packageName,
552                    newDefaultActivity.resolveInfo.activityInfo.name);
553            HistoricalRecord historicalRecord = new HistoricalRecord(defaultName,
554                    System.currentTimeMillis(), weight);
555            addHisoricalRecord(historicalRecord);
556        }
557    }
558
559    /**
560     * Persists the history data to the backing file if the latter
561     * was provided. Calling this method before a call to {@link #readHistoricalDataIfNeeded()}
562     * throws an exception. Calling this method more than one without choosing an
563     * activity has not effect.
564     *
565     * @throws IllegalStateException If this method is called before a call to
566     *         {@link #readHistoricalDataIfNeeded()}.
567     */
568    private void persistHistoricalDataIfNeeded() {
569        if (!mReadShareHistoryCalled) {
570            throw new IllegalStateException("No preceding call to #readHistoricalData");
571        }
572        if (!mHistoricalRecordsChanged) {
573            return;
574        }
575        mHistoricalRecordsChanged = false;
576        if (!TextUtils.isEmpty(mHistoryFileName)) {
577            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
578                executePersistHistoryAsyncTaskSDK11();
579            } else {
580                executePersistHistoryAsyncTaskBase();
581            }
582        }
583    }
584
585    private void executePersistHistoryAsyncTaskBase() {
586        new PersistHistoryAsyncTask().execute(new ArrayList<HistoricalRecord>(mHistoricalRecords),
587                mHistoryFileName);
588    }
589
590    private void executePersistHistoryAsyncTaskSDK11() {
591        new PersistHistoryAsyncTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,
592                new ArrayList<HistoricalRecord>(mHistoricalRecords), mHistoryFileName);
593    }
594
595    /**
596     * Sets the sorter for ordering activities based on historical data and an intent.
597     *
598     * @param activitySorter The sorter.
599     *
600     * @see ActivitySorter
601     */
602    public void setActivitySorter(ActivitySorter activitySorter) {
603        synchronized (mInstanceLock) {
604            if (mActivitySorter == activitySorter) {
605                return;
606            }
607            mActivitySorter = activitySorter;
608            if (sortActivitiesIfNeeded()) {
609                notifyChanged();
610            }
611        }
612    }
613
614    /**
615     * Sets the maximal size of the historical data. Defaults to
616     * {@link #DEFAULT_HISTORY_MAX_LENGTH}
617     * <p>
618     *   <strong>Note:</strong> Setting this property will immediately
619     *   enforce the specified max history size by dropping enough old
620     *   historical records to enforce the desired size. Thus, any
621     *   records that exceed the history size will be discarded and
622     *   irreversibly lost.
623     * </p>
624     *
625     * @param historyMaxSize The max history size.
626     */
627    public void setHistoryMaxSize(int historyMaxSize) {
628        synchronized (mInstanceLock) {
629            if (mHistoryMaxSize == historyMaxSize) {
630                return;
631            }
632            mHistoryMaxSize = historyMaxSize;
633            pruneExcessiveHistoricalRecordsIfNeeded();
634            if (sortActivitiesIfNeeded()) {
635                notifyChanged();
636            }
637        }
638    }
639
640    /**
641     * Gets the history max size.
642     *
643     * @return The history max size.
644     */
645    public int getHistoryMaxSize() {
646        synchronized (mInstanceLock) {
647            return mHistoryMaxSize;
648        }
649    }
650
651    /**
652     * Gets the history size.
653     *
654     * @return The history size.
655     */
656    public int getHistorySize() {
657        synchronized (mInstanceLock) {
658            ensureConsistentState();
659            return mHistoricalRecords.size();
660        }
661    }
662
663    /**
664     * Ensures the model is in a consistent state which is the
665     * activities for the current intent have been loaded, the
666     * most recent history has been read, and the activities
667     * are sorted.
668     */
669    private void ensureConsistentState() {
670        boolean stateChanged = loadActivitiesIfNeeded();
671        stateChanged |= readHistoricalDataIfNeeded();
672        pruneExcessiveHistoricalRecordsIfNeeded();
673        if (stateChanged) {
674            sortActivitiesIfNeeded();
675            notifyChanged();
676        }
677    }
678
679    /**
680     * Sorts the activities if necessary which is if there is a
681     * sorter, there are some activities to sort, and there is some
682     * historical data.
683     *
684     * @return Whether sorting was performed.
685     */
686    private boolean sortActivitiesIfNeeded() {
687        if (mActivitySorter != null && mIntent != null
688                && !mActivities.isEmpty() && !mHistoricalRecords.isEmpty()) {
689            mActivitySorter.sort(mIntent, mActivities,
690                    Collections.unmodifiableList(mHistoricalRecords));
691            return true;
692        }
693        return false;
694    }
695
696    /**
697     * Loads the activities for the current intent if needed which is
698     * if they are not already loaded for the current intent.
699     *
700     * @return Whether loading was performed.
701     */
702    private boolean loadActivitiesIfNeeded() {
703        if (mReloadActivities && mIntent != null) {
704            mReloadActivities = false;
705            mActivities.clear();
706            List<ResolveInfo> resolveInfos = mContext.getPackageManager()
707                    .queryIntentActivities(mIntent, 0);
708            final int resolveInfoCount = resolveInfos.size();
709            for (int i = 0; i < resolveInfoCount; i++) {
710                ResolveInfo resolveInfo = resolveInfos.get(i);
711                mActivities.add(new ActivityResolveInfo(resolveInfo));
712            }
713            return true;
714        }
715        return false;
716    }
717
718    /**
719     * Reads the historical data if necessary which is it has
720     * changed, there is a history file, and there is not persist
721     * in progress.
722     *
723     * @return Whether reading was performed.
724     */
725    private boolean readHistoricalDataIfNeeded() {
726        if (mCanReadHistoricalData && mHistoricalRecordsChanged &&
727                !TextUtils.isEmpty(mHistoryFileName)) {
728            mCanReadHistoricalData = false;
729            mReadShareHistoryCalled = true;
730            readHistoricalDataImpl();
731            return true;
732        }
733        return false;
734    }
735
736    /**
737     * Adds a historical record.
738     *
739     * @param historicalRecord The record to add.
740     * @return True if the record was added.
741     */
742    private boolean addHisoricalRecord(HistoricalRecord historicalRecord) {
743        final boolean added = mHistoricalRecords.add(historicalRecord);
744        if (added) {
745            mHistoricalRecordsChanged = true;
746            pruneExcessiveHistoricalRecordsIfNeeded();
747            persistHistoricalDataIfNeeded();
748            sortActivitiesIfNeeded();
749            notifyChanged();
750        }
751        return added;
752    }
753
754    /**
755     * Prunes older excessive records to guarantee maxHistorySize.
756     */
757    private void pruneExcessiveHistoricalRecordsIfNeeded() {
758        final int pruneCount = mHistoricalRecords.size() - mHistoryMaxSize;
759        if (pruneCount <= 0) {
760            return;
761        }
762        mHistoricalRecordsChanged = true;
763        for (int i = 0; i < pruneCount; i++) {
764            HistoricalRecord prunedRecord = mHistoricalRecords.remove(0);
765            if (DEBUG) {
766                Log.i(LOG_TAG, "Pruned: " + prunedRecord);
767            }
768        }
769    }
770
771    /**
772     * Represents a record in the history.
773     */
774    public final static class HistoricalRecord {
775
776        /**
777         * The activity name.
778         */
779        public final ComponentName activity;
780
781        /**
782         * The choice time.
783         */
784        public final long time;
785
786        /**
787         * The record weight.
788         */
789        public final float weight;
790
791        /**
792         * Creates a new instance.
793         *
794         * @param activityName The activity component name flattened to string.
795         * @param time The time the activity was chosen.
796         * @param weight The weight of the record.
797         */
798        public HistoricalRecord(String activityName, long time, float weight) {
799            this(ComponentName.unflattenFromString(activityName), time, weight);
800        }
801
802        /**
803         * Creates a new instance.
804         *
805         * @param activityName The activity name.
806         * @param time The time the activity was chosen.
807         * @param weight The weight of the record.
808         */
809        public HistoricalRecord(ComponentName activityName, long time, float weight) {
810            this.activity = activityName;
811            this.time = time;
812            this.weight = weight;
813        }
814
815        @Override
816        public int hashCode() {
817            final int prime = 31;
818            int result = 1;
819            result = prime * result + ((activity == null) ? 0 : activity.hashCode());
820            result = prime * result + (int) (time ^ (time >>> 32));
821            result = prime * result + Float.floatToIntBits(weight);
822            return result;
823        }
824
825        @Override
826        public boolean equals(Object obj) {
827            if (this == obj) {
828                return true;
829            }
830            if (obj == null) {
831                return false;
832            }
833            if (getClass() != obj.getClass()) {
834                return false;
835            }
836            HistoricalRecord other = (HistoricalRecord) obj;
837            if (activity == null) {
838                if (other.activity != null) {
839                    return false;
840                }
841            } else if (!activity.equals(other.activity)) {
842                return false;
843            }
844            if (time != other.time) {
845                return false;
846            }
847            if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
848                return false;
849            }
850            return true;
851        }
852
853        @Override
854        public String toString() {
855            StringBuilder builder = new StringBuilder();
856            builder.append("[");
857            builder.append("; activity:").append(activity);
858            builder.append("; time:").append(time);
859            builder.append("; weight:").append(new BigDecimal(weight));
860            builder.append("]");
861            return builder.toString();
862        }
863    }
864
865    /**
866     * Represents an activity.
867     */
868    public final class ActivityResolveInfo implements Comparable<ActivityResolveInfo> {
869
870        /**
871         * The {@link ResolveInfo} of the activity.
872         */
873        public final ResolveInfo resolveInfo;
874
875        /**
876         * Weight of the activity. Useful for sorting.
877         */
878        public float weight;
879
880        /**
881         * Creates a new instance.
882         *
883         * @param resolveInfo activity {@link ResolveInfo}.
884         */
885        public ActivityResolveInfo(ResolveInfo resolveInfo) {
886            this.resolveInfo = resolveInfo;
887        }
888
889        @Override
890        public int hashCode() {
891            return 31 + Float.floatToIntBits(weight);
892        }
893
894        @Override
895        public boolean equals(Object obj) {
896            if (this == obj) {
897                return true;
898            }
899            if (obj == null) {
900                return false;
901            }
902            if (getClass() != obj.getClass()) {
903                return false;
904            }
905            ActivityResolveInfo other = (ActivityResolveInfo) obj;
906            if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
907                return false;
908            }
909            return true;
910        }
911
912        public int compareTo(ActivityResolveInfo another) {
913            return  Float.floatToIntBits(another.weight) - Float.floatToIntBits(weight);
914        }
915
916        @Override
917        public String toString() {
918            StringBuilder builder = new StringBuilder();
919            builder.append("[");
920            builder.append("resolveInfo:").append(resolveInfo.toString());
921            builder.append("; weight:").append(new BigDecimal(weight));
922            builder.append("]");
923            return builder.toString();
924        }
925    }
926
927    /**
928     * Default activity sorter implementation.
929     */
930    private final class DefaultSorter implements ActivitySorter {
931        private static final float WEIGHT_DECAY_COEFFICIENT = 0.95f;
932
933        private final Map<String, ActivityResolveInfo> mPackageNameToActivityMap =
934                new HashMap<String, ActivityResolveInfo>();
935
936        public void sort(Intent intent, List<ActivityResolveInfo> activities,
937                List<HistoricalRecord> historicalRecords) {
938            Map<String, ActivityResolveInfo> packageNameToActivityMap =
939                    mPackageNameToActivityMap;
940            packageNameToActivityMap.clear();
941
942            final int activityCount = activities.size();
943            for (int i = 0; i < activityCount; i++) {
944                ActivityResolveInfo activity = activities.get(i);
945                activity.weight = 0.0f;
946                String packageName = activity.resolveInfo.activityInfo.packageName;
947                packageNameToActivityMap.put(packageName, activity);
948            }
949
950            final int lastShareIndex = historicalRecords.size() - 1;
951            float nextRecordWeight = 1;
952            for (int i = lastShareIndex; i >= 0; i--) {
953                HistoricalRecord historicalRecord = historicalRecords.get(i);
954                String packageName = historicalRecord.activity.getPackageName();
955                ActivityResolveInfo activity = packageNameToActivityMap.get(packageName);
956                if (activity != null) {
957                    activity.weight += historicalRecord.weight * nextRecordWeight;
958                    nextRecordWeight = nextRecordWeight * WEIGHT_DECAY_COEFFICIENT;
959                }
960            }
961
962            Collections.sort(activities);
963
964            if (DEBUG) {
965                for (int i = 0; i < activityCount; i++) {
966                    Log.i(LOG_TAG, "Sorted: " + activities.get(i));
967                }
968            }
969        }
970    }
971
972    /**
973     * Command for reading the historical records from a file off the UI thread.
974     */
975    private void readHistoricalDataImpl() {
976        FileInputStream fis = null;
977        try {
978            fis = mContext.openFileInput(mHistoryFileName);
979        } catch (FileNotFoundException fnfe) {
980            if (DEBUG) {
981                Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName);
982            }
983            return;
984        }
985        try {
986            XmlPullParser parser = Xml.newPullParser();
987            parser.setInput(fis, null);
988
989            int type = XmlPullParser.START_DOCUMENT;
990            while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
991                type = parser.next();
992            }
993
994            if (!TAG_HISTORICAL_RECORDS.equals(parser.getName())) {
995                throw new XmlPullParserException("Share records file does not start with "
996                        + TAG_HISTORICAL_RECORDS + " tag.");
997            }
998
999            List<HistoricalRecord> historicalRecords = mHistoricalRecords;
1000            historicalRecords.clear();
1001
1002            while (true) {
1003                type = parser.next();
1004                if (type == XmlPullParser.END_DOCUMENT) {
1005                    break;
1006                }
1007                if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1008                    continue;
1009                }
1010                String nodeName = parser.getName();
1011                if (!TAG_HISTORICAL_RECORD.equals(nodeName)) {
1012                    throw new XmlPullParserException("Share records file not well-formed.");
1013                }
1014
1015                String activity = parser.getAttributeValue(null, ATTRIBUTE_ACTIVITY);
1016                final long time =
1017                        Long.parseLong(parser.getAttributeValue(null, ATTRIBUTE_TIME));
1018                final float weight =
1019                        Float.parseFloat(parser.getAttributeValue(null, ATTRIBUTE_WEIGHT));
1020                HistoricalRecord readRecord = new HistoricalRecord(activity, time, weight);
1021                historicalRecords.add(readRecord);
1022
1023                if (DEBUG) {
1024                    Log.i(LOG_TAG, "Read " + readRecord.toString());
1025                }
1026            }
1027
1028            if (DEBUG) {
1029                Log.i(LOG_TAG, "Read " + historicalRecords.size() + " historical records.");
1030            }
1031        } catch (XmlPullParserException xppe) {
1032            Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, xppe);
1033        } catch (IOException ioe) {
1034            Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, ioe);
1035        } finally {
1036            if (fis != null) {
1037                try {
1038                    fis.close();
1039                } catch (IOException ioe) {
1040                    /* ignore */
1041                }
1042            }
1043        }
1044    }
1045
1046    /**
1047     * Command for persisting the historical records to a file off the UI thread.
1048     */
1049    private final class PersistHistoryAsyncTask extends AsyncTask<Object, Void, Void> {
1050
1051        @Override
1052        @SuppressWarnings("unchecked")
1053        public Void doInBackground(Object... args) {
1054            List<HistoricalRecord> historicalRecords = (List<HistoricalRecord>) args[0];
1055            String hostoryFileName = (String) args[1];
1056
1057            FileOutputStream fos = null;
1058
1059            try {
1060                fos = mContext.openFileOutput(hostoryFileName, Context.MODE_PRIVATE);
1061            } catch (FileNotFoundException fnfe) {
1062                Log.e(LOG_TAG, "Error writing historical recrod file: " + hostoryFileName, fnfe);
1063                return null;
1064            }
1065
1066            XmlSerializer serializer = Xml.newSerializer();
1067
1068            try {
1069                serializer.setOutput(fos, null);
1070                serializer.startDocument("UTF-8", true);
1071                serializer.startTag(null, TAG_HISTORICAL_RECORDS);
1072
1073                final int recordCount = historicalRecords.size();
1074                for (int i = 0; i < recordCount; i++) {
1075                    HistoricalRecord record = historicalRecords.remove(0);
1076                    serializer.startTag(null, TAG_HISTORICAL_RECORD);
1077                    serializer.attribute(null, ATTRIBUTE_ACTIVITY,
1078                            record.activity.flattenToString());
1079                    serializer.attribute(null, ATTRIBUTE_TIME, String.valueOf(record.time));
1080                    serializer.attribute(null, ATTRIBUTE_WEIGHT, String.valueOf(record.weight));
1081                    serializer.endTag(null, TAG_HISTORICAL_RECORD);
1082                    if (DEBUG) {
1083                        Log.i(LOG_TAG, "Wrote " + record.toString());
1084                    }
1085                }
1086
1087                serializer.endTag(null, TAG_HISTORICAL_RECORDS);
1088                serializer.endDocument();
1089
1090                if (DEBUG) {
1091                    Log.i(LOG_TAG, "Wrote " + recordCount + " historical records.");
1092                }
1093            } catch (IllegalArgumentException iae) {
1094                Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, iae);
1095            } catch (IllegalStateException ise) {
1096                Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ise);
1097            } catch (IOException ioe) {
1098                Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ioe);
1099            } finally {
1100                mCanReadHistoricalData = true;
1101                if (fos != null) {
1102                    try {
1103                        fos.close();
1104                    } catch (IOException e) {
1105                        /* ignore */
1106                    }
1107                }
1108            }
1109            return null;
1110        }
1111    }
1112}