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