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 com.android.internal.R; 20import com.android.internal.content.PackageMonitor; 21 22import android.app.ActivityManager; 23import android.app.ActivityManagerNative; 24import android.content.ComponentName; 25import android.content.Context; 26import android.content.Intent; 27import android.content.IntentFilter; 28import android.content.pm.ActivityInfo; 29import android.content.pm.LabeledIntent; 30import android.content.pm.PackageManager; 31import android.content.pm.PackageManager.NameNotFoundException; 32import android.content.pm.ResolveInfo; 33import android.content.res.Resources; 34import android.graphics.drawable.Drawable; 35import android.net.Uri; 36import android.os.Bundle; 37import android.os.PatternMatcher; 38import android.os.Process; 39import android.os.RemoteException; 40import android.os.UserHandle; 41import android.util.Log; 42import android.view.LayoutInflater; 43import android.view.View; 44import android.view.ViewGroup; 45import android.widget.AdapterView; 46import android.widget.BaseAdapter; 47import android.widget.Button; 48import android.widget.GridView; 49import android.widget.ImageView; 50import android.widget.ListView; 51import android.widget.TextView; 52 53import java.util.ArrayList; 54import java.util.Collections; 55import java.util.HashSet; 56import java.util.Iterator; 57import java.util.List; 58import java.util.Set; 59 60/** 61 * This activity is displayed when the system attempts to start an Intent for 62 * which there is more than one matching activity, allowing the user to decide 63 * which to go to. It is not normally used directly by application developers. 64 */ 65public class ResolverActivity extends AlertActivity implements AdapterView.OnItemClickListener { 66 private static final String TAG = "ResolverActivity"; 67 68 private int mLaunchedFromUid; 69 private ResolveListAdapter mAdapter; 70 private PackageManager mPm; 71 private boolean mAlwaysUseOption; 72 private boolean mShowExtended; 73 private GridView mGrid; 74 private Button mAlwaysButton; 75 private Button mOnceButton; 76 private int mIconDpi; 77 private int mIconSize; 78 private int mMaxColumns; 79 private int mLastSelected = GridView.INVALID_POSITION; 80 81 private boolean mRegistered; 82 private final PackageMonitor mPackageMonitor = new PackageMonitor() { 83 @Override public void onSomePackagesChanged() { 84 mAdapter.handlePackagesChanged(); 85 } 86 }; 87 88 private Intent makeMyIntent() { 89 Intent intent = new Intent(getIntent()); 90 // The resolver activity is set to be hidden from recent tasks. 91 // we don't want this attribute to be propagated to the next activity 92 // being launched. Note that if the original Intent also had this 93 // flag set, we are now losing it. That should be a very rare case 94 // and we can live with this. 95 intent.setFlags(intent.getFlags()&~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 96 return intent; 97 } 98 99 @Override 100 protected void onCreate(Bundle savedInstanceState) { 101 onCreate(savedInstanceState, makeMyIntent(), 102 getResources().getText(com.android.internal.R.string.whichApplication), 103 null, null, true); 104 } 105 106 protected void onCreate(Bundle savedInstanceState, Intent intent, 107 CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList, 108 boolean alwaysUseOption) { 109 setTheme(R.style.Theme_DeviceDefault_Light_Dialog_Alert); 110 super.onCreate(savedInstanceState); 111 try { 112 mLaunchedFromUid = ActivityManagerNative.getDefault().getLaunchedFromUid( 113 getActivityToken()); 114 } catch (RemoteException e) { 115 mLaunchedFromUid = -1; 116 } 117 mPm = getPackageManager(); 118 mAlwaysUseOption = alwaysUseOption; 119 mMaxColumns = getResources().getInteger(R.integer.config_maxResolverActivityColumns); 120 intent.setComponent(null); 121 122 AlertController.AlertParams ap = mAlertParams; 123 124 ap.mTitle = title; 125 126 mPackageMonitor.register(this, getMainLooper(), false); 127 mRegistered = true; 128 129 final ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 130 mIconDpi = am.getLauncherLargeIconDensity(); 131 mIconSize = am.getLauncherLargeIconSize(); 132 133 mAdapter = new ResolveListAdapter(this, intent, initialIntents, rList, 134 mLaunchedFromUid); 135 int count = mAdapter.getCount(); 136 if (mLaunchedFromUid < 0 || UserHandle.isIsolated(mLaunchedFromUid)) { 137 // Gulp! 138 finish(); 139 return; 140 } else if (count > 1) { 141 ap.mView = getLayoutInflater().inflate(R.layout.resolver_grid, null); 142 mGrid = (GridView) ap.mView.findViewById(R.id.resolver_grid); 143 mGrid.setAdapter(mAdapter); 144 mGrid.setOnItemClickListener(this); 145 mGrid.setOnItemLongClickListener(new ItemLongClickListener()); 146 147 if (alwaysUseOption) { 148 mGrid.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 149 } 150 151 resizeGrid(); 152 } else if (count == 1) { 153 startActivity(mAdapter.intentForPosition(0)); 154 mPackageMonitor.unregister(); 155 mRegistered = false; 156 finish(); 157 return; 158 } else { 159 ap.mMessage = getResources().getText(R.string.noApplications); 160 } 161 162 setupAlert(); 163 164 if (alwaysUseOption) { 165 final ViewGroup buttonLayout = (ViewGroup) findViewById(R.id.button_bar); 166 if (buttonLayout != null) { 167 buttonLayout.setVisibility(View.VISIBLE); 168 mAlwaysButton = (Button) buttonLayout.findViewById(R.id.button_always); 169 mOnceButton = (Button) buttonLayout.findViewById(R.id.button_once); 170 } else { 171 mAlwaysUseOption = false; 172 } 173 } 174 } 175 176 void resizeGrid() { 177 final int itemCount = mAdapter.getCount(); 178 mGrid.setNumColumns(Math.min(itemCount, mMaxColumns)); 179 } 180 181 Drawable getIcon(Resources res, int resId) { 182 Drawable result; 183 try { 184 result = res.getDrawableForDensity(resId, mIconDpi); 185 } catch (Resources.NotFoundException e) { 186 result = null; 187 } 188 189 return result; 190 } 191 192 Drawable loadIconForResolveInfo(ResolveInfo ri) { 193 Drawable dr; 194 try { 195 if (ri.resolvePackageName != null && ri.icon != 0) { 196 dr = getIcon(mPm.getResourcesForApplication(ri.resolvePackageName), ri.icon); 197 if (dr != null) { 198 return dr; 199 } 200 } 201 final int iconRes = ri.getIconResource(); 202 if (iconRes != 0) { 203 dr = getIcon(mPm.getResourcesForApplication(ri.activityInfo.packageName), iconRes); 204 if (dr != null) { 205 return dr; 206 } 207 } 208 } catch (NameNotFoundException e) { 209 Log.e(TAG, "Couldn't find resources for package", e); 210 } 211 return ri.loadIcon(mPm); 212 } 213 214 @Override 215 protected void onRestart() { 216 super.onRestart(); 217 if (!mRegistered) { 218 mPackageMonitor.register(this, getMainLooper(), false); 219 mRegistered = true; 220 } 221 mAdapter.handlePackagesChanged(); 222 } 223 224 @Override 225 protected void onStop() { 226 super.onStop(); 227 if (mRegistered) { 228 mPackageMonitor.unregister(); 229 mRegistered = false; 230 } 231 if ((getIntent().getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { 232 // This resolver is in the unusual situation where it has been 233 // launched at the top of a new task. We don't let it be added 234 // to the recent tasks shown to the user, and we need to make sure 235 // that each time we are launched we get the correct launching 236 // uid (not re-using the same resolver from an old launching uid), 237 // so we will now finish ourself since being no longer visible, 238 // the user probably can't get back to us. 239 if (!isChangingConfigurations()) { 240 finish(); 241 } 242 } 243 } 244 245 @Override 246 protected void onRestoreInstanceState(Bundle savedInstanceState) { 247 super.onRestoreInstanceState(savedInstanceState); 248 if (mAlwaysUseOption) { 249 final int checkedPos = mGrid.getCheckedItemPosition(); 250 final boolean enabled = checkedPos != GridView.INVALID_POSITION; 251 mLastSelected = checkedPos; 252 mAlwaysButton.setEnabled(enabled); 253 mOnceButton.setEnabled(enabled); 254 if (enabled) { 255 mGrid.setSelection(checkedPos); 256 } 257 } 258 } 259 260 @Override 261 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 262 final int checkedPos = mGrid.getCheckedItemPosition(); 263 final boolean hasValidSelection = checkedPos != GridView.INVALID_POSITION; 264 if (mAlwaysUseOption && (!hasValidSelection || mLastSelected != checkedPos)) { 265 mAlwaysButton.setEnabled(hasValidSelection); 266 mOnceButton.setEnabled(hasValidSelection); 267 if (hasValidSelection) { 268 mGrid.smoothScrollToPosition(checkedPos); 269 } 270 mLastSelected = checkedPos; 271 } else { 272 startSelected(position, false); 273 } 274 } 275 276 public void onButtonClick(View v) { 277 final int id = v.getId(); 278 startSelected(mGrid.getCheckedItemPosition(), id == R.id.button_always); 279 dismiss(); 280 } 281 282 void startSelected(int which, boolean always) { 283 ResolveInfo ri = mAdapter.resolveInfoForPosition(which); 284 Intent intent = mAdapter.intentForPosition(which); 285 onIntentSelected(ri, intent, always); 286 finish(); 287 } 288 289 protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) { 290 if (alwaysCheck) { 291 // Build a reasonable intent filter, based on what matched. 292 IntentFilter filter = new IntentFilter(); 293 294 if (intent.getAction() != null) { 295 filter.addAction(intent.getAction()); 296 } 297 Set<String> categories = intent.getCategories(); 298 if (categories != null) { 299 for (String cat : categories) { 300 filter.addCategory(cat); 301 } 302 } 303 filter.addCategory(Intent.CATEGORY_DEFAULT); 304 305 int cat = ri.match&IntentFilter.MATCH_CATEGORY_MASK; 306 Uri data = intent.getData(); 307 if (cat == IntentFilter.MATCH_CATEGORY_TYPE) { 308 String mimeType = intent.resolveType(this); 309 if (mimeType != null) { 310 try { 311 filter.addDataType(mimeType); 312 } catch (IntentFilter.MalformedMimeTypeException e) { 313 Log.w("ResolverActivity", e); 314 filter = null; 315 } 316 } 317 } 318 if (data != null && data.getScheme() != null) { 319 // We need the data specification if there was no type, 320 // OR if the scheme is not one of our magical "file:" 321 // or "content:" schemes (see IntentFilter for the reason). 322 if (cat != IntentFilter.MATCH_CATEGORY_TYPE 323 || (!"file".equals(data.getScheme()) 324 && !"content".equals(data.getScheme()))) { 325 filter.addDataScheme(data.getScheme()); 326 327 // Look through the resolved filter to determine which part 328 // of it matched the original Intent. 329 Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator(); 330 if (aIt != null) { 331 while (aIt.hasNext()) { 332 IntentFilter.AuthorityEntry a = aIt.next(); 333 if (a.match(data) >= 0) { 334 int port = a.getPort(); 335 filter.addDataAuthority(a.getHost(), 336 port >= 0 ? Integer.toString(port) : null); 337 break; 338 } 339 } 340 } 341 Iterator<PatternMatcher> pIt = ri.filter.pathsIterator(); 342 if (pIt != null) { 343 String path = data.getPath(); 344 while (path != null && pIt.hasNext()) { 345 PatternMatcher p = pIt.next(); 346 if (p.match(path)) { 347 filter.addDataPath(p.getPath(), p.getType()); 348 break; 349 } 350 } 351 } 352 } 353 } 354 355 if (filter != null) { 356 final int N = mAdapter.mList.size(); 357 ComponentName[] set = new ComponentName[N]; 358 int bestMatch = 0; 359 for (int i=0; i<N; i++) { 360 ResolveInfo r = mAdapter.mList.get(i).ri; 361 set[i] = new ComponentName(r.activityInfo.packageName, 362 r.activityInfo.name); 363 if (r.match > bestMatch) bestMatch = r.match; 364 } 365 getPackageManager().addPreferredActivity(filter, bestMatch, set, 366 intent.getComponent()); 367 } 368 } 369 370 if (intent != null) { 371 startActivity(intent); 372 } 373 } 374 375 void showAppDetails(ResolveInfo ri) { 376 Intent in = new Intent().setAction("android.settings.APPLICATION_DETAILS_SETTINGS") 377 .setData(Uri.fromParts("package", ri.activityInfo.packageName, null)) 378 .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 379 startActivity(in); 380 } 381 382 private final class DisplayResolveInfo { 383 ResolveInfo ri; 384 CharSequence displayLabel; 385 Drawable displayIcon; 386 CharSequence extendedInfo; 387 Intent origIntent; 388 389 DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel, 390 CharSequence pInfo, Intent pOrigIntent) { 391 ri = pri; 392 displayLabel = pLabel; 393 extendedInfo = pInfo; 394 origIntent = pOrigIntent; 395 } 396 } 397 398 private final class ResolveListAdapter extends BaseAdapter { 399 private final Intent[] mInitialIntents; 400 private final List<ResolveInfo> mBaseResolveList; 401 private final Intent mIntent; 402 private final int mLaunchedFromUid; 403 private final LayoutInflater mInflater; 404 405 private List<ResolveInfo> mCurrentResolveList; 406 private List<DisplayResolveInfo> mList; 407 408 public ResolveListAdapter(Context context, Intent intent, 409 Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid) { 410 mIntent = new Intent(intent); 411 mIntent.setComponent(null); 412 mInitialIntents = initialIntents; 413 mBaseResolveList = rList; 414 mLaunchedFromUid = launchedFromUid; 415 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 416 rebuildList(); 417 } 418 419 public void handlePackagesChanged() { 420 final int oldItemCount = getCount(); 421 rebuildList(); 422 notifyDataSetChanged(); 423 if (mList.size() <= 0) { 424 // We no longer have any items... just finish the activity. 425 finish(); 426 } 427 428 final int newItemCount = getCount(); 429 if (newItemCount != oldItemCount) { 430 resizeGrid(); 431 } 432 } 433 434 private void rebuildList() { 435 if (mBaseResolveList != null) { 436 mCurrentResolveList = mBaseResolveList; 437 } else { 438 mCurrentResolveList = mPm.queryIntentActivities( 439 mIntent, PackageManager.MATCH_DEFAULT_ONLY 440 | (mAlwaysUseOption ? PackageManager.GET_RESOLVED_FILTER : 0)); 441 // Filter out any activities that the launched uid does not 442 // have permission for. We don't do this when we have an explicit 443 // list of resolved activities, because that only happens when 444 // we are being subclassed, so we can safely launch whatever 445 // they gave us. 446 if (mCurrentResolveList != null) { 447 for (int i=mCurrentResolveList.size()-1; i >= 0; i--) { 448 ActivityInfo ai = mCurrentResolveList.get(i).activityInfo; 449 int granted = ActivityManager.checkComponentPermission( 450 ai.permission, mLaunchedFromUid, 451 ai.applicationInfo.uid, ai.exported); 452 if (granted != PackageManager.PERMISSION_GRANTED) { 453 // Access not allowed! 454 mCurrentResolveList.remove(i); 455 } 456 } 457 } 458 } 459 int N; 460 if ((mCurrentResolveList != null) && ((N = mCurrentResolveList.size()) > 0)) { 461 // Only display the first matches that are either of equal 462 // priority or have asked to be default options. 463 ResolveInfo r0 = mCurrentResolveList.get(0); 464 for (int i=1; i<N; i++) { 465 ResolveInfo ri = mCurrentResolveList.get(i); 466 if (false) Log.v( 467 "ResolveListActivity", 468 r0.activityInfo.name + "=" + 469 r0.priority + "/" + r0.isDefault + " vs " + 470 ri.activityInfo.name + "=" + 471 ri.priority + "/" + ri.isDefault); 472 if (r0.priority != ri.priority || 473 r0.isDefault != ri.isDefault) { 474 while (i < N) { 475 mCurrentResolveList.remove(i); 476 N--; 477 } 478 } 479 } 480 if (N > 1) { 481 ResolveInfo.DisplayNameComparator rComparator = 482 new ResolveInfo.DisplayNameComparator(mPm); 483 Collections.sort(mCurrentResolveList, rComparator); 484 } 485 486 mList = new ArrayList<DisplayResolveInfo>(); 487 488 // First put the initial items at the top. 489 if (mInitialIntents != null) { 490 for (int i=0; i<mInitialIntents.length; i++) { 491 Intent ii = mInitialIntents[i]; 492 if (ii == null) { 493 continue; 494 } 495 ActivityInfo ai = ii.resolveActivityInfo( 496 getPackageManager(), 0); 497 if (ai == null) { 498 Log.w("ResolverActivity", "No activity found for " 499 + ii); 500 continue; 501 } 502 ResolveInfo ri = new ResolveInfo(); 503 ri.activityInfo = ai; 504 if (ii instanceof LabeledIntent) { 505 LabeledIntent li = (LabeledIntent)ii; 506 ri.resolvePackageName = li.getSourcePackage(); 507 ri.labelRes = li.getLabelResource(); 508 ri.nonLocalizedLabel = li.getNonLocalizedLabel(); 509 ri.icon = li.getIconResource(); 510 } 511 mList.add(new DisplayResolveInfo(ri, 512 ri.loadLabel(getPackageManager()), null, ii)); 513 } 514 } 515 516 // Check for applications with same name and use application name or 517 // package name if necessary 518 r0 = mCurrentResolveList.get(0); 519 int start = 0; 520 CharSequence r0Label = r0.loadLabel(mPm); 521 mShowExtended = false; 522 for (int i = 1; i < N; i++) { 523 if (r0Label == null) { 524 r0Label = r0.activityInfo.packageName; 525 } 526 ResolveInfo ri = mCurrentResolveList.get(i); 527 CharSequence riLabel = ri.loadLabel(mPm); 528 if (riLabel == null) { 529 riLabel = ri.activityInfo.packageName; 530 } 531 if (riLabel.equals(r0Label)) { 532 continue; 533 } 534 processGroup(mCurrentResolveList, start, (i-1), r0, r0Label); 535 r0 = ri; 536 r0Label = riLabel; 537 start = i; 538 } 539 // Process last group 540 processGroup(mCurrentResolveList, start, (N-1), r0, r0Label); 541 } 542 } 543 544 private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro, 545 CharSequence roLabel) { 546 // Process labels from start to i 547 int num = end - start+1; 548 if (num == 1) { 549 // No duplicate labels. Use label for entry at start 550 mList.add(new DisplayResolveInfo(ro, roLabel, null, null)); 551 } else { 552 mShowExtended = true; 553 boolean usePkg = false; 554 CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm); 555 if (startApp == null) { 556 usePkg = true; 557 } 558 if (!usePkg) { 559 // Use HashSet to track duplicates 560 HashSet<CharSequence> duplicates = 561 new HashSet<CharSequence>(); 562 duplicates.add(startApp); 563 for (int j = start+1; j <= end ; j++) { 564 ResolveInfo jRi = rList.get(j); 565 CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm); 566 if ( (jApp == null) || (duplicates.contains(jApp))) { 567 usePkg = true; 568 break; 569 } else { 570 duplicates.add(jApp); 571 } 572 } 573 // Clear HashSet for later use 574 duplicates.clear(); 575 } 576 for (int k = start; k <= end; k++) { 577 ResolveInfo add = rList.get(k); 578 if (usePkg) { 579 // Use application name for all entries from start to end-1 580 mList.add(new DisplayResolveInfo(add, roLabel, 581 add.activityInfo.packageName, null)); 582 } else { 583 // Use package name for all entries from start to end-1 584 mList.add(new DisplayResolveInfo(add, roLabel, 585 add.activityInfo.applicationInfo.loadLabel(mPm), null)); 586 } 587 } 588 } 589 } 590 591 public ResolveInfo resolveInfoForPosition(int position) { 592 if (mList == null) { 593 return null; 594 } 595 596 return mList.get(position).ri; 597 } 598 599 public Intent intentForPosition(int position) { 600 if (mList == null) { 601 return null; 602 } 603 604 DisplayResolveInfo dri = mList.get(position); 605 606 Intent intent = new Intent(dri.origIntent != null 607 ? dri.origIntent : mIntent); 608 intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT 609 |Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); 610 ActivityInfo ai = dri.ri.activityInfo; 611 intent.setComponent(new ComponentName( 612 ai.applicationInfo.packageName, ai.name)); 613 return intent; 614 } 615 616 public int getCount() { 617 return mList != null ? mList.size() : 0; 618 } 619 620 public Object getItem(int position) { 621 return position; 622 } 623 624 public long getItemId(int position) { 625 return position; 626 } 627 628 public View getView(int position, View convertView, ViewGroup parent) { 629 View view; 630 if (convertView == null) { 631 view = mInflater.inflate( 632 com.android.internal.R.layout.resolve_list_item, parent, false); 633 634 // Fix the icon size even if we have different sized resources 635 ImageView icon = (ImageView)view.findViewById(R.id.icon); 636 ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) icon.getLayoutParams(); 637 lp.width = lp.height = mIconSize; 638 } else { 639 view = convertView; 640 } 641 bindView(view, mList.get(position)); 642 return view; 643 } 644 645 private final void bindView(View view, DisplayResolveInfo info) { 646 TextView text = (TextView)view.findViewById(com.android.internal.R.id.text1); 647 TextView text2 = (TextView)view.findViewById(com.android.internal.R.id.text2); 648 ImageView icon = (ImageView)view.findViewById(R.id.icon); 649 text.setText(info.displayLabel); 650 if (mShowExtended) { 651 text2.setVisibility(View.VISIBLE); 652 text2.setText(info.extendedInfo); 653 } else { 654 text2.setVisibility(View.GONE); 655 } 656 if (info.displayIcon == null) { 657 info.displayIcon = loadIconForResolveInfo(info.ri); 658 } 659 icon.setImageDrawable(info.displayIcon); 660 } 661 } 662 663 class ItemLongClickListener implements AdapterView.OnItemLongClickListener { 664 665 @Override 666 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { 667 ResolveInfo ri = mAdapter.resolveInfoForPosition(position); 668 showAppDetails(ri); 669 return true; 670 } 671 672 } 673} 674 675