Home | History | Annotate | Download | only in widget
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.widget;
     18 
     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.AsyncTask;
     25 import android.text.TextUtils;
     26 import android.util.Log;
     27 import android.util.Xml;
     28 
     29 import com.android.internal.content.PackageMonitor;
     30 
     31 import org.xmlpull.v1.XmlPullParser;
     32 import org.xmlpull.v1.XmlPullParserException;
     33 import org.xmlpull.v1.XmlSerializer;
     34 
     35 import java.io.FileInputStream;
     36 import java.io.FileNotFoundException;
     37 import java.io.FileOutputStream;
     38 import java.io.IOException;
     39 import java.math.BigDecimal;
     40 import java.util.ArrayList;
     41 import java.util.Collections;
     42 import java.util.HashMap;
     43 import java.util.List;
     44 import java.util.Map;
     45 
     46 /**
     47  * <p>
     48  * This class represents a data model for choosing a component for handing a
     49  * given {@link Intent}. The model is responsible for querying the system for
     50  * activities that can handle the given intent and order found activities
     51  * based on historical data of previous choices. The historical data is stored
     52  * in an application private file. If a client does not want to have persistent
     53  * choice history the file can be omitted, thus the activities will be ordered
     54  * based on historical usage for the current session.
     55  * <p>
     56  * </p>
     57  * For each backing history file there is a singleton instance of this class. Thus,
     58  * several clients that specify the same history file will share the same model. Note
     59  * that if multiple clients are sharing the same model they should implement semantically
     60  * equivalent functionality since setting the model intent will change the found
     61  * activities and they may be inconsistent with the functionality of some of the clients.
     62  * For example, choosing a share activity can be implemented by a single backing
     63  * model and two different views for performing the selection. If however, one of the
     64  * views is used for sharing but the other for importing, for example, then each
     65  * view should be backed by a separate model.
     66  * </p>
     67  * <p>
     68  * The way clients interact with this class is as follows:
     69  * </p>
     70  * <p>
     71  * <pre>
     72  * <code>
     73  *  // Get a model and set it to a couple of clients with semantically similar function.
     74  *  ActivityChooserModel dataModel =
     75  *      ActivityChooserModel.get(context, "task_specific_history_file_name.xml");
     76  *
     77  *  ActivityChooserModelClient modelClient1 = getActivityChooserModelClient1();
     78  *  modelClient1.setActivityChooserModel(dataModel);
     79  *
     80  *  ActivityChooserModelClient modelClient2 = getActivityChooserModelClient2();
     81  *  modelClient2.setActivityChooserModel(dataModel);
     82  *
     83  *  // Set an intent to choose a an activity for.
     84  *  dataModel.setIntent(intent);
     85  * <pre>
     86  * <code>
     87  * </p>
     88  * <p>
     89  * <strong>Note:</strong> This class is thread safe.
     90  * </p>
     91  *
     92  * @hide
     93  */
     94 public class ActivityChooserModel extends DataSetObservable {
     95 
     96     /**
     97      * Client that utilizes an {@link ActivityChooserModel}.
     98      */
     99     public interface ActivityChooserModelClient {
    100 
    101         /**
    102          * Sets the {@link ActivityChooserModel}.
    103          *
    104          * @param dataModel The model.
    105          */
    106         public void setActivityChooserModel(ActivityChooserModel dataModel);
    107     }
    108 
    109     /**
    110      * Defines a sorter that is responsible for sorting the activities
    111      * based on the provided historical choices and an intent.
    112      */
    113     public interface ActivitySorter {
    114 
    115         /**
    116          * Sorts the <code>activities</code> in descending order of relevance
    117          * based on previous history and an intent.
    118          *
    119          * @param intent The {@link Intent}.
    120          * @param activities Activities to be sorted.
    121          * @param historicalRecords Historical records.
    122          */
    123         // This cannot be done by a simple comparator since an Activity weight
    124         // is computed from history. Note that Activity implements Comparable.
    125         public void sort(Intent intent, List<ActivityResolveInfo> activities,
    126                 List<HistoricalRecord> historicalRecords);
    127     }
    128 
    129     /**
    130      * Listener for choosing an activity.
    131      */
    132     public interface OnChooseActivityListener {
    133 
    134         /**
    135          * Called when an activity has been chosen. The client can decide whether
    136          * an activity can be chosen and if so the caller of
    137          * {@link ActivityChooserModel#chooseActivity(int)} will receive and {@link Intent}
    138          * for launching it.
    139          * <p>
    140          * <strong>Note:</strong> Modifying the intent is not permitted and
    141          *     any changes to the latter will be ignored.
    142          * </p>
    143          *
    144          * @param host The listener's host model.
    145          * @param intent The intent for launching the chosen activity.
    146          * @return Whether the intent is handled and should not be delivered to clients.
    147          *
    148          * @see ActivityChooserModel#chooseActivity(int)
    149          */
    150         public boolean onChooseActivity(ActivityChooserModel host, Intent intent);
    151     }
    152 
    153     /**
    154      * Flag for selecting debug mode.
    155      */
    156     private static final boolean DEBUG = false;
    157 
    158     /**
    159      * Tag used for logging.
    160      */
    161     private static final String LOG_TAG = ActivityChooserModel.class.getSimpleName();
    162 
    163     /**
    164      * The root tag in the history file.
    165      */
    166     private static final String TAG_HISTORICAL_RECORDS = "historical-records";
    167 
    168     /**
    169      * The tag for a record in the history file.
    170      */
    171     private static final String TAG_HISTORICAL_RECORD = "historical-record";
    172 
    173     /**
    174      * Attribute for the activity.
    175      */
    176     private static final String ATTRIBUTE_ACTIVITY = "activity";
    177 
    178     /**
    179      * Attribute for the choice time.
    180      */
    181     private static final String ATTRIBUTE_TIME = "time";
    182 
    183     /**
    184      * Attribute for the choice weight.
    185      */
    186     private static final String ATTRIBUTE_WEIGHT = "weight";
    187 
    188     /**
    189      * The default name of the choice history file.
    190      */
    191     public static final String DEFAULT_HISTORY_FILE_NAME =
    192         "activity_choser_model_history.xml";
    193 
    194     /**
    195      * The default maximal length of the choice history.
    196      */
    197     public static final int DEFAULT_HISTORY_MAX_LENGTH = 50;
    198 
    199     /**
    200      * The amount with which to inflate a chosen activity when set as default.
    201      */
    202     private static final int DEFAULT_ACTIVITY_INFLATION = 5;
    203 
    204     /**
    205      * Default weight for a choice record.
    206      */
    207     private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = 1.0f;
    208 
    209     /**
    210      * The extension of the history file.
    211      */
    212     private static final String HISTORY_FILE_EXTENSION = ".xml";
    213 
    214     /**
    215      * An invalid item index.
    216      */
    217     private static final int INVALID_INDEX = -1;
    218 
    219     /**
    220      * Lock to guard the model registry.
    221      */
    222     private static final Object sRegistryLock = new Object();
    223 
    224     /**
    225      * This the registry for data models.
    226      */
    227     private static final Map<String, ActivityChooserModel> sDataModelRegistry =
    228         new HashMap<String, ActivityChooserModel>();
    229 
    230     /**
    231      * Lock for synchronizing on this instance.
    232      */
    233     private final Object mInstanceLock = new Object();
    234 
    235     /**
    236      * List of activities that can handle the current intent.
    237      */
    238     private final List<ActivityResolveInfo> mActivities = new ArrayList<ActivityResolveInfo>();
    239 
    240     /**
    241      * List with historical choice records.
    242      */
    243     private final List<HistoricalRecord> mHistoricalRecords = new ArrayList<HistoricalRecord>();
    244 
    245     /**
    246      * Monitor for added and removed packages.
    247      */
    248     private final PackageMonitor mPackageMonitor = new DataModelPackageMonitor();
    249 
    250     /**
    251      * Context for accessing resources.
    252      */
    253     private final Context mContext;
    254 
    255     /**
    256      * The name of the history file that backs this model.
    257      */
    258     private final String mHistoryFileName;
    259 
    260     /**
    261      * The intent for which a activity is being chosen.
    262      */
    263     private Intent mIntent;
    264 
    265     /**
    266      * The sorter for ordering activities based on intent and past choices.
    267      */
    268     private ActivitySorter mActivitySorter = new DefaultSorter();
    269 
    270     /**
    271      * The maximal length of the choice history.
    272      */
    273     private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH;
    274 
    275     /**
    276      * Flag whether choice history can be read. In general many clients can
    277      * share the same data model and {@link #readHistoricalDataIfNeeded()} may be called
    278      * by arbitrary of them any number of times. Therefore, this class guarantees
    279      * that the very first read succeeds and subsequent reads can be performed
    280      * only after a call to {@link #persistHistoricalDataIfNeeded()} followed by change
    281      * of the share records.
    282      */
    283     private boolean mCanReadHistoricalData = true;
    284 
    285     /**
    286      * Flag whether the choice history was read. This is used to enforce that
    287      * before calling {@link #persistHistoricalDataIfNeeded()} a call to
    288      * {@link #persistHistoricalDataIfNeeded()} has been made. This aims to avoid a
    289      * scenario in which a choice history file exits, it is not read yet and
    290      * it is overwritten. Note that always all historical records are read in
    291      * full and the file is rewritten. This is necessary since we need to
    292      * purge old records that are outside of the sliding window of past choices.
    293      */
    294     private boolean mReadShareHistoryCalled = false;
    295 
    296     /**
    297      * Flag whether the choice records have changed. In general many clients can
    298      * share the same data model and {@link #persistHistoricalDataIfNeeded()} may be called
    299      * by arbitrary of them any number of times. Therefore, this class guarantees
    300      * that choice history will be persisted only if it has changed.
    301      */
    302     private boolean mHistoricalRecordsChanged = true;
    303 
    304     /**
    305      * Flag whether to reload the activities for the current intent.
    306      */
    307     private boolean mReloadActivities = false;
    308 
    309     /**
    310      * Policy for controlling how the model handles chosen activities.
    311      */
    312     private OnChooseActivityListener mActivityChoserModelPolicy;
    313 
    314     /**
    315      * Gets the data model backed by the contents of the provided file with historical data.
    316      * Note that only one data model is backed by a given file, thus multiple calls with
    317      * the same file name will return the same model instance. If no such instance is present
    318      * it is created.
    319      * <p>
    320      * <strong>Note:</strong> To use the default historical data file clients should explicitly
    321      * pass as file name {@link #DEFAULT_HISTORY_FILE_NAME}. If no persistence of the choice
    322      * history is desired clients should pass <code>null</code> for the file name. In such
    323      * case a new model is returned for each invocation.
    324      * </p>
    325      *
    326      * <p>
    327      * <strong>Always use difference historical data files for semantically different actions.
    328      * For example, sharing is different from importing.</strong>
    329      * </p>
    330      *
    331      * @param context Context for loading resources.
    332      * @param historyFileName File name with choice history, <code>null</code>
    333      *        if the model should not be backed by a file. In this case the activities
    334      *        will be ordered only by data from the current session.
    335      *
    336      * @return The model.
    337      */
    338     public static ActivityChooserModel get(Context context, String historyFileName) {
    339         synchronized (sRegistryLock) {
    340             ActivityChooserModel dataModel = sDataModelRegistry.get(historyFileName);
    341             if (dataModel == null) {
    342                 dataModel = new ActivityChooserModel(context, historyFileName);
    343                 sDataModelRegistry.put(historyFileName, dataModel);
    344             }
    345             return dataModel;
    346         }
    347     }
    348 
    349     /**
    350      * Creates a new instance.
    351      *
    352      * @param context Context for loading resources.
    353      * @param historyFileName The history XML file.
    354      */
    355     private ActivityChooserModel(Context context, String historyFileName) {
    356         mContext = context.getApplicationContext();
    357         if (!TextUtils.isEmpty(historyFileName)
    358                 && !historyFileName.endsWith(HISTORY_FILE_EXTENSION)) {
    359             mHistoryFileName = historyFileName + HISTORY_FILE_EXTENSION;
    360         } else {
    361             mHistoryFileName = historyFileName;
    362         }
    363         mPackageMonitor.register(mContext, null, true);
    364     }
    365 
    366     /**
    367      * Sets an intent for which to choose a activity.
    368      * <p>
    369      * <strong>Note:</strong> Clients must set only semantically similar
    370      * intents for each data model.
    371      * <p>
    372      *
    373      * @param intent The intent.
    374      */
    375     public void setIntent(Intent intent) {
    376         synchronized (mInstanceLock) {
    377             if (mIntent == intent) {
    378                 return;
    379             }
    380             mIntent = intent;
    381             mReloadActivities = true;
    382             ensureConsistentState();
    383         }
    384     }
    385 
    386     /**
    387      * Gets the intent for which a activity is being chosen.
    388      *
    389      * @return The intent.
    390      */
    391     public Intent getIntent() {
    392         synchronized (mInstanceLock) {
    393             return mIntent;
    394         }
    395     }
    396 
    397     /**
    398      * Gets the number of activities that can handle the intent.
    399      *
    400      * @return The activity count.
    401      *
    402      * @see #setIntent(Intent)
    403      */
    404     public int getActivityCount() {
    405         synchronized (mInstanceLock) {
    406             ensureConsistentState();
    407             return mActivities.size();
    408         }
    409     }
    410 
    411     /**
    412      * Gets an activity at a given index.
    413      *
    414      * @return The activity.
    415      *
    416      * @see ActivityResolveInfo
    417      * @see #setIntent(Intent)
    418      */
    419     public ResolveInfo getActivity(int index) {
    420         synchronized (mInstanceLock) {
    421             ensureConsistentState();
    422             return mActivities.get(index).resolveInfo;
    423         }
    424     }
    425 
    426     /**
    427      * Gets the index of a the given activity.
    428      *
    429      * @param activity The activity index.
    430      *
    431      * @return The index if found, -1 otherwise.
    432      */
    433     public int getActivityIndex(ResolveInfo activity) {
    434         synchronized (mInstanceLock) {
    435             ensureConsistentState();
    436             List<ActivityResolveInfo> activities = mActivities;
    437             final int activityCount = activities.size();
    438             for (int i = 0; i < activityCount; i++) {
    439                 ActivityResolveInfo currentActivity = activities.get(i);
    440                 if (currentActivity.resolveInfo == activity) {
    441                     return i;
    442                 }
    443             }
    444             return INVALID_INDEX;
    445         }
    446     }
    447 
    448     /**
    449      * Chooses a activity to handle the current intent. This will result in
    450      * adding a historical record for that action and construct intent with
    451      * its component name set such that it can be immediately started by the
    452      * client.
    453      * <p>
    454      * <strong>Note:</strong> By calling this method the client guarantees
    455      * that the returned intent will be started. This intent is returned to
    456      * the client solely to let additional customization before the start.
    457      * </p>
    458      *
    459      * @return An {@link Intent} for launching the activity or null if the
    460      *         policy has consumed the intent or there is not current intent
    461      *         set via {@link #setIntent(Intent)}.
    462      *
    463      * @see HistoricalRecord
    464      * @see OnChooseActivityListener
    465      */
    466     public Intent chooseActivity(int index) {
    467         synchronized (mInstanceLock) {
    468             if (mIntent == null) {
    469                 return null;
    470             }
    471 
    472             ensureConsistentState();
    473 
    474             ActivityResolveInfo chosenActivity = mActivities.get(index);
    475 
    476             ComponentName chosenName = new ComponentName(
    477                     chosenActivity.resolveInfo.activityInfo.packageName,
    478                     chosenActivity.resolveInfo.activityInfo.name);
    479 
    480             Intent choiceIntent = new Intent(mIntent);
    481             choiceIntent.setComponent(chosenName);
    482 
    483             if (mActivityChoserModelPolicy != null) {
    484                 // Do not allow the policy to change the intent.
    485                 Intent choiceIntentCopy = new Intent(choiceIntent);
    486                 final boolean handled = mActivityChoserModelPolicy.onChooseActivity(this,
    487                         choiceIntentCopy);
    488                 if (handled) {
    489                     return null;
    490                 }
    491             }
    492 
    493             HistoricalRecord historicalRecord = new HistoricalRecord(chosenName,
    494                     System.currentTimeMillis(), DEFAULT_HISTORICAL_RECORD_WEIGHT);
    495             addHisoricalRecord(historicalRecord);
    496 
    497             return choiceIntent;
    498         }
    499     }
    500 
    501     /**
    502      * Sets the listener for choosing an activity.
    503      *
    504      * @param listener The listener.
    505      */
    506     public void setOnChooseActivityListener(OnChooseActivityListener listener) {
    507         synchronized (mInstanceLock) {
    508             mActivityChoserModelPolicy = listener;
    509         }
    510     }
    511 
    512     /**
    513      * Gets the default activity, The default activity is defined as the one
    514      * with highest rank i.e. the first one in the list of activities that can
    515      * handle the intent.
    516      *
    517      * @return The default activity, <code>null</code> id not activities.
    518      *
    519      * @see #getActivity(int)
    520      */
    521     public ResolveInfo getDefaultActivity() {
    522         synchronized (mInstanceLock) {
    523             ensureConsistentState();
    524             if (!mActivities.isEmpty()) {
    525                 return mActivities.get(0).resolveInfo;
    526             }
    527         }
    528         return null;
    529     }
    530 
    531     /**
    532      * Sets the default activity. The default activity is set by adding a
    533      * historical record with weight high enough that this activity will
    534      * become the highest ranked. Such a strategy guarantees that the default
    535      * will eventually change if not used. Also the weight of the record for
    536      * setting a default is inflated with a constant amount to guarantee that
    537      * it will stay as default for awhile.
    538      *
    539      * @param index The index of the activity to set as default.
    540      */
    541     public void setDefaultActivity(int index) {
    542         synchronized (mInstanceLock) {
    543             ensureConsistentState();
    544 
    545             ActivityResolveInfo newDefaultActivity = mActivities.get(index);
    546             ActivityResolveInfo oldDefaultActivity = mActivities.get(0);
    547 
    548             final float weight;
    549             if (oldDefaultActivity != null) {
    550                 // Add a record with weight enough to boost the chosen at the top.
    551                 weight = oldDefaultActivity.weight - newDefaultActivity.weight
    552                     + DEFAULT_ACTIVITY_INFLATION;
    553             } else {
    554                 weight = DEFAULT_HISTORICAL_RECORD_WEIGHT;
    555             }
    556 
    557             ComponentName defaultName = new ComponentName(
    558                     newDefaultActivity.resolveInfo.activityInfo.packageName,
    559                     newDefaultActivity.resolveInfo.activityInfo.name);
    560             HistoricalRecord historicalRecord = new HistoricalRecord(defaultName,
    561                     System.currentTimeMillis(), weight);
    562             addHisoricalRecord(historicalRecord);
    563         }
    564     }
    565 
    566     /**
    567      * Persists the history data to the backing file if the latter
    568      * was provided. Calling this method before a call to {@link #readHistoricalDataIfNeeded()}
    569      * throws an exception. Calling this method more than one without choosing an
    570      * activity has not effect.
    571      *
    572      * @throws IllegalStateException If this method is called before a call to
    573      *         {@link #readHistoricalDataIfNeeded()}.
    574      */
    575     private void persistHistoricalDataIfNeeded() {
    576         if (!mReadShareHistoryCalled) {
    577             throw new IllegalStateException("No preceding call to #readHistoricalData");
    578         }
    579         if (!mHistoricalRecordsChanged) {
    580             return;
    581         }
    582         mHistoricalRecordsChanged = false;
    583         if (!TextUtils.isEmpty(mHistoryFileName)) {
    584             new PersistHistoryAsyncTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,
    585                     new ArrayList<HistoricalRecord>(mHistoricalRecords), mHistoryFileName);
    586         }
    587     }
    588 
    589     /**
    590      * Sets the sorter for ordering activities based on historical data and an intent.
    591      *
    592      * @param activitySorter The sorter.
    593      *
    594      * @see ActivitySorter
    595      */
    596     public void setActivitySorter(ActivitySorter activitySorter) {
    597         synchronized (mInstanceLock) {
    598             if (mActivitySorter == activitySorter) {
    599                 return;
    600             }
    601             mActivitySorter = activitySorter;
    602             if (sortActivitiesIfNeeded()) {
    603                 notifyChanged();
    604             }
    605         }
    606     }
    607 
    608     /**
    609      * Sets the maximal size of the historical data. Defaults to
    610      * {@link #DEFAULT_HISTORY_MAX_LENGTH}
    611      * <p>
    612      *   <strong>Note:</strong> Setting this property will immediately
    613      *   enforce the specified max history size by dropping enough old
    614      *   historical records to enforce the desired size. Thus, any
    615      *   records that exceed the history size will be discarded and
    616      *   irreversibly lost.
    617      * </p>
    618      *
    619      * @param historyMaxSize The max history size.
    620      */
    621     public void setHistoryMaxSize(int historyMaxSize) {
    622         synchronized (mInstanceLock) {
    623             if (mHistoryMaxSize == historyMaxSize) {
    624                 return;
    625             }
    626             mHistoryMaxSize = historyMaxSize;
    627             pruneExcessiveHistoricalRecordsIfNeeded();
    628             if (sortActivitiesIfNeeded()) {
    629                 notifyChanged();
    630             }
    631         }
    632     }
    633 
    634     /**
    635      * Gets the history max size.
    636      *
    637      * @return The history max size.
    638      */
    639     public int getHistoryMaxSize() {
    640         synchronized (mInstanceLock) {
    641             return mHistoryMaxSize;
    642         }
    643     }
    644 
    645     /**
    646      * Gets the history size.
    647      *
    648      * @return The history size.
    649      */
    650     public int getHistorySize() {
    651         synchronized (mInstanceLock) {
    652             ensureConsistentState();
    653             return mHistoricalRecords.size();
    654         }
    655     }
    656 
    657     @Override
    658     protected void finalize() throws Throwable {
    659         super.finalize();
    660         mPackageMonitor.unregister();
    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 
   1113     /**
   1114      * Keeps in sync the historical records and activities with the installed applications.
   1115      */
   1116     private final class DataModelPackageMonitor extends PackageMonitor {
   1117 
   1118         @Override
   1119         public void onSomePackagesChanged() {
   1120             mReloadActivities = true;
   1121         }
   1122     }
   1123 }
   1124