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