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