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