2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.internal.app;
19 import android.animation.ObjectAnimator;
20 import android.annotation.NonNull;
21 import android.app.Activity;
22 import android.content.ComponentName;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.IntentSender;
26 import android.content.IntentSender.SendIntentException;
27 import android.content.ServiceConnection;
28 import android.content.pm.ActivityInfo;
29 import android.content.pm.LabeledIntent;
30 import android.content.pm.PackageManager;
31 import android.content.pm.PackageManager.NameNotFoundException;
32 import android.content.pm.ResolveInfo;
33 import android.database.DataSetObserver;
34 import android.graphics.Color;
35 import android.graphics.drawable.Drawable;
36 import android.graphics.drawable.Icon;
37 import android.os.Bundle;
38 import android.os.Handler;
39 import android.os.IBinder;
40 import android.os.Message;
41 import android.os.Parcelable;
42 import android.os.RemoteException;
43 import android.os.ResultReceiver;
44 import android.os.UserHandle;
45 import android.os.UserManager;
46 import android.provider.DocumentsContract;
47 import android.service.chooser.ChooserTarget;
48 import android.service.chooser.ChooserTargetService;
49 import android.service.chooser.IChooserTargetResult;
50 import android.service.chooser.IChooserTargetService;
51 import android.text.TextUtils;
52 import android.util.FloatProperty;
53 import android.util.Log;
54 import android.util.Slog;
55 import android.view.LayoutInflater;
56 import android.view.View;
57 import android.view.View.MeasureSpec;
58 import android.view.View.OnClickListener;
59 import android.view.View.OnLongClickListener;
60 import android.view.ViewGroup;
61 import android.view.ViewGroup.LayoutParams;
62 import android.view.animation.AnimationUtils;
63 import android.view.animation.Interpolator;
64 import android.widget.AbsListView;
65 import android.widget.BaseAdapter;
66 import android.widget.ListView;
67 import com.android.internal.R;
68 import com.android.internal.logging.MetricsLogger;
70 import java.util.ArrayList;
71 import java.util.Collections;
72 import java.util.Comparator;
73 import java.util.List;
75 public class ChooserActivity extends ResolverActivity {
76 private static final String TAG = "ChooserActivity";
78 private static final boolean DEBUG = false;
80 private static final int QUERY_TARGET_SERVICE_LIMIT = 5;
81 private static final int WATCHDOG_TIMEOUT_MILLIS = 5000;
83 private Bundle mReplacementExtras;
84 private IntentSender mChosenComponentSender;
85 private IntentSender mRefinementIntentSender;
86 private RefinementResultReceiver mRefinementResultReceiver;
88 private Intent mReferrerFillInIntent;
90 private ChooserListAdapter mChooserListAdapter;
91 private ChooserRowAdapter mChooserRowAdapter;
93 private final List<ChooserTargetServiceConnection> mServiceConnections = new ArrayList<>();
95 private static final int CHOOSER_TARGET_SERVICE_RESULT = 1;
96 private static final int CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT = 2;
98 private final Handler mChooserHandler = new Handler() {
100 public void handleMessage(Message msg) {
102 case CHOOSER_TARGET_SERVICE_RESULT:
103 if (DEBUG) Log.d(TAG, "CHOOSER_TARGET_SERVICE_RESULT");
104 if (isDestroyed()) break;
105 final ServiceResultInfo sri = (ServiceResultInfo) msg.obj;
106 if (!mServiceConnections.contains(sri.connection)) {
107 Log.w(TAG, "ChooserTargetServiceConnection " + sri.connection
108 + " returned after being removed from active connections."
109 + " Have you considered returning results faster?");
112 if (sri.resultTargets != null) {
113 mChooserListAdapter.addServiceResults(sri.originalTarget,
116 unbindService(sri.connection);
117 sri.connection.destroy();
118 mServiceConnections.remove(sri.connection);
119 if (mServiceConnections.isEmpty()) {
120 mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
121 sendVoiceChoicesIfNeeded();
125 case CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT:
127 Log.d(TAG, "CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT; unbinding services");
129 unbindRemainingServices();
130 sendVoiceChoicesIfNeeded();
134 super.handleMessage(msg);
140 protected void onCreate(Bundle savedInstanceState) {
141 Intent intent = getIntent();
142 Parcelable targetParcelable = intent.getParcelableExtra(Intent.EXTRA_INTENT);
143 if (!(targetParcelable instanceof Intent)) {
144 Log.w("ChooserActivity", "Target is not an intent: " + targetParcelable);
146 super.onCreate(null);
149 Intent target = (Intent) targetParcelable;
150 if (target != null) {
151 modifyTargetIntent(target);
153 Parcelable[] targetsParcelable
154 = intent.getParcelableArrayExtra(Intent.EXTRA_ALTERNATE_INTENTS);
155 if (targetsParcelable != null) {
156 final boolean offset = target == null;
157 Intent[] additionalTargets =
158 new Intent[offset ? targetsParcelable.length - 1 : targetsParcelable.length];
159 for (int i = 0; i < targetsParcelable.length; i++) {
160 if (!(targetsParcelable[i] instanceof Intent)) {
161 Log.w(TAG, "EXTRA_ALTERNATE_INTENTS array entry #" + i + " is not an Intent: "
162 + targetsParcelable[i]);
164 super.onCreate(null);
167 final Intent additionalTarget = (Intent) targetsParcelable[i];
168 if (i == 0 && target == null) {
169 target = additionalTarget;
170 modifyTargetIntent(target);
172 additionalTargets[offset ? i - 1 : i] = additionalTarget;
173 modifyTargetIntent(additionalTarget);
176 setAdditionalTargets(additionalTargets);
179 mReplacementExtras = intent.getBundleExtra(Intent.EXTRA_REPLACEMENT_EXTRAS);
180 CharSequence title = intent.getCharSequenceExtra(Intent.EXTRA_TITLE);
181 int defaultTitleRes = 0;
183 defaultTitleRes = com.android.internal.R.string.chooseActivity;
185 Parcelable[] pa = intent.getParcelableArrayExtra(Intent.EXTRA_INITIAL_INTENTS);
186 Intent[] initialIntents = null;
188 initialIntents = new Intent[pa.length];
189 for (int i=0; i<pa.length; i++) {
190 if (!(pa[i] instanceof Intent)) {
191 Log.w(TAG, "Initial intent #" + i + " not an Intent: " + pa[i]);
193 super.onCreate(null);
196 final Intent in = (Intent) pa[i];
197 modifyTargetIntent(in);
198 initialIntents[i] = in;
202 mReferrerFillInIntent = new Intent().putExtra(Intent.EXTRA_REFERRER, getReferrer());
204 mChosenComponentSender = intent.getParcelableExtra(
205 Intent.EXTRA_CHOSEN_COMPONENT_INTENT_SENDER);
206 mRefinementIntentSender = intent.getParcelableExtra(
207 Intent.EXTRA_CHOOSER_REFINEMENT_INTENT_SENDER);
208 setSafeForwardingMode(true);
209 super.onCreate(savedInstanceState, target, title, defaultTitleRes, initialIntents,
212 MetricsLogger.action(this, MetricsLogger.ACTION_ACTIVITY_CHOOSER_SHOWN);
216 protected void onDestroy() {
218 if (mRefinementResultReceiver != null) {
219 mRefinementResultReceiver.destroy();
220 mRefinementResultReceiver = null;
222 unbindRemainingServices();
223 mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_RESULT);
227 public Intent getReplacementIntent(ActivityInfo aInfo, Intent defIntent) {
228 Intent result = defIntent;
229 if (mReplacementExtras != null) {
230 final Bundle replExtras = mReplacementExtras.getBundle(aInfo.packageName);
231 if (replExtras != null) {
232 result = new Intent(defIntent);
233 result.putExtras(replExtras);
236 if (aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER)
237 || aInfo.name.equals(IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE)) {
238 result = Intent.createChooser(result,
239 getIntent().getCharSequenceExtra(Intent.EXTRA_TITLE));
245 void onActivityStarted(TargetInfo cti) {
246 if (mChosenComponentSender != null) {
247 final ComponentName target = cti.getResolvedComponentName();
248 if (target != null) {
249 final Intent fillIn = new Intent().putExtra(Intent.EXTRA_CHOSEN_COMPONENT, target);
251 mChosenComponentSender.sendIntent(this, Activity.RESULT_OK, fillIn, null, null);
252 } catch (IntentSender.SendIntentException e) {
253 Slog.e(TAG, "Unable to launch supplied IntentSender to report "
254 + "the chosen component: " + e);
261 void onPrepareAdapterView(AbsListView adapterView, ResolveListAdapter adapter,
262 boolean alwaysUseOption) {
263 final ListView listView = adapterView instanceof ListView ? (ListView) adapterView : null;
264 mChooserListAdapter = (ChooserListAdapter) adapter;
265 mChooserRowAdapter = new ChooserRowAdapter(mChooserListAdapter);
266 mChooserRowAdapter.registerDataSetObserver(new OffsetDataSetObserver(adapterView));
267 adapterView.setAdapter(mChooserRowAdapter);
268 if (listView != null) {
269 listView.setItemsCanFocus(true);
274 int getLayoutResource() {
275 return R.layout.chooser_grid;
279 boolean shouldGetActivityMetadata() {
284 boolean shouldAutoLaunchSingleChoice(TargetInfo target) {
285 final Intent intent = target.getResolvedIntent();
286 final ResolveInfo resolve = target.getResolveInfo();
288 // When GET_CONTENT is handled by the DocumentsUI system component,
289 // we're okay automatically launching it, since it offers it's own
290 // intent disambiguation UI.
291 if (intent != null && Intent.ACTION_GET_CONTENT.equals(intent.getAction())
292 && resolve != null && resolve.priority > 0
293 && resolve.activityInfo != null && DocumentsContract.PACKAGE_DOCUMENTS_UI
294 .equals(resolve.activityInfo.packageName)) {
301 private void modifyTargetIntent(Intent in) {
302 final String action = in.getAction();
303 if (Intent.ACTION_SEND.equals(action) ||
304 Intent.ACTION_SEND_MULTIPLE.equals(action)) {
305 in.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
306 Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
311 protected boolean onTargetSelected(TargetInfo target, boolean alwaysCheck) {
312 if (mRefinementIntentSender != null) {
313 final Intent fillIn = new Intent();
314 final List<Intent> sourceIntents = target.getAllSourceIntents();
315 if (!sourceIntents.isEmpty()) {
316 fillIn.putExtra(Intent.EXTRA_INTENT, sourceIntents.get(0));
317 if (sourceIntents.size() > 1) {
318 final Intent[] alts = new Intent[sourceIntents.size() - 1];
319 for (int i = 1, N = sourceIntents.size(); i < N; i++) {
320 alts[i - 1] = sourceIntents.get(i);
322 fillIn.putExtra(Intent.EXTRA_ALTERNATE_INTENTS, alts);
324 if (mRefinementResultReceiver != null) {
325 mRefinementResultReceiver.destroy();
327 mRefinementResultReceiver = new RefinementResultReceiver(this, target, null);
328 fillIn.putExtra(Intent.EXTRA_RESULT_RECEIVER,
329 mRefinementResultReceiver);
331 mRefinementIntentSender.sendIntent(this, 0, fillIn, null, null);
333 } catch (SendIntentException e) {
334 Log.e(TAG, "Refinement IntentSender failed to send", e);
338 return super.onTargetSelected(target, alwaysCheck);
342 void startSelected(int which, boolean always, boolean filtered) {
343 super.startSelected(which, always, filtered);
345 if (mChooserListAdapter != null) {
346 // Log the index of which type of target the user picked.
347 // Lower values mean the ranking was better.
350 switch (mChooserListAdapter.getPositionTargetType(which)) {
351 case ChooserListAdapter.TARGET_CALLER:
352 cat = MetricsLogger.ACTION_ACTIVITY_CHOOSER_PICKED_APP_TARGET;
354 case ChooserListAdapter.TARGET_SERVICE:
355 cat = MetricsLogger.ACTION_ACTIVITY_CHOOSER_PICKED_SERVICE_TARGET;
356 value -= mChooserListAdapter.getCallerTargetCount();
358 case ChooserListAdapter.TARGET_STANDARD:
359 cat = MetricsLogger.ACTION_ACTIVITY_CHOOSER_PICKED_STANDARD_TARGET;
360 value -= mChooserListAdapter.getCallerTargetCount()
361 + mChooserListAdapter.getServiceTargetCount();
366 MetricsLogger.action(this, cat, value);
371 void queryTargetServices(ChooserListAdapter adapter) {
372 final PackageManager pm = getPackageManager();
373 int targetsToQuery = 0;
374 for (int i = 0, N = adapter.getDisplayResolveInfoCount(); i < N; i++) {
375 final DisplayResolveInfo dri = adapter.getDisplayResolveInfo(i);
376 if (adapter.getScore(dri) == 0) {
377 // A score of 0 means the app hasn't been used in some time;
378 // don't query it as it's not likely to be relevant.
381 final ActivityInfo ai = dri.getResolveInfo().activityInfo;
382 final Bundle md = ai.metaData;
383 final String serviceName = md != null ? convertServiceName(ai.packageName,
384 md.getString(ChooserTargetService.META_DATA_NAME)) : null;
385 if (serviceName != null) {
386 final ComponentName serviceComponent = new ComponentName(
387 ai.packageName, serviceName);
388 final Intent serviceIntent = new Intent(ChooserTargetService.SERVICE_INTERFACE)
389 .setComponent(serviceComponent);
392 Log.d(TAG, "queryTargets found target with service " + serviceComponent);
396 final String perm = pm.getServiceInfo(serviceComponent, 0).permission;
397 if (!ChooserTargetService.BIND_PERMISSION.equals(perm)) {
398 Log.w(TAG, "ChooserTargetService " + serviceComponent + " does not require"
399 + " permission " + ChooserTargetService.BIND_PERMISSION
400 + " - this service will not be queried for ChooserTargets."
401 + " add android:permission=\""
402 + ChooserTargetService.BIND_PERMISSION + "\""
403 + " to the <service> tag for " + serviceComponent
404 + " in the manifest.");
407 } catch (NameNotFoundException e) {
408 Log.e(TAG, "Could not look up service " + serviceComponent, e);
412 final ChooserTargetServiceConnection conn =
413 new ChooserTargetServiceConnection(this, dri);
414 if (bindServiceAsUser(serviceIntent, conn, BIND_AUTO_CREATE | BIND_NOT_FOREGROUND,
415 UserHandle.CURRENT)) {
417 Log.d(TAG, "Binding service connection for target " + dri
418 + " intent " + serviceIntent);
420 mServiceConnections.add(conn);
424 if (targetsToQuery >= QUERY_TARGET_SERVICE_LIMIT) {
425 if (DEBUG) Log.d(TAG, "queryTargets hit query target limit "
426 + QUERY_TARGET_SERVICE_LIMIT);
431 if (!mServiceConnections.isEmpty()) {
432 if (DEBUG) Log.d(TAG, "queryTargets setting watchdog timer for "
433 + WATCHDOG_TIMEOUT_MILLIS + "ms");
434 mChooserHandler.sendEmptyMessageDelayed(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT,
435 WATCHDOG_TIMEOUT_MILLIS);
437 sendVoiceChoicesIfNeeded();
441 private String convertServiceName(String packageName, String serviceName) {
442 if (TextUtils.isEmpty(serviceName)) {
446 final String fullName;
447 if (serviceName.startsWith(".")) {
448 // Relative to the app package. Prepend the app package name.
449 fullName = packageName + serviceName;
450 } else if (serviceName.indexOf('.') >= 0) {
451 // Fully qualified package name.
452 fullName = serviceName;
459 void unbindRemainingServices() {
461 Log.d(TAG, "unbindRemainingServices, " + mServiceConnections.size() + " left");
463 for (int i = 0, N = mServiceConnections.size(); i < N; i++) {
464 final ChooserTargetServiceConnection conn = mServiceConnections.get(i);
465 if (DEBUG) Log.d(TAG, "unbinding " + conn);
469 mServiceConnections.clear();
470 mChooserHandler.removeMessages(CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
473 void onSetupVoiceInteraction() {
474 // Do nothing. We'll send the voice stuff ourselves.
477 void onRefinementResult(TargetInfo selectedTarget, Intent matchingIntent) {
478 if (mRefinementResultReceiver != null) {
479 mRefinementResultReceiver.destroy();
480 mRefinementResultReceiver = null;
483 if (selectedTarget == null) {
484 Log.e(TAG, "Refinement result intent did not match any known targets; canceling");
485 } else if (!checkTargetSourceIntent(selectedTarget, matchingIntent)) {
486 Log.e(TAG, "onRefinementResult: Selected target " + selectedTarget
487 + " cannot match refined source intent " + matchingIntent);
488 } else if (super.onTargetSelected(selectedTarget.cloneFilledIn(matchingIntent, 0), false)) {
492 onRefinementCanceled();
495 void onRefinementCanceled() {
496 if (mRefinementResultReceiver != null) {
497 mRefinementResultReceiver.destroy();
498 mRefinementResultReceiver = null;
503 boolean checkTargetSourceIntent(TargetInfo target, Intent matchingIntent) {
504 final List<Intent> targetIntents = target.getAllSourceIntents();
505 for (int i = 0, N = targetIntents.size(); i < N; i++) {
506 final Intent targetIntent = targetIntents.get(i);
507 if (targetIntent.filterEquals(matchingIntent)) {
514 void filterServiceTargets(String packageName, List<ChooserTarget> targets) {
515 if (targets == null) {
519 final PackageManager pm = getPackageManager();
520 for (int i = targets.size() - 1; i >= 0; i--) {
521 final ChooserTarget target = targets.get(i);
522 final ComponentName targetName = target.getComponentName();
523 if (packageName != null && packageName.equals(targetName.getPackageName())) {
524 // Anything from the original target's package is fine.
530 final ActivityInfo ai = pm.getActivityInfo(targetName, 0);
531 remove = !ai.exported || ai.permission != null;
532 } catch (NameNotFoundException e) {
533 Log.e(TAG, "Target " + target + " returned by " + packageName
534 + " component not found");
545 ResolveListAdapter createAdapter(Context context, List<Intent> payloadIntents,
546 Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
547 boolean filterLastUsed) {
548 final ChooserListAdapter adapter = new ChooserListAdapter(context, payloadIntents,
549 initialIntents, rList, launchedFromUid, filterLastUsed);
550 if (DEBUG) Log.d(TAG, "Adapter created; querying services");
551 queryTargetServices(adapter);
555 final class ChooserTargetInfo implements TargetInfo {
556 private final DisplayResolveInfo mSourceInfo;
557 private final ResolveInfo mBackupResolveInfo;
558 private final ChooserTarget mChooserTarget;
559 private Drawable mBadgeIcon = null;
560 private CharSequence mBadgeContentDescription;
561 private Drawable mDisplayIcon;
562 private final Intent mFillInIntent;
563 private final int mFillInFlags;
564 private final float mModifiedScore;
566 public ChooserTargetInfo(DisplayResolveInfo sourceInfo, ChooserTarget chooserTarget,
567 float modifiedScore) {
568 mSourceInfo = sourceInfo;
569 mChooserTarget = chooserTarget;
570 mModifiedScore = modifiedScore;
571 if (sourceInfo != null) {
572 final ResolveInfo ri = sourceInfo.getResolveInfo();
574 final ActivityInfo ai = ri.activityInfo;
575 if (ai != null && ai.applicationInfo != null) {
576 final PackageManager pm = getPackageManager();
577 mBadgeIcon = pm.getApplicationIcon(ai.applicationInfo);
578 mBadgeContentDescription = pm.getApplicationLabel(ai.applicationInfo);
582 final Icon icon = chooserTarget.getIcon();
583 // TODO do this in the background
584 mDisplayIcon = icon != null ? icon.loadDrawable(ChooserActivity.this) : null;
586 if (sourceInfo != null) {
587 mBackupResolveInfo = null;
589 mBackupResolveInfo = getPackageManager().resolveActivity(getResolvedIntent(), 0);
592 mFillInIntent = null;
596 private ChooserTargetInfo(ChooserTargetInfo other, Intent fillInIntent, int flags) {
597 mSourceInfo = other.mSourceInfo;
598 mBackupResolveInfo = other.mBackupResolveInfo;
599 mChooserTarget = other.mChooserTarget;
600 mBadgeIcon = other.mBadgeIcon;
601 mBadgeContentDescription = other.mBadgeContentDescription;
602 mDisplayIcon = other.mDisplayIcon;
603 mFillInIntent = fillInIntent;
604 mFillInFlags = flags;
605 mModifiedScore = other.mModifiedScore;
608 public float getModifiedScore() {
609 return mModifiedScore;
613 public Intent getResolvedIntent() {
614 if (mSourceInfo != null) {
615 return mSourceInfo.getResolvedIntent();
617 return getTargetIntent();
621 public ComponentName getResolvedComponentName() {
622 if (mSourceInfo != null) {
623 return mSourceInfo.getResolvedComponentName();
624 } else if (mBackupResolveInfo != null) {
625 return new ComponentName(mBackupResolveInfo.activityInfo.packageName,
626 mBackupResolveInfo.activityInfo.name);
631 private Intent getBaseIntentToSend() {
632 Intent result = mSourceInfo != null
633 ? mSourceInfo.getResolvedIntent() : getTargetIntent();
634 if (result == null) {
635 Log.e(TAG, "ChooserTargetInfo: no base intent available to send");
637 result = new Intent(result);
638 if (mFillInIntent != null) {
639 result.fillIn(mFillInIntent, mFillInFlags);
641 result.fillIn(mReferrerFillInIntent, 0);
647 public boolean start(Activity activity, Bundle options) {
648 throw new RuntimeException("ChooserTargets should be started as caller.");
652 public boolean startAsCaller(Activity activity, Bundle options, int userId) {
653 final Intent intent = getBaseIntentToSend();
654 if (intent == null) {
657 intent.setComponent(mChooserTarget.getComponentName());
658 intent.putExtras(mChooserTarget.getIntentExtras());
660 // Important: we will ignore the target security checks in ActivityManager
661 // if and only if the ChooserTarget's target package is the same package
662 // where we got the ChooserTargetService that provided it. This lets a
663 // ChooserTargetService provide a non-exported or permission-guarded target
664 // to the chooser for the user to pick.
666 // If mSourceInfo is null, we got this ChooserTarget from the caller or elsewhere
667 // so we'll obey the caller's normal security checks.
668 final boolean ignoreTargetSecurity = mSourceInfo != null
669 && mSourceInfo.getResolvedComponentName().getPackageName()
670 .equals(mChooserTarget.getComponentName().getPackageName());
671 activity.startActivityAsCaller(intent, options, ignoreTargetSecurity, userId);
676 public boolean startAsUser(Activity activity, Bundle options, UserHandle user) {
677 throw new RuntimeException("ChooserTargets should be started as caller.");
681 public ResolveInfo getResolveInfo() {
682 return mSourceInfo != null ? mSourceInfo.getResolveInfo() : mBackupResolveInfo;
686 public CharSequence getDisplayLabel() {
687 return mChooserTarget.getTitle();
691 public CharSequence getExtendedInfo() {
692 // ChooserTargets have badge icons, so we won't show the extended info to disambiguate.
697 public Drawable getDisplayIcon() {
702 public Drawable getBadgeIcon() {
707 public CharSequence getBadgeContentDescription() {
708 return mBadgeContentDescription;
712 public TargetInfo cloneFilledIn(Intent fillInIntent, int flags) {
713 return new ChooserTargetInfo(this, fillInIntent, flags);
717 public List<Intent> getAllSourceIntents() {
718 final List<Intent> results = new ArrayList<>();
719 if (mSourceInfo != null) {
720 // We only queried the service for the first one in our sourceinfo.
721 results.add(mSourceInfo.getAllSourceIntents().get(0));
727 public class ChooserListAdapter extends ResolveListAdapter {
728 public static final int TARGET_BAD = -1;
729 public static final int TARGET_CALLER = 0;
730 public static final int TARGET_SERVICE = 1;
731 public static final int TARGET_STANDARD = 2;
733 private static final int MAX_SERVICE_TARGETS = 8;
735 private final List<ChooserTargetInfo> mServiceTargets = new ArrayList<>();
736 private final List<TargetInfo> mCallerTargets = new ArrayList<>();
738 private float mLateFee = 1.f;
740 private final BaseChooserTargetComparator mBaseTargetComparator
741 = new BaseChooserTargetComparator();
743 public ChooserListAdapter(Context context, List<Intent> payloadIntents,
744 Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
745 boolean filterLastUsed) {
746 // Don't send the initial intents through the shared ResolverActivity path,
747 // we want to separate them into a different section.
748 super(context, payloadIntents, null, rList, launchedFromUid, filterLastUsed);
750 if (initialIntents != null) {
751 final PackageManager pm = getPackageManager();
752 for (int i = 0; i < initialIntents.length; i++) {
753 final Intent ii = initialIntents[i];
757 final ActivityInfo ai = ii.resolveActivityInfo(pm, 0);
759 Log.w(TAG, "No activity found for " + ii);
762 ResolveInfo ri = new ResolveInfo();
763 ri.activityInfo = ai;
764 UserManager userManager =
765 (UserManager) getSystemService(Context.USER_SERVICE);
766 if (ii instanceof LabeledIntent) {
767 LabeledIntent li = (LabeledIntent)ii;
768 ri.resolvePackageName = li.getSourcePackage();
769 ri.labelRes = li.getLabelResource();
770 ri.nonLocalizedLabel = li.getNonLocalizedLabel();
771 ri.icon = li.getIconResource();
772 ri.iconResourceId = ri.icon;
774 if (userManager.isManagedProfile()) {
775 ri.noResourceId = true;
778 mCallerTargets.add(new DisplayResolveInfo(ii, ri,
779 ri.loadLabel(pm), null, ii));
785 public boolean showsExtendedInfo(TargetInfo info) {
786 // We have badges so we don't need this text shown.
791 public View onCreateView(ViewGroup parent) {
792 return mInflater.inflate(
793 com.android.internal.R.layout.resolve_grid_item, parent, false);
797 public void onListRebuilt() {
798 if (mServiceTargets != null) {
799 pruneServiceTargets();
804 public boolean shouldGetResolvedFilter() {
809 public int getCount() {
810 return super.getCount() + getServiceTargetCount() + getCallerTargetCount();
814 public int getUnfilteredCount() {
815 return super.getUnfilteredCount() + getServiceTargetCount() + getCallerTargetCount();
818 public int getCallerTargetCount() {
819 return mCallerTargets.size();
822 public int getServiceTargetCount() {
823 return Math.min(mServiceTargets.size(), MAX_SERVICE_TARGETS);
826 public int getStandardTargetCount() {
827 return super.getCount();
830 public int getPositionTargetType(int position) {
833 final int callerTargetCount = getCallerTargetCount();
834 if (position < callerTargetCount) {
835 return TARGET_CALLER;
837 offset += callerTargetCount;
839 final int serviceTargetCount = getServiceTargetCount();
840 if (position - offset < serviceTargetCount) {
841 return TARGET_SERVICE;
843 offset += serviceTargetCount;
845 final int standardTargetCount = super.getCount();
846 if (position - offset < standardTargetCount) {
847 return TARGET_STANDARD;
854 public TargetInfo getItem(int position) {
855 return targetInfoForPosition(position, true);
859 public TargetInfo targetInfoForPosition(int position, boolean filtered) {
862 final int callerTargetCount = getCallerTargetCount();
863 if (position < callerTargetCount) {
864 return mCallerTargets.get(position);
866 offset += callerTargetCount;
868 final int serviceTargetCount = getServiceTargetCount();
869 if (position - offset < serviceTargetCount) {
870 return mServiceTargets.get(position - offset);
872 offset += serviceTargetCount;
874 return filtered ? super.getItem(position - offset)
875 : getDisplayInfoAt(position - offset);
878 public void addServiceResults(DisplayResolveInfo origTarget, List<ChooserTarget> targets) {
879 if (DEBUG) Log.d(TAG, "addServiceResults " + origTarget + ", " + targets.size()
881 final float parentScore = getScore(origTarget);
882 Collections.sort(targets, mBaseTargetComparator);
884 for (int i = 0, N = targets.size(); i < N; i++) {
885 final ChooserTarget target = targets.get(i);
886 float targetScore = target.getScore();
887 targetScore *= parentScore;
888 targetScore *= mLateFee;
889 if (i > 0 && targetScore >= lastScore) {
890 // Apply a decay so that the top app can't crowd out everything else.
891 // This incents ChooserTargetServices to define what's truly better.
892 targetScore = lastScore * 0.95f;
894 insertServiceTarget(new ChooserTargetInfo(origTarget, target, targetScore));
897 Log.d(TAG, " => " + target.toString() + " score=" + targetScore
898 + " base=" + target.getScore()
899 + " lastScore=" + lastScore
900 + " parentScore=" + parentScore
901 + " lateFee=" + mLateFee);
904 lastScore = targetScore;
909 notifyDataSetChanged();
912 private void insertServiceTarget(ChooserTargetInfo chooserTargetInfo) {
913 final float newScore = chooserTargetInfo.getModifiedScore();
914 for (int i = 0, N = mServiceTargets.size(); i < N; i++) {
915 final ChooserTargetInfo serviceTarget = mServiceTargets.get(i);
916 if (newScore > serviceTarget.getModifiedScore()) {
917 mServiceTargets.add(i, chooserTargetInfo);
921 mServiceTargets.add(chooserTargetInfo);
924 private void pruneServiceTargets() {
925 if (DEBUG) Log.d(TAG, "pruneServiceTargets");
926 for (int i = mServiceTargets.size() - 1; i >= 0; i--) {
927 final ChooserTargetInfo cti = mServiceTargets.get(i);
928 if (!hasResolvedTarget(cti.getResolveInfo())) {
929 if (DEBUG) Log.d(TAG, " => " + i + " " + cti);
930 mServiceTargets.remove(i);
936 static class BaseChooserTargetComparator implements Comparator<ChooserTarget> {
938 public int compare(ChooserTarget lhs, ChooserTarget rhs) {
940 return (int) Math.signum(rhs.getScore() - lhs.getScore());
944 static class RowScale {
945 private static final int DURATION = 400;
948 ChooserRowAdapter mAdapter;
949 private final ObjectAnimator mAnimator;
951 public static final FloatProperty<RowScale> PROPERTY =
952 new FloatProperty<RowScale>("scale") {
954 public void setValue(RowScale object, float value) {
955 object.mScale = value;
956 object.mAdapter.notifyDataSetChanged();
960 public Float get(RowScale object) {
961 return object.mScale;
965 public RowScale(@NonNull ChooserRowAdapter adapter, float from, float to) {
973 mAnimator = ObjectAnimator.ofFloat(this, PROPERTY, from, to).setDuration(DURATION);
976 public RowScale setInterpolator(Interpolator interpolator) {
977 if (mAnimator != null) {
978 mAnimator.setInterpolator(interpolator);
987 public void startAnimation() {
988 if (mAnimator != null) {
993 public void cancelAnimation() {
994 if (mAnimator != null) {
1000 class ChooserRowAdapter extends BaseAdapter {
1001 private ChooserListAdapter mChooserListAdapter;
1002 private final LayoutInflater mLayoutInflater;
1003 private final int mColumnCount = 4;
1004 private RowScale[] mServiceTargetScale;
1005 private final Interpolator mInterpolator;
1007 public ChooserRowAdapter(ChooserListAdapter wrappedAdapter) {
1008 mChooserListAdapter = wrappedAdapter;
1009 mLayoutInflater = LayoutInflater.from(ChooserActivity.this);
1011 mInterpolator = AnimationUtils.loadInterpolator(ChooserActivity.this,
1012 android.R.interpolator.decelerate_quint);
1014 wrappedAdapter.registerDataSetObserver(new DataSetObserver() {
1016 public void onChanged() {
1018 final int rcount = getServiceTargetRowCount();
1019 if (mServiceTargetScale == null
1020 || mServiceTargetScale.length != rcount) {
1021 RowScale[] old = mServiceTargetScale;
1022 int oldRCount = old != null ? old.length : 0;
1023 mServiceTargetScale = new RowScale[rcount];
1024 if (old != null && rcount > 0) {
1025 System.arraycopy(old, 0, mServiceTargetScale, 0,
1026 Math.min(old.length, rcount));
1029 for (int i = rcount; i < oldRCount; i++) {
1030 old[i].cancelAnimation();
1033 for (int i = oldRCount; i < rcount; i++) {
1034 final RowScale rs = new RowScale(ChooserRowAdapter.this, 0.f, 1.f)
1035 .setInterpolator(mInterpolator);
1036 mServiceTargetScale[i] = rs;
1039 // Start the animations in a separate loop.
1040 // The process of starting animations will result in
1041 // binding views to set up initial values, and we must
1042 // have ALL of the new RowScale objects created above before
1044 for (int i = oldRCount; i < rcount; i++) {
1045 mServiceTargetScale[i].startAnimation();
1049 notifyDataSetChanged();
1053 public void onInvalidated() {
1054 super.onInvalidated();
1055 notifyDataSetInvalidated();
1056 if (mServiceTargetScale != null) {
1057 for (RowScale rs : mServiceTargetScale) {
1058 rs.cancelAnimation();
1065 private float getRowScale(int rowPosition) {
1066 final int start = getCallerTargetRowCount();
1067 final int end = start + getServiceTargetRowCount();
1068 if (rowPosition >= start && rowPosition < end) {
1069 return mServiceTargetScale[rowPosition - start].get();
1075 public int getCount() {
1077 getCallerTargetRowCount()
1078 + getServiceTargetRowCount()
1079 + Math.ceil((float) mChooserListAdapter.getStandardTargetCount() / mColumnCount)
1083 public int getCallerTargetRowCount() {
1084 return (int) Math.ceil(
1085 (float) mChooserListAdapter.getCallerTargetCount() / mColumnCount);
1088 public int getServiceTargetRowCount() {
1089 return (int) Math.ceil(
1090 (float) mChooserListAdapter.getServiceTargetCount() / mColumnCount);
1094 public Object getItem(int position) {
1095 // We have nothing useful to return here.
1100 public long getItemId(int position) {
1105 public View getView(int position, View convertView, ViewGroup parent) {
1106 final RowViewHolder holder;
1107 if (convertView == null) {
1108 holder = createViewHolder(parent);
1110 holder = (RowViewHolder) convertView.getTag();
1112 bindViewHolder(position, holder);
1117 RowViewHolder createViewHolder(ViewGroup parent) {
1118 final ViewGroup row = (ViewGroup) mLayoutInflater.inflate(R.layout.chooser_row,
1120 final RowViewHolder holder = new RowViewHolder(row, mColumnCount);
1121 final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1123 for (int i = 0; i < mColumnCount; i++) {
1124 final View v = mChooserListAdapter.createView(row);
1125 final int column = i;
1126 v.setOnClickListener(new OnClickListener() {
1128 public void onClick(View v) {
1129 startSelected(holder.itemIndices[column], false, true);
1132 v.setOnLongClickListener(new OnLongClickListener() {
1134 public boolean onLongClick(View v) {
1136 mChooserListAdapter.resolveInfoForPosition(
1137 holder.itemIndices[column], true));
1142 holder.cells[i] = v;
1144 // Force height to be a given so we don't have visual disruption during scaling.
1145 LayoutParams lp = v.getLayoutParams();
1146 v.measure(spec, spec);
1148 lp = new LayoutParams(LayoutParams.MATCH_PARENT, v.getMeasuredHeight());
1149 row.setLayoutParams(lp);
1151 lp.height = v.getMeasuredHeight();
1155 // Pre-measure so we can scale later.
1157 LayoutParams lp = row.getLayoutParams();
1159 lp = new LayoutParams(LayoutParams.MATCH_PARENT, holder.measuredRowHeight);
1160 row.setLayoutParams(lp);
1162 lp.height = holder.measuredRowHeight;
1168 void bindViewHolder(int rowPosition, RowViewHolder holder) {
1169 final int start = getFirstRowPosition(rowPosition);
1170 final int startType = mChooserListAdapter.getPositionTargetType(start);
1172 int end = start + mColumnCount - 1;
1173 while (mChooserListAdapter.getPositionTargetType(end) != startType && end >= start) {
1177 if (startType == ChooserListAdapter.TARGET_SERVICE) {
1178 holder.row.setBackgroundColor(
1179 getColor(R.color.chooser_service_row_background_color));
1181 holder.row.setBackgroundColor(Color.TRANSPARENT);
1184 final int oldHeight = holder.row.getLayoutParams().height;
1185 holder.row.getLayoutParams().height = Math.max(1,
1186 (int) (holder.measuredRowHeight * getRowScale(rowPosition)));
1187 if (holder.row.getLayoutParams().height != oldHeight) {
1188 holder.row.requestLayout();
1191 for (int i = 0; i < mColumnCount; i++) {
1192 final View v = holder.cells[i];
1193 if (start + i <= end) {
1194 v.setVisibility(View.VISIBLE);
1195 holder.itemIndices[i] = start + i;
1196 mChooserListAdapter.bindView(holder.itemIndices[i], v);
1198 v.setVisibility(View.GONE);
1203 int getFirstRowPosition(int row) {
1204 final int callerCount = mChooserListAdapter.getCallerTargetCount();
1205 final int callerRows = (int) Math.ceil((float) callerCount / mColumnCount);
1207 if (row < callerRows) {
1208 return row * mColumnCount;
1211 final int serviceCount = mChooserListAdapter.getServiceTargetCount();
1212 final int serviceRows = (int) Math.ceil((float) serviceCount / mColumnCount);
1214 if (row < callerRows + serviceRows) {
1215 return callerCount + (row - callerRows) * mColumnCount;
1218 return callerCount + serviceCount
1219 + (row - callerRows - serviceRows) * mColumnCount;
1223 static class RowViewHolder {
1225 final ViewGroup row;
1226 int measuredRowHeight;
1229 public RowViewHolder(ViewGroup row, int cellCount) {
1231 this.cells = new View[cellCount];
1232 this.itemIndices = new int[cellCount];
1235 public void measure() {
1236 final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1237 row.measure(spec, spec);
1238 measuredRowHeight = row.getMeasuredHeight();
1242 static class ChooserTargetServiceConnection implements ServiceConnection {
1243 private final DisplayResolveInfo mOriginalTarget;
1244 private ComponentName mConnectedComponent;
1245 private ChooserActivity mChooserActivity;
1246 private final Object mLock = new Object();
1248 private final IChooserTargetResult mChooserTargetResult = new IChooserTargetResult.Stub() {
1250 public void sendResult(List<ChooserTarget> targets) throws RemoteException {
1251 synchronized (mLock) {
1252 if (mChooserActivity == null) {
1253 Log.e(TAG, "destroyed ChooserTargetServiceConnection received result from "
1254 + mConnectedComponent + "; ignoring...");
1257 mChooserActivity.filterServiceTargets(
1258 mOriginalTarget.getResolveInfo().activityInfo.packageName, targets);
1259 final Message msg = Message.obtain();
1260 msg.what = CHOOSER_TARGET_SERVICE_RESULT;
1261 msg.obj = new ServiceResultInfo(mOriginalTarget, targets,
1262 ChooserTargetServiceConnection.this);
1263 mChooserActivity.mChooserHandler.sendMessage(msg);
1268 public ChooserTargetServiceConnection(ChooserActivity chooserActivity,
1269 DisplayResolveInfo dri) {
1270 mChooserActivity = chooserActivity;
1271 mOriginalTarget = dri;
1275 public void onServiceConnected(ComponentName name, IBinder service) {
1276 if (DEBUG) Log.d(TAG, "onServiceConnected: " + name);
1277 synchronized (mLock) {
1278 if (mChooserActivity == null) {
1279 Log.e(TAG, "destroyed ChooserTargetServiceConnection got onServiceConnected");
1283 final IChooserTargetService icts = IChooserTargetService.Stub.asInterface(service);
1285 icts.getChooserTargets(mOriginalTarget.getResolvedComponentName(),
1286 mOriginalTarget.getResolveInfo().filter, mChooserTargetResult);
1287 } catch (RemoteException e) {
1288 Log.e(TAG, "Querying ChooserTargetService " + name + " failed.", e);
1289 mChooserActivity.unbindService(this);
1291 mChooserActivity.mServiceConnections.remove(this);
1297 public void onServiceDisconnected(ComponentName name) {
1298 if (DEBUG) Log.d(TAG, "onServiceDisconnected: " + name);
1299 synchronized (mLock) {
1300 if (mChooserActivity == null) {
1302 "destroyed ChooserTargetServiceConnection got onServiceDisconnected");
1306 mChooserActivity.unbindService(this);
1308 mChooserActivity.mServiceConnections.remove(this);
1309 if (mChooserActivity.mServiceConnections.isEmpty()) {
1310 mChooserActivity.mChooserHandler.removeMessages(
1311 CHOOSER_TARGET_SERVICE_WATCHDOG_TIMEOUT);
1312 mChooserActivity.sendVoiceChoicesIfNeeded();
1314 mConnectedComponent = null;
1318 public void destroy() {
1319 synchronized (mLock) {
1320 mChooserActivity = null;
1325 public String toString() {
1326 return "ChooserTargetServiceConnection{service="
1327 + mConnectedComponent + ", activity="
1328 + mOriginalTarget.getResolveInfo().activityInfo.toString() + "}";
1332 static class ServiceResultInfo {
1333 public final DisplayResolveInfo originalTarget;
1334 public final List<ChooserTarget> resultTargets;
1335 public final ChooserTargetServiceConnection connection;
1337 public ServiceResultInfo(DisplayResolveInfo ot, List<ChooserTarget> rt,
1338 ChooserTargetServiceConnection c) {
1339 originalTarget = ot;
1345 static class RefinementResultReceiver extends ResultReceiver {
1346 private ChooserActivity mChooserActivity;
1347 private TargetInfo mSelectedTarget;
1349 public RefinementResultReceiver(ChooserActivity host, TargetInfo target,
1352 mChooserActivity = host;
1353 mSelectedTarget = target;
1357 protected void onReceiveResult(int resultCode, Bundle resultData) {
1358 if (mChooserActivity == null) {
1359 Log.e(TAG, "Destroyed RefinementResultReceiver received a result");
1362 if (resultData == null) {
1363 Log.e(TAG, "RefinementResultReceiver received null resultData");
1367 switch (resultCode) {
1368 case RESULT_CANCELED:
1369 mChooserActivity.onRefinementCanceled();
1372 Parcelable intentParcelable = resultData.getParcelable(Intent.EXTRA_INTENT);
1373 if (intentParcelable instanceof Intent) {
1374 mChooserActivity.onRefinementResult(mSelectedTarget,
1375 (Intent) intentParcelable);
1377 Log.e(TAG, "RefinementResultReceiver received RESULT_OK but no Intent"
1378 + " in resultData with key Intent.EXTRA_INTENT");
1382 Log.w(TAG, "Unknown result code " + resultCode
1383 + " sent to RefinementResultReceiver");
1388 public void destroy() {
1389 mChooserActivity = null;
1390 mSelectedTarget = null;
1394 class OffsetDataSetObserver extends DataSetObserver {
1395 private final AbsListView mListView;
1396 private int mCachedViewType = -1;
1397 private View mCachedView;
1399 public OffsetDataSetObserver(AbsListView listView) {
1400 mListView = listView;
1404 public void onChanged() {
1405 if (mResolverDrawerLayout == null) {
1409 final int chooserTargetRows = mChooserRowAdapter.getServiceTargetRowCount();
1411 for (int i = 0; i < chooserTargetRows; i++) {
1412 final int pos = mChooserRowAdapter.getCallerTargetRowCount() + i;
1413 final int vt = mChooserRowAdapter.getItemViewType(pos);
1414 if (vt != mCachedViewType) {
1417 final View v = mChooserRowAdapter.getView(pos, mCachedView, mListView);
1418 int height = ((RowViewHolder) (v.getTag())).measuredRowHeight;
1420 offset += (int) (height * mChooserRowAdapter.getRowScale(pos));
1423 mCachedViewType = vt;
1426 mCachedViewType = -1;
1430 mResolverDrawerLayout.setCollapsibleHeightReserved(offset);