OSDN Git Service

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