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