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