ChooserActivity.java revision 0cef910d5e159800bacb69310a69ba04eafcd30c
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.app;
18
19import android.animation.ObjectAnimator;
20import android.annotation.NonNull;
21import android.app.Activity;
22import android.app.usage.UsageStatsManager;
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentSender;
27import android.content.IntentSender.SendIntentException;
28import android.content.ServiceConnection;
29import android.content.SharedPreferences;
30import android.content.pm.ActivityInfo;
31import android.content.pm.LabeledIntent;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.ResolveInfo;
35import android.database.DataSetObserver;
36import android.graphics.Color;
37import android.graphics.drawable.Drawable;
38import android.graphics.drawable.Icon;
39import android.os.Bundle;
40import android.os.Environment;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcelable;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.ResultReceiver;
48import android.os.UserHandle;
49import android.os.UserManager;
50import android.os.storage.StorageManager;
51import android.service.chooser.ChooserTarget;
52import android.service.chooser.ChooserTargetService;
53import android.service.chooser.IChooserTargetResult;
54import android.service.chooser.IChooserTargetService;
55import android.text.TextUtils;
56import android.util.FloatProperty;
57import android.util.Log;
58import android.util.Slog;
59import android.view.LayoutInflater;
60import android.view.View;
61import android.view.View.MeasureSpec;
62import android.view.View.OnClickListener;
63import android.view.View.OnLongClickListener;
64import android.view.ViewGroup;
65import android.view.ViewGroup.LayoutParams;
66import android.view.animation.AnimationUtils;
67import android.view.animation.Interpolator;
68import android.widget.AbsListView;
69import android.widget.BaseAdapter;
70import android.widget.ListView;
71import com.android.internal.R;
72import com.android.internal.annotations.VisibleForTesting;
73import com.android.internal.app.ResolverActivity.TargetInfo;
74import com.android.internal.logging.MetricsLogger;
75import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
76import com.google.android.collect.Lists;
77
78import java.io.File;
79import java.util.ArrayList;
80import java.util.Collections;
81import java.util.Comparator;
82import java.util.List;
83
84public class ChooserActivity extends ResolverActivity {
85    private static final String TAG = "ChooserActivity";
86
87    private static final boolean DEBUG = false;
88
89    private static final int QUERY_TARGET_SERVICE_LIMIT = 5;
90    private static final int WATCHDOG_TIMEOUT_MILLIS = 5000;
91
92    private Bundle mReplacementExtras;
93    private IntentSender mChosenComponentSender;
94    private IntentSender mRefinementIntentSender;
95    private RefinementResultReceiver mRefinementResultReceiver;
96    private ChooserTarget[] mCallerChooserTargets;
97    private ComponentName[] mFilteredComponentNames;
98
99    private Intent mReferrerFillInIntent;
100
101    private long mChooserShownTime;
102    private boolean mIsSuccessfullySelected;
103
104    private ChooserListAdapter mChooserListAdapter;
105    private ChooserRowAdapter mChooserRowAdapter;
106
107    private SharedPreferences mPinnedSharedPrefs;
108    private static final float PINNED_TARGET_SCORE_BOOST = 1000.f;
109    private static final float CALLER_TARGET_SCORE_BOOST = 900.f;
110    private static final String PINNED_SHARED_PREFS_NAME = "chooser_pin_settings";
111    private static final String TARGET_DETAILS_FRAGMENT_TAG = "targetDetailsFragment";
112
113    private final List<ChooserTargetServiceConnection> mServiceConnections = new ArrayList<>();
114
115    private static final int CHOOSER_TARGET_SERVICE_RESULT = 1;
116    private static final int CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT = 2;
117
118    private final Handler mChooserHandler = new Handler() {
119        @Override
120        public void handleMessage(Message msg) {
121            switch (msg.what) {
122                case CHOOSER_TARGET_SERVICE_RESULT:
123                    if (DEBUG) Log.d(TAG, "CHOOSER_TARGET_SERVICE_RESULT");
124                    if (isDestroyed()) break;
125                    final ServiceResultInfo sri = (ServiceResultInfo) msg.obj;
126                    if (!mServiceConnections.contains(sri.connection)) {
127                        Log.w(TAG, "ChooserTargetServiceConnection " + sri.connection
128                                + " returned after being removed from active connections."
129                                + " Have you considered returning results faster?");
130                        break;
131                    }
132                    if (sri.resultTargets != null) {
133                        mChooserListAdapter.addServiceResults(sri.originalTarget,
134                                sri.resultTargets);
135                    }
136                    unbindService(sri.connection);
137                    sri.connection.destroy();
138                    mServiceConnections.remove(sri.connection);
139                    if (mServiceConnections.isEmpty()) {
140                        mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
141                        sendVoiceChoicesIfNeeded();
142                        mChooserListAdapter.setShowServiceTargets(true);
143                    }
144                    break;
145
146                case CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT:
147                    if (DEBUG) {
148                        Log.d(TAG, "CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT; unbinding services");
149                    }
150                    unbindRemainingServices();
151                    sendVoiceChoicesIfNeeded();
152                    mChooserListAdapter.setShowServiceTargets(true);
153                    break;
154
155                default:
156                    super.handleMessage(msg);
157            }
158        }
159    };
160
161    @Override
162    protected void onCreate(Bundle savedInstanceState) {
163        final long intentReceivedTime = System.currentTimeMillis();
164        mIsSuccessfullySelected = false;
165        Intent intent = getIntent();
166        Parcelable targetParcelable = intent.getParcelableExtra(Intent.EXTRA_INTENT);
167        if (!(targetParcelable instanceof Intent)) {
168            Log.w("ChooserActivity", "Target is not an intent: " + targetParcelable);
169            finish();
170            super.onCreate(null);
171            return;
172        }
173        Intent target = (Intent) targetParcelable;
174        if (target != null) {
175            modifyTargetIntent(target);
176        }
177        Parcelable[] targetsParcelable
178                = intent.getParcelableArrayExtra(Intent.EXTRA_ALTERNATE_INTENTS);
179        if (targetsParcelable != null) {
180            final boolean offset = target == null;
181            Intent[] additionalTargets =
182                    new Intent[offset ? targetsParcelable.length - 1 : targetsParcelable.length];
183            for (int i = 0; i < targetsParcelable.length; i++) {
184                if (!(targetsParcelable[i] instanceof Intent)) {
185                    Log.w(TAG, "EXTRA_ALTERNATE_INTENTS array entry #" + i + " is not an Intent: "
186                            + targetsParcelable[i]);
187                    finish();
188                    super.onCreate(null);
189                    return;
190                }
191                final Intent additionalTarget = (Intent) targetsParcelable[i];
192                if (i == 0 && target == null) {
193                    target = additionalTarget;
194                    modifyTargetIntent(target);
195                } else {
196                    additionalTargets[offset ? i - 1 : i] = additionalTarget;
197                    modifyTargetIntent(additionalTarget);
198                }
199            }
200            setAdditionalTargets(additionalTargets);
201        }
202
203        mReplacementExtras = intent.getBundleExtra(Intent.EXTRA_REPLACEMENT_EXTRAS);
204        CharSequence title = intent.getCharSequenceExtra(Intent.EXTRA_TITLE);
205        int defaultTitleRes = 0;
206        if (title == null) {
207            defaultTitleRes = com.android.internal.R.string.chooseActivity;
208        }
209        Parcelable[] pa = intent.getParcelableArrayExtra(Intent.EXTRA_INITIAL_INTENTS);
210        Intent[] initialIntents = null;
211        if (pa != null) {
212            initialIntents = new Intent[pa.length];
213            for (int i=0; i<pa.length; i++) {
214                if (!(pa[i] instanceof Intent)) {
215                    Log.w(TAG, "Initial intent #" + i + " not an Intent: " + pa[i]);
216                    finish();
217                    super.onCreate(null);
218                    return;
219                }
220                final Intent in = (Intent) pa[i];
221                modifyTargetIntent(in);
222                initialIntents[i] = in;
223            }
224        }
225
226        mReferrerFillInIntent = new Intent().putExtra(Intent.EXTRA_REFERRER, getReferrer());
227
228        mChosenComponentSender = intent.getParcelableExtra(
229                Intent.EXTRA_CHOSEN_COMPONENT_INTENT_SENDER);
230        mRefinementIntentSender = intent.getParcelableExtra(
231                Intent.EXTRA_CHOOSER_REFINEMENT_INTENT_SENDER);
232        setSafeForwardingMode(true);
233
234        pa = intent.getParcelableArrayExtra(Intent.EXTRA_EXCLUDE_COMPONENTS);
235        if (pa != null) {
236            ComponentName[] names = new ComponentName[pa.length];
237            for (int i = 0; i < pa.length; i++) {
238                if (!(pa[i] instanceof ComponentName)) {
239                    Log.w(TAG, "Filtered component #" + i + " not a ComponentName: " + pa[i]);
240                    names = null;
241                    break;
242                }
243                names[i] = (ComponentName) pa[i];
244            }
245            mFilteredComponentNames = names;
246        }
247
248        pa = intent.getParcelableArrayExtra(Intent.EXTRA_CHOOSER_TARGETS);
249        if (pa != null) {
250            ChooserTarget[] targets = new ChooserTarget[pa.length];
251            for (int i = 0; i < pa.length; i++) {
252                if (!(pa[i] instanceof ChooserTarget)) {
253                    Log.w(TAG, "Chooser target #" + i + " not a ChooserTarget: " + pa[i]);
254                    targets = null;
255                    break;
256                }
257                targets[i] = (ChooserTarget) pa[i];
258            }
259            mCallerChooserTargets = targets;
260        }
261
262        mPinnedSharedPrefs = getPinnedSharedPrefs(this);
263        super.onCreate(savedInstanceState, target, title, defaultTitleRes, initialIntents,
264                null, false);
265
266        MetricsLogger.action(this, MetricsEvent.ACTION_ACTIVITY_CHOOSER_SHOWN);
267
268        mChooserShownTime = System.currentTimeMillis();
269        final long systemCost = mChooserShownTime - intentReceivedTime;
270        MetricsLogger.histogram(null, "system_cost_for_smart_sharing", (int) systemCost);
271        if (DEBUG) {
272            Log.d(TAG, "System Time Cost is " + systemCost);
273        }
274    }
275
276    static SharedPreferences getPinnedSharedPrefs(Context context) {
277        // The code below is because in the android:ui process, no one can hear you scream.
278        // The package info in the context isn't initialized in the way it is for normal apps,
279        // so the standard, name-based context.getSharedPreferences doesn't work. Instead, we
280        // build the path manually below using the same policy that appears in ContextImpl.
281        // This fails silently under the hood if there's a problem, so if we find ourselves in
282        // the case where we don't have access to credential encrypted storage we just won't
283        // have our pinned target info.
284        final File prefsFile = new File(new File(
285                Environment.getDataUserCePackageDirectory(StorageManager.UUID_PRIVATE_INTERNAL,
286                        context.getUserId(), context.getPackageName()),
287                "shared_prefs"),
288                PINNED_SHARED_PREFS_NAME + ".xml");
289        return context.getSharedPreferences(prefsFile, MODE_PRIVATE);
290    }
291
292    @Override
293    protected void onDestroy() {
294        super.onDestroy();
295        if (mRefinementResultReceiver != null) {
296            mRefinementResultReceiver.destroy();
297            mRefinementResultReceiver = null;
298        }
299        unbindRemainingServices();
300        mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_RESULT);
301    }
302
303    @Override
304    public Intent getReplacementIntent(ActivityInfo aInfo, Intent defIntent) {
305        Intent result = defIntent;
306        if (mReplacementExtras != null) {
307            final Bundle replExtras = mReplacementExtras.getBundle(aInfo.packageName);
308            if (replExtras != null) {
309                result = new Intent(defIntent);
310                result.putExtras(replExtras);
311            }
312        }
313        if (aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_PARENT)
314                || aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE)) {
315            result = Intent.createChooser(result,
316                    getIntent().getCharSequenceExtra(Intent.EXTRA_TITLE));
317
318            // Don't auto-launch single intents if the intent is being forwarded. This is done
319            // because automatically launching a resolving application as a response to the user
320            // action of switching accounts is pretty unexpected.
321            result.putExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE, false);
322        }
323        return result;
324    }
325
326    @Override
327    public void onActivityStarted(TargetInfo cti) {
328        if (mChosenComponentSender != null) {
329            final ComponentName target = cti.getResolvedComponentName();
330            if (target != null) {
331                final Intent fillIn = new Intent().putExtra(Intent.EXTRA_CHOSEN_COMPONENT, target);
332                try {
333                    mChosenComponentSender.sendIntent(this, Activity.RESULT_OK, fillIn, null, null);
334                } catch (IntentSender.SendIntentException e) {
335                    Slog.e(TAG, "Unable to launch supplied IntentSender to report "
336                            + "the chosen component: " + e);
337                }
338            }
339        }
340    }
341
342    @Override
343    public void onPrepareAdapterView(AbsListView adapterView, ResolveListAdapter adapter,
344            boolean alwaysUseOption) {
345        final ListView listView = adapterView instanceof ListView ? (ListView) adapterView : null;
346        mChooserListAdapter = (ChooserListAdapter) adapter;
347        if (mCallerChooserTargets != null && mCallerChooserTargets.length > 0) {
348            mChooserListAdapter.addServiceResults(null, Lists.newArrayList(mCallerChooserTargets));
349        }
350        mChooserRowAdapter = new ChooserRowAdapter(mChooserListAdapter);
351        mChooserRowAdapter.registerDataSetObserver(new OffsetDataSetObserver(adapterView));
352        adapterView.setAdapter(mChooserRowAdapter);
353        if (listView != null) {
354            listView.setItemsCanFocus(true);
355        }
356    }
357
358    @Override
359    public int getLayoutResource() {
360        return R.layout.chooser_grid;
361    }
362
363    @Override
364    public boolean shouldGetActivityMetadata() {
365        return true;
366    }
367
368    @Override
369    public boolean shouldAutoLaunchSingleChoice(TargetInfo target) {
370        return getIntent().getBooleanExtra(Intent.EXTRA_AUTO_LAUNCH_SINGLE_CHOICE,
371                super.shouldAutoLaunchSingleChoice(target));
372    }
373
374    @Override
375    public void showTargetDetails(ResolveInfo ri) {
376        ComponentName name = ri.activityInfo.getComponentName();
377        boolean pinned = mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
378        ResolverTargetActionsDialogFragment f =
379                new ResolverTargetActionsDialogFragment(ri.loadLabel(getPackageManager()),
380                        name, pinned);
381        f.show(getFragmentManager(), TARGET_DETAILS_FRAGMENT_TAG);
382    }
383
384    private void modifyTargetIntent(Intent in) {
385        final String action = in.getAction();
386        if (Intent.ACTION_SEND.equals(action) ||
387                Intent.ACTION_SEND_MULTIPLE.equals(action)) {
388            in.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
389                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
390        }
391    }
392
393    @Override
394    protected boolean onTargetSelected(TargetInfo target, boolean alwaysCheck) {
395        if (mRefinementIntentSender != null) {
396            final Intent fillIn = new Intent();
397            final List<Intent> sourceIntents = target.getAllSourceIntents();
398            if (!sourceIntents.isEmpty()) {
399                fillIn.putExtra(Intent.EXTRA_INTENT, sourceIntents.get(0));
400                if (sourceIntents.size() > 1) {
401                    final Intent[] alts = new Intent[sourceIntents.size() - 1];
402                    for (int i = 1, N = sourceIntents.size(); i < N; i++) {
403                        alts[i - 1] = sourceIntents.get(i);
404                    }
405                    fillIn.putExtra(Intent.EXTRA_ALTERNATE_INTENTS, alts);
406                }
407                if (mRefinementResultReceiver != null) {
408                    mRefinementResultReceiver.destroy();
409                }
410                mRefinementResultReceiver = new RefinementResultReceiver(this, target, null);
411                fillIn.putExtra(Intent.EXTRA_RESULT_RECEIVER,
412                        mRefinementResultReceiver);
413                try {
414                    mRefinementIntentSender.sendIntent(this, 0, fillIn, null, null);
415                    return false;
416                } catch (SendIntentException e) {
417                    Log.e(TAG, "Refinement IntentSender failed to send", e);
418                }
419            }
420        }
421        updateChooserCounts(target, mContentType);
422        return super.onTargetSelected(target, alwaysCheck);
423    }
424
425    @Override
426    public void startSelected(int which, boolean always, boolean filtered) {
427        final long selectionCost = System.currentTimeMillis() - mChooserShownTime;
428        super.startSelected(which, always, filtered);
429
430        if (mChooserListAdapter != null) {
431            // Log the index of which type of target the user picked.
432            // Lower values mean the ranking was better.
433            int cat = 0;
434            int value = which;
435            switch (mChooserListAdapter.getPositionTargetType(which)) {
436                case ChooserListAdapter.TARGET_CALLER:
437                    cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_APP_TARGET;
438                    break;
439                case ChooserListAdapter.TARGET_SERVICE:
440                    cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_SERVICE_TARGET;
441                    value -= mChooserListAdapter.getCallerTargetCount();
442                    break;
443                case ChooserListAdapter.TARGET_STANDARD:
444                    cat = MetricsEvent.ACTION_ACTIVITY_CHOOSER_PICKED_STANDARD_TARGET;
445                    value -= mChooserListAdapter.getCallerTargetCount()
446                            + mChooserListAdapter.getServiceTargetCount();
447                    break;
448            }
449
450            if (cat != 0) {
451                MetricsLogger.action(this, cat, value);
452            }
453
454            if (mIsSuccessfullySelected) {
455                if (DEBUG) {
456                    Log.d(TAG, "User Selection Time Cost is " + selectionCost);
457                    Log.d(TAG, "position of selected app/service/caller is " +
458                            Integer.toString(value));
459                }
460                MetricsLogger.histogram(null, "user_selection_cost_for_smart_sharing",
461                        (int) selectionCost);
462                MetricsLogger.histogram(null, "app_position_for_smart_sharing", value);
463            }
464        }
465    }
466
467    void queryTargetServices(ChooserListAdapter adapter) {
468        final PackageManager pm = getPackageManager();
469        int targetsToQuery = 0;
470        for (int i = 0, N = adapter.getDisplayResolveInfoCount(); i < N; i++) {
471            final DisplayResolveInfo dri = adapter.getDisplayResolveInfo(i);
472            if (adapter.getScore(dri) == 0) {
473                // A score of 0 means the app hasn't been used in some time;
474                // don't query it as it's not likely to be relevant.
475                continue;
476            }
477            final ActivityInfo ai = dri.getResolveInfo().activityInfo;
478            final Bundle md = ai.metaData;
479            final String serviceName = md != null ? convertServiceName(ai.packageName,
480                    md.getString(ChooserTargetService.META_DATA_NAME)) : null;
481            if (serviceName != null) {
482                final ComponentName serviceComponent = new ComponentName(
483                        ai.packageName, serviceName);
484                final Intent serviceIntent = new Intent(ChooserTargetService.SERVICE_INTERFACE)
485                        .setComponent(serviceComponent);
486
487                if (DEBUG) {
488                    Log.d(TAG, "queryTargets found target with service " + serviceComponent);
489                }
490
491                try {
492                    final String perm = pm.getServiceInfo(serviceComponent, 0).permission;
493                    if (!ChooserTargetService.BIND_PERMISSION.equals(perm)) {
494                        Log.w(TAG, "ChooserTargetService " + serviceComponent + " does not require"
495                                + " permission " + ChooserTargetService.BIND_PERMISSION
496                                + " - this service will not be queried for ChooserTargets."
497                                + " add android:permission=\""
498                                + ChooserTargetService.BIND_PERMISSION + "\""
499                                + " to the <service> tag for " + serviceComponent
500                                + " in the manifest.");
501                        continue;
502                    }
503                } catch (NameNotFoundException e) {
504                    Log.e(TAG, "Could not look up service " + serviceComponent
505                            + "; component name not found");
506                    continue;
507                }
508
509                final ChooserTargetServiceConnection conn =
510                        new ChooserTargetServiceConnection(this, dri);
511
512                // Explicitly specify Process.myUserHandle instead of calling bindService
513                // to avoid the warning from calling from the system process without an explicit
514                // user handle
515                if (bindServiceAsUser(serviceIntent, conn, BIND_AUTO_CREATE | BIND_NOT_FOREGROUND,
516                        Process.myUserHandle())) {
517                    if (DEBUG) {
518                        Log.d(TAG, "Binding service connection for target " + dri
519                                + " intent " + serviceIntent);
520                    }
521                    mServiceConnections.add(conn);
522                    targetsToQuery++;
523                }
524            }
525            if (targetsToQuery >= QUERY_TARGET_SERVICE_LIMIT) {
526                if (DEBUG) Log.d(TAG, "queryTargets hit query target limit "
527                        + QUERY_TARGET_SERVICE_LIMIT);
528                break;
529            }
530        }
531
532        if (!mServiceConnections.isEmpty()) {
533            if (DEBUG) Log.d(TAG, "queryTargets setting watchdog timer for "
534                    + WATCHDOG_TIMEOUT_MILLIS + "ms");
535            mChooserHandler.sendEmptyMessageDelayed(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT,
536                    WATCHDOG_TIMEOUT_MILLIS);
537        } else {
538            sendVoiceChoicesIfNeeded();
539        }
540    }
541
542    private String convertServiceName(String packageName, String serviceName) {
543        if (TextUtils.isEmpty(serviceName)) {
544            return null;
545        }
546
547        final String fullName;
548        if (serviceName.startsWith(".")) {
549            // Relative to the app package. Prepend the app package name.
550            fullName = packageName + serviceName;
551        } else if (serviceName.indexOf('.') >= 0) {
552            // Fully qualified package name.
553            fullName = serviceName;
554        } else {
555            fullName = null;
556        }
557        return fullName;
558    }
559
560    void unbindRemainingServices() {
561        if (DEBUG) {
562            Log.d(TAG, "unbindRemainingServices, " + mServiceConnections.size() + " left");
563        }
564        for (int i = 0, N = mServiceConnections.size(); i < N; i++) {
565            final ChooserTargetServiceConnection conn = mServiceConnections.get(i);
566            if (DEBUG) Log.d(TAG, "unbinding " + conn);
567            unbindService(conn);
568            conn.destroy();
569        }
570        mServiceConnections.clear();
571        mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
572    }
573
574    public void onSetupVoiceInteraction() {
575        // Do nothing. We'll send the voice stuff ourselves.
576    }
577
578    void updateChooserCounts(TargetInfo info, String annotation) {
579        if (info != null) {
580            UsageStatsManager usageStatsManager =
581                    (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
582            if (usageStatsManager == null) {
583                if (DEBUG) {
584                    Log.d(TAG, "Can not start UsageStatsManager");
585                }
586                return;
587            }
588            final ResolveInfo ri = info.getResolveInfo();
589            if (ri != null && ri.activityInfo != null) {
590                usageStatsManager.reportChooserSelection(ri.activityInfo.packageName, getUserId(),
591                        annotation, null, info.getResolvedIntent().getAction());
592                if (mAdapter != null) {
593                    mAdapter.updateModel(info.getResolvedComponentName());
594                }
595                if (DEBUG) {
596                    Log.d(TAG, "ResolveInfo Package is" + ri.activityInfo.packageName);
597                }
598            } else if(DEBUG) {
599                Log.d(TAG, "Can not log Chooser Counts of null ResovleInfo");
600            }
601        }
602        mIsSuccessfullySelected = true;
603    }
604
605    void onRefinementResult(TargetInfo selectedTarget, Intent matchingIntent) {
606        if (mRefinementResultReceiver != null) {
607            mRefinementResultReceiver.destroy();
608            mRefinementResultReceiver = null;
609        }
610        if (selectedTarget == null) {
611            Log.e(TAG, "Refinement result intent did not match any known targets; canceling");
612        } else if (!checkTargetSourceIntent(selectedTarget, matchingIntent)) {
613            Log.e(TAG, "onRefinementResult: Selected target " + selectedTarget
614                    + " cannot match refined source intent " + matchingIntent);
615        } else {
616            TargetInfo clonedTarget = selectedTarget.cloneFilledIn(matchingIntent, 0);
617            if (super.onTargetSelected(clonedTarget, false)) {
618                updateChooserCounts(clonedTarget, mContentType);
619                finish();
620                return;
621            }
622        }
623        onRefinementCanceled();
624    }
625
626    void onRefinementCanceled() {
627        if (mRefinementResultReceiver != null) {
628            mRefinementResultReceiver.destroy();
629            mRefinementResultReceiver = null;
630        }
631        finish();
632    }
633
634    boolean checkTargetSourceIntent(TargetInfo target, Intent matchingIntent) {
635        final List<Intent> targetIntents = target.getAllSourceIntents();
636        for (int i = 0, N = targetIntents.size(); i < N; i++) {
637            final Intent targetIntent = targetIntents.get(i);
638            if (targetIntent.filterEquals(matchingIntent)) {
639                return true;
640            }
641        }
642        return false;
643    }
644
645    void filterServiceTargets(String packageName, List<ChooserTarget> targets) {
646        if (targets == null) {
647            return;
648        }
649
650        final PackageManager pm = getPackageManager();
651        for (int i = targets.size() - 1; i >= 0; i--) {
652            final ChooserTarget target = targets.get(i);
653            final ComponentName targetName = target.getComponentName();
654            if (packageName != null && packageName.equals(targetName.getPackageName())) {
655                // Anything from the original target's package is fine.
656                continue;
657            }
658
659            boolean remove;
660            try {
661                final ActivityInfo ai = pm.getActivityInfo(targetName, 0);
662                remove = !ai.exported || ai.permission != null;
663            } catch (NameNotFoundException e) {
664                Log.e(TAG, "Target " + target + " returned by " + packageName
665                        + " component not found");
666                remove = true;
667            }
668
669            if (remove) {
670                targets.remove(i);
671            }
672        }
673    }
674
675    public class ChooserListController extends ResolverListController {
676        public ChooserListController(Context context,
677                PackageManager pm,
678                Intent targetIntent,
679                String referrerPackageName,
680                int launchedFromUid) {
681            super(context, pm, targetIntent, referrerPackageName, launchedFromUid);
682        }
683
684        @Override
685        boolean isComponentPinned(ComponentName name) {
686            return mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
687        }
688
689        @Override
690        boolean isComponentFiltered(ComponentName name) {
691            if (mFilteredComponentNames == null) {
692                return false;
693            }
694            for (ComponentName filteredComponentName : mFilteredComponentNames) {
695                if (name.equals(filteredComponentName)) {
696                    return true;
697                }
698            }
699            return false;
700        }
701
702        @Override
703        public float getScore(DisplayResolveInfo target) {
704            if (target == null) {
705                return CALLER_TARGET_SCORE_BOOST;
706            }
707            float score = super.getScore(target);
708            if (target.isPinned()) {
709                score += PINNED_TARGET_SCORE_BOOST;
710            }
711            return score;
712        }
713    }
714
715    @Override
716    public ResolveListAdapter createAdapter(Context context, List<Intent> payloadIntents,
717            Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
718            boolean filterLastUsed) {
719        final ChooserListAdapter adapter = new ChooserListAdapter(context, payloadIntents,
720                initialIntents, rList, launchedFromUid, filterLastUsed, createListController());
721        return adapter;
722    }
723
724    @VisibleForTesting
725    protected ResolverListController createListController() {
726        return new ChooserListController(
727                this,
728                mPm,
729                getTargetIntent(),
730                getReferrerPackageName(),
731                mLaunchedFromUid);
732    }
733
734    final class ChooserTargetInfo implements TargetInfo {
735        private final DisplayResolveInfo mSourceInfo;
736        private final ResolveInfo mBackupResolveInfo;
737        private final ChooserTarget mChooserTarget;
738        private Drawable mBadgeIcon = null;
739        private CharSequence mBadgeContentDescription;
740        private Drawable mDisplayIcon;
741        private final Intent mFillInIntent;
742        private final int mFillInFlags;
743        private final float mModifiedScore;
744
745        public ChooserTargetInfo(DisplayResolveInfo sourceInfo, ChooserTarget chooserTarget,
746                float modifiedScore) {
747            mSourceInfo = sourceInfo;
748            mChooserTarget = chooserTarget;
749            mModifiedScore = modifiedScore;
750            if (sourceInfo != null) {
751                final ResolveInfo ri = sourceInfo.getResolveInfo();
752                if (ri != null) {
753                    final ActivityInfo ai = ri.activityInfo;
754                    if (ai != null && ai.applicationInfo != null) {
755                        final PackageManager pm = getPackageManager();
756                        mBadgeIcon = pm.getApplicationIcon(ai.applicationInfo);
757                        mBadgeContentDescription = pm.getApplicationLabel(ai.applicationInfo);
758                    }
759                }
760            }
761            final Icon icon = chooserTarget.getIcon();
762            // TODO do this in the background
763            mDisplayIcon = icon != null ? icon.loadDrawable(ChooserActivity.this) : null;
764
765            if (sourceInfo != null) {
766                mBackupResolveInfo = null;
767            } else {
768                mBackupResolveInfo = getPackageManager().resolveActivity(getResolvedIntent(), 0);
769            }
770
771            mFillInIntent = null;
772            mFillInFlags = 0;
773        }
774
775        private ChooserTargetInfo(ChooserTargetInfo other, Intent fillInIntent, int flags) {
776            mSourceInfo = other.mSourceInfo;
777            mBackupResolveInfo = other.mBackupResolveInfo;
778            mChooserTarget = other.mChooserTarget;
779            mBadgeIcon = other.mBadgeIcon;
780            mBadgeContentDescription = other.mBadgeContentDescription;
781            mDisplayIcon = other.mDisplayIcon;
782            mFillInIntent = fillInIntent;
783            mFillInFlags = flags;
784            mModifiedScore = other.mModifiedScore;
785        }
786
787        public float getModifiedScore() {
788            return mModifiedScore;
789        }
790
791        @Override
792        public Intent getResolvedIntent() {
793            if (mSourceInfo != null) {
794                return mSourceInfo.getResolvedIntent();
795            }
796
797            final Intent targetIntent = new Intent(getTargetIntent());
798            targetIntent.setComponent(mChooserTarget.getComponentName());
799            targetIntent.putExtras(mChooserTarget.getIntentExtras());
800            return targetIntent;
801        }
802
803        @Override
804        public ComponentName getResolvedComponentName() {
805            if (mSourceInfo != null) {
806                return mSourceInfo.getResolvedComponentName();
807            } else if (mBackupResolveInfo != null) {
808                return new ComponentName(mBackupResolveInfo.activityInfo.packageName,
809                        mBackupResolveInfo.activityInfo.name);
810            }
811            return null;
812        }
813
814        private Intent getBaseIntentToSend() {
815            Intent result = getResolvedIntent();
816            if (result == null) {
817                Log.e(TAG, "ChooserTargetInfo: no base intent available to send");
818            } else {
819                result = new Intent(result);
820                if (mFillInIntent != null) {
821                    result.fillIn(mFillInIntent, mFillInFlags);
822                }
823                result.fillIn(mReferrerFillInIntent, 0);
824            }
825            return result;
826        }
827
828        @Override
829        public boolean start(Activity activity, Bundle options) {
830            throw new RuntimeException("ChooserTargets should be started as caller.");
831        }
832
833        @Override
834        public boolean startAsCaller(Activity activity, Bundle options, int userId) {
835            final Intent intent = getBaseIntentToSend();
836            if (intent == null) {
837                return false;
838            }
839            intent.setComponent(mChooserTarget.getComponentName());
840            intent.putExtras(mChooserTarget.getIntentExtras());
841
842            // Important: we will ignore the target security checks in ActivityManager
843            // if and only if the ChooserTarget's target package is the same package
844            // where we got the ChooserTargetService that provided it. This lets a
845            // ChooserTargetService provide a non-exported or permission-guarded target
846            // to the chooser for the user to pick.
847            //
848            // If mSourceInfo is null, we got this ChooserTarget from the caller or elsewhere
849            // so we'll obey the caller's normal security checks.
850            final boolean ignoreTargetSecurity = mSourceInfo != null
851                    && mSourceInfo.getResolvedComponentName().getPackageName()
852                    .equals(mChooserTarget.getComponentName().getPackageName());
853            activity.startActivityAsCaller(intent, options, ignoreTargetSecurity, userId);
854            return true;
855        }
856
857        @Override
858        public boolean startAsUser(Activity activity, Bundle options, UserHandle user) {
859            throw new RuntimeException("ChooserTargets should be started as caller.");
860        }
861
862        @Override
863        public ResolveInfo getResolveInfo() {
864            return mSourceInfo != null ? mSourceInfo.getResolveInfo() : mBackupResolveInfo;
865        }
866
867        @Override
868        public CharSequence getDisplayLabel() {
869            return mChooserTarget.getTitle();
870        }
871
872        @Override
873        public CharSequence getExtendedInfo() {
874            // ChooserTargets have badge icons, so we won't show the extended info to disambiguate.
875            return null;
876        }
877
878        @Override
879        public Drawable getDisplayIcon() {
880            return mDisplayIcon;
881        }
882
883        @Override
884        public Drawable getBadgeIcon() {
885            return mBadgeIcon;
886        }
887
888        @Override
889        public CharSequence getBadgeContentDescription() {
890            return mBadgeContentDescription;
891        }
892
893        @Override
894        public TargetInfo cloneFilledIn(Intent fillInIntent, int flags) {
895            return new ChooserTargetInfo(this, fillInIntent, flags);
896        }
897
898        @Override
899        public List<Intent> getAllSourceIntents() {
900            final List<Intent> results = new ArrayList<>();
901            if (mSourceInfo != null) {
902                // We only queried the service for the first one in our sourceinfo.
903                results.add(mSourceInfo.getAllSourceIntents().get(0));
904            }
905            return results;
906        }
907
908        @Override
909        public boolean isPinned() {
910            return mSourceInfo != null ? mSourceInfo.isPinned() : false;
911        }
912    }
913
914    public class ChooserListAdapter extends ResolveListAdapter {
915        public static final int TARGET_BAD = -1;
916        public static final int TARGET_CALLER = 0;
917        public static final int TARGET_SERVICE = 1;
918        public static final int TARGET_STANDARD = 2;
919
920        private static final int MAX_SERVICE_TARGETS = 8;
921        private static final int MAX_TARGETS_PER_SERVICE = 4;
922
923        private final List<ChooserTargetInfo> mServiceTargets = new ArrayList<>();
924        private final List<TargetInfo> mCallerTargets = new ArrayList<>();
925        private boolean mShowServiceTargets;
926
927        private float mLateFee = 1.f;
928
929        private final BaseChooserTargetComparator mBaseTargetComparator
930                = new BaseChooserTargetComparator();
931
932        public ChooserListAdapter(Context context, List<Intent> payloadIntents,
933                Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
934                boolean filterLastUsed, ResolverListController resolverListController) {
935            // Don't send the initial intents through the shared ResolverActivity path,
936            // we want to separate them into a different section.
937            super(context, payloadIntents, null, rList, launchedFromUid, filterLastUsed,
938                    resolverListController);
939
940            if (initialIntents != null) {
941                final PackageManager pm = getPackageManager();
942                for (int i = 0; i < initialIntents.length; i++) {
943                    final Intent ii = initialIntents[i];
944                    if (ii == null) {
945                        continue;
946                    }
947
948                    // We reimplement Intent#resolveActivityInfo here because if we have an
949                    // implicit intent, we want the ResolveInfo returned by PackageManager
950                    // instead of one we reconstruct ourselves. The ResolveInfo returned might
951                    // have extra metadata and resolvePackageName set and we want to respect that.
952                    ResolveInfo ri = null;
953                    ActivityInfo ai = null;
954                    final ComponentName cn = ii.getComponent();
955                    if (cn != null) {
956                        try {
957                            ai = pm.getActivityInfo(ii.getComponent(), 0);
958                            ri = new ResolveInfo();
959                            ri.activityInfo = ai;
960                        } catch (PackageManager.NameNotFoundException ignored) {
961                            // ai will == null below
962                        }
963                    }
964                    if (ai == null) {
965                        ri = pm.resolveActivity(ii, PackageManager.MATCH_DEFAULT_ONLY);
966                        ai = ri != null ? ri.activityInfo : null;
967                    }
968                    if (ai == null) {
969                        Log.w(TAG, "No activity found for " + ii);
970                        continue;
971                    }
972                    UserManager userManager =
973                            (UserManager) getSystemService(Context.USER_SERVICE);
974                    if (ii instanceof LabeledIntent) {
975                        LabeledIntent li = (LabeledIntent)ii;
976                        ri.resolvePackageName = li.getSourcePackage();
977                        ri.labelRes = li.getLabelResource();
978                        ri.nonLocalizedLabel = li.getNonLocalizedLabel();
979                        ri.icon = li.getIconResource();
980                        ri.iconResourceId = ri.icon;
981                    }
982                    if (userManager.isManagedProfile()) {
983                        ri.noResourceId = true;
984                        ri.icon = 0;
985                    }
986                    mCallerTargets.add(new DisplayResolveInfo(ii, ri,
987                            ri.loadLabel(pm), null, ii));
988                }
989            }
990        }
991
992        @Override
993        public boolean showsExtendedInfo(TargetInfo info) {
994            // We have badges so we don't need this text shown.
995            return false;
996        }
997
998        @Override
999        public boolean isComponentPinned(ComponentName name) {
1000            return mPinnedSharedPrefs.getBoolean(name.flattenToString(), false);
1001        }
1002
1003        @Override
1004        public View onCreateView(ViewGroup parent) {
1005            return mInflater.inflate(
1006                    com.android.internal.R.layout.resolve_grid_item, parent, false);
1007        }
1008
1009        @Override
1010        public void onListRebuilt() {
1011            if (mServiceTargets != null) {
1012                pruneServiceTargets();
1013            }
1014            if (DEBUG) Log.d(TAG, "List built querying services");
1015            queryTargetServices(this);
1016        }
1017
1018        @Override
1019        public boolean shouldGetResolvedFilter() {
1020            return true;
1021        }
1022
1023        @Override
1024        public int getCount() {
1025            return super.getCount() + getServiceTargetCount() + getCallerTargetCount();
1026        }
1027
1028        @Override
1029        public int getUnfilteredCount() {
1030            return super.getUnfilteredCount() + getServiceTargetCount() + getCallerTargetCount();
1031        }
1032
1033        public int getCallerTargetCount() {
1034            return mCallerTargets.size();
1035        }
1036
1037        public int getServiceTargetCount() {
1038            if (!mShowServiceTargets) {
1039                return 0;
1040            }
1041            return Math.min(mServiceTargets.size(), MAX_SERVICE_TARGETS);
1042        }
1043
1044        public int getStandardTargetCount() {
1045            return super.getCount();
1046        }
1047
1048        public int getPositionTargetType(int position) {
1049            int offset = 0;
1050
1051            final int callerTargetCount = getCallerTargetCount();
1052            if (position < callerTargetCount) {
1053                return TARGET_CALLER;
1054            }
1055            offset += callerTargetCount;
1056
1057            final int serviceTargetCount = getServiceTargetCount();
1058            if (position - offset < serviceTargetCount) {
1059                return TARGET_SERVICE;
1060            }
1061            offset += serviceTargetCount;
1062
1063            final int standardTargetCount = super.getCount();
1064            if (position - offset < standardTargetCount) {
1065                return TARGET_STANDARD;
1066            }
1067
1068            return TARGET_BAD;
1069        }
1070
1071        @Override
1072        public TargetInfo getItem(int position) {
1073            return targetInfoForPosition(position, true);
1074        }
1075
1076        @Override
1077        public TargetInfo targetInfoForPosition(int position, boolean filtered) {
1078            int offset = 0;
1079
1080            final int callerTargetCount = getCallerTargetCount();
1081            if (position < callerTargetCount) {
1082                return mCallerTargets.get(position);
1083            }
1084            offset += callerTargetCount;
1085
1086            final int serviceTargetCount = getServiceTargetCount();
1087            if (position - offset < serviceTargetCount) {
1088                return mServiceTargets.get(position - offset);
1089            }
1090            offset += serviceTargetCount;
1091
1092            return filtered ? super.getItem(position - offset)
1093                    : getDisplayInfoAt(position - offset);
1094        }
1095
1096        public void addServiceResults(DisplayResolveInfo origTarget, List<ChooserTarget> targets) {
1097            if (DEBUG) Log.d(TAG, "addServiceResults " + origTarget + ", " + targets.size()
1098                    + " targets");
1099            final float parentScore = getScore(origTarget);
1100            Collections.sort(targets, mBaseTargetComparator);
1101            float lastScore = 0;
1102            for (int i = 0, N = Math.min(targets.size(), MAX_TARGETS_PER_SERVICE); i < N; i++) {
1103                final ChooserTarget target = targets.get(i);
1104                float targetScore = target.getScore();
1105                targetScore *= parentScore;
1106                targetScore *= mLateFee;
1107                if (i > 0 && targetScore >= lastScore) {
1108                    // Apply a decay so that the top app can't crowd out everything else.
1109                    // This incents ChooserTargetServices to define what's truly better.
1110                    targetScore = lastScore * 0.95f;
1111                }
1112                insertServiceTarget(new ChooserTargetInfo(origTarget, target, targetScore));
1113
1114                if (DEBUG) {
1115                    Log.d(TAG, " => " + target.toString() + " score=" + targetScore
1116                            + " base=" + target.getScore()
1117                            + " lastScore=" + lastScore
1118                            + " parentScore=" + parentScore
1119                            + " lateFee=" + mLateFee);
1120                }
1121
1122                lastScore = targetScore;
1123            }
1124
1125            mLateFee *= 0.95f;
1126
1127            notifyDataSetChanged();
1128        }
1129
1130        /**
1131         * Set to true to reveal all service targets at once.
1132         */
1133        public void setShowServiceTargets(boolean show) {
1134            mShowServiceTargets = show;
1135            notifyDataSetChanged();
1136        }
1137
1138        private void insertServiceTarget(ChooserTargetInfo chooserTargetInfo) {
1139            final float newScore = chooserTargetInfo.getModifiedScore();
1140            for (int i = 0, N = mServiceTargets.size(); i < N; i++) {
1141                final ChooserTargetInfo serviceTarget = mServiceTargets.get(i);
1142                if (newScore > serviceTarget.getModifiedScore()) {
1143                    mServiceTargets.add(i, chooserTargetInfo);
1144                    return;
1145                }
1146            }
1147            mServiceTargets.add(chooserTargetInfo);
1148        }
1149
1150        private void pruneServiceTargets() {
1151            if (DEBUG) Log.d(TAG, "pruneServiceTargets");
1152            for (int i = mServiceTargets.size() - 1; i >= 0; i--) {
1153                final ChooserTargetInfo cti = mServiceTargets.get(i);
1154                if (!hasResolvedTarget(cti.getResolveInfo())) {
1155                    if (DEBUG) Log.d(TAG, " => " + i + " " + cti);
1156                    mServiceTargets.remove(i);
1157                }
1158            }
1159        }
1160    }
1161
1162    static class BaseChooserTargetComparator implements Comparator<ChooserTarget> {
1163        @Override
1164        public int compare(ChooserTarget lhs, ChooserTarget rhs) {
1165            // Descending order
1166            return (int) Math.signum(rhs.getScore() - lhs.getScore());
1167        }
1168    }
1169
1170    static class RowScale {
1171        private static final int DURATION = 400;
1172
1173        float mScale;
1174        ChooserRowAdapter mAdapter;
1175        private final ObjectAnimator mAnimator;
1176
1177        public static final FloatProperty<RowScale> PROPERTY =
1178                new FloatProperty<RowScale>("scale") {
1179            @Override
1180            public void setValue(RowScale object, float value) {
1181                object.mScale = value;
1182                object.mAdapter.notifyDataSetChanged();
1183            }
1184
1185            @Override
1186            public Float get(RowScale object) {
1187                return object.mScale;
1188            }
1189        };
1190
1191        public RowScale(@NonNull ChooserRowAdapter adapter, float from, float to) {
1192            mAdapter = adapter;
1193            mScale = from;
1194            if (from == to) {
1195                mAnimator = null;
1196                return;
1197            }
1198
1199            mAnimator = ObjectAnimator.ofFloat(this, PROPERTY, from, to).setDuration(DURATION);
1200        }
1201
1202        public RowScale setInterpolator(Interpolator interpolator) {
1203            if (mAnimator != null) {
1204                mAnimator.setInterpolator(interpolator);
1205            }
1206            return this;
1207        }
1208
1209        public float get() {
1210            return mScale;
1211        }
1212
1213        public void startAnimation() {
1214            if (mAnimator != null) {
1215                mAnimator.start();
1216            }
1217        }
1218
1219        public void cancelAnimation() {
1220            if (mAnimator != null) {
1221                mAnimator.cancel();
1222            }
1223        }
1224    }
1225
1226    class ChooserRowAdapter extends BaseAdapter {
1227        private ChooserListAdapter mChooserListAdapter;
1228        private final LayoutInflater mLayoutInflater;
1229        private final int mColumnCount = 4;
1230        private RowScale[] mServiceTargetScale;
1231        private final Interpolator mInterpolator;
1232
1233        public ChooserRowAdapter(ChooserListAdapter wrappedAdapter) {
1234            mChooserListAdapter = wrappedAdapter;
1235            mLayoutInflater = LayoutInflater.from(ChooserActivity.this);
1236
1237            mInterpolator = AnimationUtils.loadInterpolator(ChooserActivity.this,
1238                    android.R.interpolator.decelerate_quint);
1239
1240            wrappedAdapter.registerDataSetObserver(new DataSetObserver() {
1241                @Override
1242                public void onChanged() {
1243                    super.onChanged();
1244                    final int rcount = getServiceTargetRowCount();
1245                    if (mServiceTargetScale == null
1246                            || mServiceTargetScale.length != rcount) {
1247                        RowScale[] old = mServiceTargetScale;
1248                        int oldRCount = old != null ? old.length : 0;
1249                        mServiceTargetScale = new RowScale[rcount];
1250                        if (old != null && rcount > 0) {
1251                            System.arraycopy(old, 0, mServiceTargetScale, 0,
1252                                    Math.min(old.length, rcount));
1253                        }
1254
1255                        for (int i = rcount; i < oldRCount; i++) {
1256                            old[i].cancelAnimation();
1257                        }
1258
1259                        for (int i = oldRCount; i < rcount; i++) {
1260                            final RowScale rs = new RowScale(ChooserRowAdapter.this, 0.f, 1.f)
1261                                    .setInterpolator(mInterpolator);
1262                            mServiceTargetScale[i] = rs;
1263                        }
1264
1265                        // Start the animations in a separate loop.
1266                        // The process of starting animations will result in
1267                        // binding views to set up initial values, and we must
1268                        // have ALL of the new RowScale objects created above before
1269                        // we get started.
1270                        for (int i = oldRCount; i < rcount; i++) {
1271                            mServiceTargetScale[i].startAnimation();
1272                        }
1273                    }
1274
1275                    notifyDataSetChanged();
1276                }
1277
1278                @Override
1279                public void onInvalidated() {
1280                    super.onInvalidated();
1281                    notifyDataSetInvalidated();
1282                    if (mServiceTargetScale != null) {
1283                        for (RowScale rs : mServiceTargetScale) {
1284                            rs.cancelAnimation();
1285                        }
1286                    }
1287                }
1288            });
1289        }
1290
1291        private float getRowScale(int rowPosition) {
1292            final int start = getCallerTargetRowCount();
1293            final int end = start + getServiceTargetRowCount();
1294            if (rowPosition >= start && rowPosition < end) {
1295                return mServiceTargetScale[rowPosition - start].get();
1296            }
1297            return 1.f;
1298        }
1299
1300        @Override
1301        public int getCount() {
1302            return (int) (
1303                    getCallerTargetRowCount()
1304                    + getServiceTargetRowCount()
1305                    + Math.ceil((float) mChooserListAdapter.getStandardTargetCount() / mColumnCount)
1306            );
1307        }
1308
1309        public int getCallerTargetRowCount() {
1310            return (int) Math.ceil(
1311                    (float) mChooserListAdapter.getCallerTargetCount() / mColumnCount);
1312        }
1313
1314        public int getServiceTargetRowCount() {
1315            return (int) Math.ceil(
1316                    (float) mChooserListAdapter.getServiceTargetCount() / mColumnCount);
1317        }
1318
1319        @Override
1320        public Object getItem(int position) {
1321            // We have nothing useful to return here.
1322            return position;
1323        }
1324
1325        @Override
1326        public long getItemId(int position) {
1327            return position;
1328        }
1329
1330        @Override
1331        public View getView(int position, View convertView, ViewGroup parent) {
1332            final RowViewHolder holder;
1333            if (convertView == null) {
1334                holder = createViewHolder(parent);
1335            } else {
1336                holder = (RowViewHolder) convertView.getTag();
1337            }
1338            bindViewHolder(position, holder);
1339
1340            return holder.row;
1341        }
1342
1343        RowViewHolder createViewHolder(ViewGroup parent) {
1344            final ViewGroup row = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row,
1345                    parent, false);
1346            final RowViewHolder holder = new RowViewHolder(row, mColumnCount);
1347            final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1348
1349            for (int i = 0; i < mColumnCount; i++) {
1350                final View v = mChooserListAdapter.createView(row);
1351                final int column = i;
1352                v.setOnClickListener(new OnClickListener() {
1353                    @Override
1354                    public void onClick(View v) {
1355                        startSelected(holder.itemIndices[column], false, true);
1356                    }
1357                });
1358                v.setOnLongClickListener(new OnLongClickListener() {
1359                    @Override
1360                    public boolean onLongClick(View v) {
1361                        showTargetDetails(
1362                                mChooserListAdapter.resolveInfoForPosition(
1363                                        holder.itemIndices[column], true));
1364                        return true;
1365                    }
1366                });
1367                row.addView(v);
1368                holder.cells[i] = v;
1369
1370                // Force height to be a given so we don't have visual disruption during scaling.
1371                LayoutParams lp = v.getLayoutParams();
1372                v.measure(spec, spec);
1373                if (lp == null) {
1374                    lp = new LayoutParams(LayoutParams.MATCH_PARENT, v.getMeasuredHeight());
1375                    row.setLayoutParams(lp);
1376                } else {
1377                    lp.height = v.getMeasuredHeight();
1378                }
1379            }
1380
1381            // Pre-measure so we can scale later.
1382            holder.measure();
1383            LayoutParams lp = row.getLayoutParams();
1384            if (lp == null) {
1385                lp = new LayoutParams(LayoutParams.MATCH_PARENT, holder.measuredRowHeight);
1386                row.setLayoutParams(lp);
1387            } else {
1388                lp.height = holder.measuredRowHeight;
1389            }
1390            row.setTag(holder);
1391            return holder;
1392        }
1393
1394        void bindViewHolder(int rowPosition, RowViewHolder holder) {
1395            final int start = getFirstRowPosition(rowPosition);
1396            final int startType = mChooserListAdapter.getPositionTargetType(start);
1397
1398            int end = start + mColumnCount - 1;
1399            while (mChooserListAdapter.getPositionTargetType(end) != startType && end >= start) {
1400                end--;
1401            }
1402
1403            if (startType == ChooserListAdapter.TARGET_SERVICE) {
1404                holder.row.setBackgroundColor(
1405                        getColor(R.color.chooser_service_row_background_color));
1406            } else {
1407                holder.row.setBackgroundColor(Color.TRANSPARENT);
1408            }
1409
1410            final int oldHeight = holder.row.getLayoutParams().height;
1411            holder.row.getLayoutParams().height = Math.max(1,
1412                    (int) (holder.measuredRowHeight * getRowScale(rowPosition)));
1413            if (holder.row.getLayoutParams().height != oldHeight) {
1414                holder.row.requestLayout();
1415            }
1416
1417            for (int i = 0; i < mColumnCount; i++) {
1418                final View v = holder.cells[i];
1419                if (start + i <= end) {
1420                    v.setVisibility(View.VISIBLE);
1421                    holder.itemIndices[i] = start + i;
1422                    mChooserListAdapter.bindView(holder.itemIndices[i], v);
1423                } else {
1424                    v.setVisibility(View.GONE);
1425                }
1426            }
1427        }
1428
1429        int getFirstRowPosition(int row) {
1430            final int callerCount = mChooserListAdapter.getCallerTargetCount();
1431            final int callerRows = (int) Math.ceil((float) callerCount / mColumnCount);
1432
1433            if (row < callerRows) {
1434                return row * mColumnCount;
1435            }
1436
1437            final int serviceCount = mChooserListAdapter.getServiceTargetCount();
1438            final int serviceRows = (int) Math.ceil((float) serviceCount / mColumnCount);
1439
1440            if (row < callerRows + serviceRows) {
1441                return callerCount + (row - callerRows) * mColumnCount;
1442            }
1443
1444            return callerCount + serviceCount
1445                    + (row - callerRows - serviceRows) * mColumnCount;
1446        }
1447    }
1448
1449    static class RowViewHolder {
1450        final View[] cells;
1451        final ViewGroup row;
1452        int measuredRowHeight;
1453        int[] itemIndices;
1454
1455        public RowViewHolder(ViewGroup row, int cellCount) {
1456            this.row = row;
1457            this.cells = new View[cellCount];
1458            this.itemIndices = new int[cellCount];
1459        }
1460
1461        public void measure() {
1462            final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1463            row.measure(spec, spec);
1464            measuredRowHeight = row.getMeasuredHeight();
1465        }
1466    }
1467
1468    static class ChooserTargetServiceConnection implements ServiceConnection {
1469        private DisplayResolveInfo mOriginalTarget;
1470        private ComponentName mConnectedComponent;
1471        private ChooserActivity mChooserActivity;
1472        private final Object mLock = new Object();
1473
1474        private final IChooserTargetResult mChooserTargetResult = new IChooserTargetResult.Stub() {
1475            @Override
1476            public void sendResult(List<ChooserTarget> targets) throws RemoteException {
1477                synchronized (mLock) {
1478                    if (mChooserActivity == null) {
1479                        Log.e(TAG, "destroyed ChooserTargetServiceConnection received result from "
1480                                + mConnectedComponent + "; ignoring...");
1481                        return;
1482                    }
1483                    mChooserActivity.filterServiceTargets(
1484                            mOriginalTarget.getResolveInfo().activityInfo.packageName, targets);
1485                    final Message msg = Message.obtain();
1486                    msg.what = CHOOSER_TARGET_SERVICE_RESULT;
1487                    msg.obj = new ServiceResultInfo(mOriginalTarget, targets,
1488                            ChooserTargetServiceConnection.this);
1489                    mChooserActivity.mChooserHandler.sendMessage(msg);
1490                }
1491            }
1492        };
1493
1494        public ChooserTargetServiceConnection(ChooserActivity chooserActivity,
1495                DisplayResolveInfo dri) {
1496            mChooserActivity = chooserActivity;
1497            mOriginalTarget = dri;
1498        }
1499
1500        @Override
1501        public void onServiceConnected(ComponentName name, IBinder service) {
1502            if (DEBUG) Log.d(TAG, "onServiceConnected: " + name);
1503            synchronized (mLock) {
1504                if (mChooserActivity == null) {
1505                    Log.e(TAG, "destroyed ChooserTargetServiceConnection got onServiceConnected");
1506                    return;
1507                }
1508
1509                final IChooserTargetService icts = IChooserTargetService.Stub.asInterface(service);
1510                try {
1511                    icts.getChooserTargets(mOriginalTarget.getResolvedComponentName(),
1512                            mOriginalTarget.getResolveInfo().filter, mChooserTargetResult);
1513                } catch (RemoteException e) {
1514                    Log.e(TAG, "Querying ChooserTargetService " + name + " failed.", e);
1515                    mChooserActivity.unbindService(this);
1516                    destroy();
1517                    mChooserActivity.mServiceConnections.remove(this);
1518                }
1519            }
1520        }
1521
1522        @Override
1523        public void onServiceDisconnected(ComponentName name) {
1524            if (DEBUG) Log.d(TAG, "onServiceDisconnected: " + name);
1525            synchronized (mLock) {
1526                if (mChooserActivity == null) {
1527                    Log.e(TAG,
1528                            "destroyed ChooserTargetServiceConnection got onServiceDisconnected");
1529                    return;
1530                }
1531
1532                mChooserActivity.unbindService(this);
1533                destroy();
1534                mChooserActivity.mServiceConnections.remove(this);
1535                if (mChooserActivity.mServiceConnections.isEmpty()) {
1536                    mChooserActivity.mChooserHandler.removeMessages(
1537                            CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
1538                    mChooserActivity.sendVoiceChoicesIfNeeded();
1539                }
1540                mConnectedComponent = null;
1541            }
1542        }
1543
1544        public void destroy() {
1545            synchronized (mLock) {
1546                mChooserActivity = null;
1547                mOriginalTarget = null;
1548            }
1549        }
1550
1551        @Override
1552        public String toString() {
1553            return "ChooserTargetServiceConnection{service="
1554                    + mConnectedComponent + ", activity="
1555                    + (mOriginalTarget != null
1556                    ? mOriginalTarget.getResolveInfo().activityInfo.toString()
1557                    : "<connection destroyed>") + "}";
1558        }
1559    }
1560
1561    static class ServiceResultInfo {
1562        public final DisplayResolveInfo originalTarget;
1563        public final List<ChooserTarget> resultTargets;
1564        public final ChooserTargetServiceConnection connection;
1565
1566        public ServiceResultInfo(DisplayResolveInfo ot, List<ChooserTarget> rt,
1567                ChooserTargetServiceConnection c) {
1568            originalTarget = ot;
1569            resultTargets = rt;
1570            connection = c;
1571        }
1572    }
1573
1574    static class RefinementResultReceiver extends ResultReceiver {
1575        private ChooserActivity mChooserActivity;
1576        private TargetInfo mSelectedTarget;
1577
1578        public RefinementResultReceiver(ChooserActivity host, TargetInfo target,
1579                Handler handler) {
1580            super(handler);
1581            mChooserActivity = host;
1582            mSelectedTarget = target;
1583        }
1584
1585        @Override
1586        protected void onReceiveResult(int resultCode, Bundle resultData) {
1587            if (mChooserActivity == null) {
1588                Log.e(TAG, "Destroyed RefinementResultReceiver received a result");
1589                return;
1590            }
1591            if (resultData == null) {
1592                Log.e(TAG, "RefinementResultReceiver received null resultData");
1593                return;
1594            }
1595
1596            switch (resultCode) {
1597                case RESULT_CANCELED:
1598                    mChooserActivity.onRefinementCanceled();
1599                    break;
1600                case RESULT_OK:
1601                    Parcelable intentParcelable = resultData.getParcelable(Intent.EXTRA_INTENT);
1602                    if (intentParcelable instanceof Intent) {
1603                        mChooserActivity.onRefinementResult(mSelectedTarget,
1604                                (Intent) intentParcelable);
1605                    } else {
1606                        Log.e(TAG, "RefinementResultReceiver received RESULT_OK but no Intent"
1607                                + " in resultData with key Intent.EXTRA_INTENT");
1608                    }
1609                    break;
1610                default:
1611                    Log.w(TAG, "Unknown result code " + resultCode
1612                            + " sent to RefinementResultReceiver");
1613                    break;
1614            }
1615        }
1616
1617        public void destroy() {
1618            mChooserActivity = null;
1619            mSelectedTarget = null;
1620        }
1621    }
1622
1623    class OffsetDataSetObserver extends DataSetObserver {
1624        private final AbsListView mListView;
1625        private int mCachedViewType = -1;
1626        private View mCachedView;
1627
1628        public OffsetDataSetObserver(AbsListView listView) {
1629            mListView = listView;
1630        }
1631
1632        @Override
1633        public void onChanged() {
1634            if (mResolverDrawerLayout == null) {
1635                return;
1636            }
1637
1638            final int chooserTargetRows = mChooserRowAdapter.getServiceTargetRowCount();
1639            int offset = 0;
1640            for (int i = 0; i < chooserTargetRows; i++)  {
1641                final int pos = mChooserRowAdapter.getCallerTargetRowCount() + i;
1642                final int vt = mChooserRowAdapter.getItemViewType(pos);
1643                if (vt != mCachedViewType) {
1644                    mCachedView = null;
1645                }
1646                final View v = mChooserRowAdapter.getView(pos, mCachedView, mListView);
1647                int height = ((RowViewHolder) (v.getTag())).measuredRowHeight;
1648
1649                offset += (int) (height * mChooserRowAdapter.getRowScale(pos));
1650
1651                if (vt >= 0) {
1652                    mCachedViewType = vt;
1653                    mCachedView = v;
1654                } else {
1655                    mCachedViewType = -1;
1656                }
1657            }
1658
1659            mResolverDrawerLayout.setCollapsibleHeightReserved(offset);
1660        }
1661    }
1662}
1663