ResolverActivity.java revision d44713a63d51ba7f186c775c2a32f3c2ce018037
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.content.ComponentName; 23import android.content.Context; 24import android.content.DialogInterface; 25import android.content.Intent; 26import android.content.IntentFilter; 27import android.content.pm.ActivityInfo; 28import android.content.pm.LabeledIntent; 29import android.content.pm.PackageManager; 30import android.content.pm.ResolveInfo; 31import android.graphics.drawable.Drawable; 32import android.net.Uri; 33import android.os.Bundle; 34import android.os.PatternMatcher; 35import android.util.Log; 36import android.view.LayoutInflater; 37import android.view.View; 38import android.view.ViewGroup; 39import android.widget.AdapterView; 40import android.widget.BaseAdapter; 41import android.widget.CheckBox; 42import android.widget.CompoundButton; 43import android.widget.ImageView; 44import android.widget.ListView; 45import android.widget.TextView; 46 47import java.util.ArrayList; 48import java.util.Collections; 49import java.util.HashSet; 50import java.util.Iterator; 51import java.util.List; 52import java.util.Set; 53 54/** 55 * This activity is displayed when the system attempts to start an Intent for 56 * which there is more than one matching activity, allowing the user to decide 57 * which to go to. It is not normally used directly by application developers. 58 */ 59public class ResolverActivity extends AlertActivity implements 60 DialogInterface.OnClickListener, CheckBox.OnCheckedChangeListener { 61 private ResolveListAdapter mAdapter; 62 private CheckBox mAlwaysCheck; 63 private TextView mClearDefaultHint; 64 private PackageManager mPm; 65 66 private boolean mRegistered; 67 private final PackageMonitor mPackageMonitor = new PackageMonitor() { 68 @Override public void onSomePackagesChanged() { 69 mAdapter.handlePackagesChanged(); 70 } 71 }; 72 73 private Intent makeMyIntent() { 74 Intent intent = new Intent(getIntent()); 75 // The resolver activity is set to be hidden from recent tasks. 76 // we don't want this attribute to be propagated to the next activity 77 // being launched. Note that if the original Intent also had this 78 // flag set, we are now losing it. That should be a very rare case 79 // and we can live with this. 80 intent.setFlags(intent.getFlags()&~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 81 return intent; 82 } 83 84 @Override 85 protected void onCreate(Bundle savedInstanceState) { 86 onCreate(savedInstanceState, makeMyIntent(), 87 getResources().getText(com.android.internal.R.string.whichApplication), 88 null, null, true); 89 } 90 91 protected void onCreate(Bundle savedInstanceState, Intent intent, 92 CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList, 93 boolean alwaysUseOption) { 94 super.onCreate(savedInstanceState); 95 mPm = getPackageManager(); 96 intent.setComponent(null); 97 98 AlertController.AlertParams ap = mAlertParams; 99 100 ap.mTitle = title; 101 ap.mOnClickListener = this; 102 103 mPackageMonitor.register(this, getMainLooper(), false); 104 mRegistered = true; 105 106 if (alwaysUseOption) { 107 LayoutInflater inflater = (LayoutInflater) getSystemService( 108 Context.LAYOUT_INFLATER_SERVICE); 109 ap.mView = inflater.inflate(R.layout.always_use_checkbox, null); 110 mAlwaysCheck = (CheckBox)ap.mView.findViewById(com.android.internal.R.id.alwaysUse); 111 mAlwaysCheck.setText(R.string.alwaysUse); 112 mAlwaysCheck.setOnCheckedChangeListener(this); 113 mClearDefaultHint = (TextView)ap.mView.findViewById( 114 com.android.internal.R.id.clearDefaultHint); 115 mClearDefaultHint.setVisibility(View.GONE); 116 } 117 mAdapter = new ResolveListAdapter(this, intent, initialIntents, rList); 118 int count = mAdapter.getCount(); 119 if (count > 1) { 120 ap.mAdapter = mAdapter; 121 } else if (count == 1) { 122 startActivity(mAdapter.intentForPosition(0)); 123 mPackageMonitor.unregister(); 124 mRegistered = false; 125 finish(); 126 return; 127 } else { 128 ap.mMessage = getResources().getText(com.android.internal.R.string.noApplications); 129 } 130 131 setupAlert(); 132 133 ListView lv = mAlert.getListView(); 134 if (lv != null) { 135 lv.setOnItemLongClickListener(new ItemLongClickListener()); 136 } 137 } 138 139 @Override 140 protected void onRestart() { 141 super.onRestart(); 142 if (!mRegistered) { 143 mPackageMonitor.register(this, getMainLooper(), false); 144 mRegistered = true; 145 } 146 mAdapter.handlePackagesChanged(); 147 } 148 149 @Override 150 protected void onStop() { 151 super.onStop(); 152 if (mRegistered) { 153 mPackageMonitor.unregister(); 154 mRegistered = false; 155 } 156 } 157 158 public void onClick(DialogInterface dialog, int which) { 159 ResolveInfo ri = mAdapter.resolveInfoForPosition(which); 160 Intent intent = mAdapter.intentForPosition(which); 161 boolean alwaysCheck = (mAlwaysCheck != null && mAlwaysCheck.isChecked()); 162 onIntentSelected(ri, intent, alwaysCheck); 163 finish(); 164 } 165 166 protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) { 167 if (alwaysCheck) { 168 // Build a reasonable intent filter, based on what matched. 169 IntentFilter filter = new IntentFilter(); 170 171 if (intent.getAction() != null) { 172 filter.addAction(intent.getAction()); 173 } 174 Set<String> categories = intent.getCategories(); 175 if (categories != null) { 176 for (String cat : categories) { 177 filter.addCategory(cat); 178 } 179 } 180 filter.addCategory(Intent.CATEGORY_DEFAULT); 181 182 int cat = ri.match&IntentFilter.MATCH_CATEGORY_MASK; 183 Uri data = intent.getData(); 184 if (cat == IntentFilter.MATCH_CATEGORY_TYPE) { 185 String mimeType = intent.resolveType(this); 186 if (mimeType != null) { 187 try { 188 filter.addDataType(mimeType); 189 } catch (IntentFilter.MalformedMimeTypeException e) { 190 Log.w("ResolverActivity", e); 191 filter = null; 192 } 193 } 194 } 195 if (data != null && data.getScheme() != null) { 196 // We need the data specification if there was no type, 197 // OR if the scheme is not one of our magical "file:" 198 // or "content:" schemes (see IntentFilter for the reason). 199 if (cat != IntentFilter.MATCH_CATEGORY_TYPE 200 || (!"file".equals(data.getScheme()) 201 && !"content".equals(data.getScheme()))) { 202 filter.addDataScheme(data.getScheme()); 203 204 // Look through the resolved filter to determine which part 205 // of it matched the original Intent. 206 Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator(); 207 if (aIt != null) { 208 while (aIt.hasNext()) { 209 IntentFilter.AuthorityEntry a = aIt.next(); 210 if (a.match(data) >= 0) { 211 int port = a.getPort(); 212 filter.addDataAuthority(a.getHost(), 213 port >= 0 ? Integer.toString(port) : null); 214 break; 215 } 216 } 217 } 218 Iterator<PatternMatcher> pIt = ri.filter.pathsIterator(); 219 if (pIt != null) { 220 String path = data.getPath(); 221 while (path != null && pIt.hasNext()) { 222 PatternMatcher p = pIt.next(); 223 if (p.match(path)) { 224 filter.addDataPath(p.getPath(), p.getType()); 225 break; 226 } 227 } 228 } 229 } 230 } 231 232 if (filter != null) { 233 final int N = mAdapter.mList.size(); 234 ComponentName[] set = new ComponentName[N]; 235 int bestMatch = 0; 236 for (int i=0; i<N; i++) { 237 ResolveInfo r = mAdapter.mList.get(i).ri; 238 set[i] = new ComponentName(r.activityInfo.packageName, 239 r.activityInfo.name); 240 if (r.match > bestMatch) bestMatch = r.match; 241 } 242 getPackageManager().addPreferredActivity(filter, bestMatch, set, 243 intent.getComponent()); 244 } 245 } 246 247 if (intent != null) { 248 startActivity(intent); 249 } 250 } 251 252 private final class DisplayResolveInfo { 253 ResolveInfo ri; 254 CharSequence displayLabel; 255 Drawable displayIcon; 256 CharSequence extendedInfo; 257 Intent origIntent; 258 259 DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel, 260 CharSequence pInfo, Intent pOrigIntent) { 261 ri = pri; 262 displayLabel = pLabel; 263 extendedInfo = pInfo; 264 origIntent = pOrigIntent; 265 } 266 } 267 268 private final class ResolveListAdapter extends BaseAdapter { 269 private final Intent[] mInitialIntents; 270 private final List<ResolveInfo> mBaseResolveList; 271 private final Intent mIntent; 272 private final LayoutInflater mInflater; 273 274 private List<ResolveInfo> mCurrentResolveList; 275 private List<DisplayResolveInfo> mList; 276 277 public ResolveListAdapter(Context context, Intent intent, 278 Intent[] initialIntents, List<ResolveInfo> rList) { 279 mIntent = new Intent(intent); 280 mIntent.setComponent(null); 281 mInitialIntents = initialIntents; 282 mBaseResolveList = rList; 283 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 284 rebuildList(); 285 } 286 287 public void handlePackagesChanged() { 288 rebuildList(); 289 notifyDataSetChanged(); 290 if (mList.size() <= 0) { 291 // We no longer have any items... just finish the activity. 292 finish(); 293 } 294 } 295 296 private void rebuildList() { 297 if (mBaseResolveList != null) { 298 mCurrentResolveList = mBaseResolveList; 299 } else { 300 mCurrentResolveList = mPm.queryIntentActivities( 301 mIntent, PackageManager.MATCH_DEFAULT_ONLY 302 | (mAlwaysCheck != null ? PackageManager.GET_RESOLVED_FILTER : 0)); 303 } 304 int N; 305 if ((mCurrentResolveList != null) && ((N = mCurrentResolveList.size()) > 0)) { 306 // Only display the first matches that are either of equal 307 // priority or have asked to be default options. 308 ResolveInfo r0 = mCurrentResolveList.get(0); 309 for (int i=1; i<N; i++) { 310 ResolveInfo ri = mCurrentResolveList.get(i); 311 if (false) Log.v( 312 "ResolveListActivity", 313 r0.activityInfo.name + "=" + 314 r0.priority + "/" + r0.isDefault + " vs " + 315 ri.activityInfo.name + "=" + 316 ri.priority + "/" + ri.isDefault); 317 if (r0.priority != ri.priority || 318 r0.isDefault != ri.isDefault) { 319 while (i < N) { 320 mCurrentResolveList.remove(i); 321 N--; 322 } 323 } 324 } 325 if (N > 1) { 326 ResolveInfo.DisplayNameComparator rComparator = 327 new ResolveInfo.DisplayNameComparator(mPm); 328 Collections.sort(mCurrentResolveList, rComparator); 329 } 330 331 mList = new ArrayList<DisplayResolveInfo>(); 332 333 // First put the initial items at the top. 334 if (mInitialIntents != null) { 335 for (int i=0; i<mInitialIntents.length; i++) { 336 Intent ii = mInitialIntents[i]; 337 if (ii == null) { 338 continue; 339 } 340 ActivityInfo ai = ii.resolveActivityInfo( 341 getPackageManager(), 0); 342 if (ai == null) { 343 Log.w("ResolverActivity", "No activity found for " 344 + ii); 345 continue; 346 } 347 ResolveInfo ri = new ResolveInfo(); 348 ri.activityInfo = ai; 349 if (ii instanceof LabeledIntent) { 350 LabeledIntent li = (LabeledIntent)ii; 351 ri.resolvePackageName = li.getSourcePackage(); 352 ri.labelRes = li.getLabelResource(); 353 ri.nonLocalizedLabel = li.getNonLocalizedLabel(); 354 ri.icon = li.getIconResource(); 355 } 356 mList.add(new DisplayResolveInfo(ri, 357 ri.loadLabel(getPackageManager()), null, ii)); 358 } 359 } 360 361 // Check for applications with same name and use application name or 362 // package name if necessary 363 r0 = mCurrentResolveList.get(0); 364 int start = 0; 365 CharSequence r0Label = r0.loadLabel(mPm); 366 for (int i = 1; i < N; i++) { 367 if (r0Label == null) { 368 r0Label = r0.activityInfo.packageName; 369 } 370 ResolveInfo ri = mCurrentResolveList.get(i); 371 CharSequence riLabel = ri.loadLabel(mPm); 372 if (riLabel == null) { 373 riLabel = ri.activityInfo.packageName; 374 } 375 if (riLabel.equals(r0Label)) { 376 continue; 377 } 378 processGroup(mCurrentResolveList, start, (i-1), r0, r0Label); 379 r0 = ri; 380 r0Label = riLabel; 381 start = i; 382 } 383 // Process last group 384 processGroup(mCurrentResolveList, start, (N-1), r0, r0Label); 385 } 386 } 387 388 private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro, 389 CharSequence roLabel) { 390 // Process labels from start to i 391 int num = end - start+1; 392 if (num == 1) { 393 // No duplicate labels. Use label for entry at start 394 mList.add(new DisplayResolveInfo(ro, roLabel, null, null)); 395 } else { 396 boolean usePkg = false; 397 CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm); 398 if (startApp == null) { 399 usePkg = true; 400 } 401 if (!usePkg) { 402 // Use HashSet to track duplicates 403 HashSet<CharSequence> duplicates = 404 new HashSet<CharSequence>(); 405 duplicates.add(startApp); 406 for (int j = start+1; j <= end ; j++) { 407 ResolveInfo jRi = rList.get(j); 408 CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm); 409 if ( (jApp == null) || (duplicates.contains(jApp))) { 410 usePkg = true; 411 break; 412 } else { 413 duplicates.add(jApp); 414 } 415 } 416 // Clear HashSet for later use 417 duplicates.clear(); 418 } 419 for (int k = start; k <= end; k++) { 420 ResolveInfo add = rList.get(k); 421 if (usePkg) { 422 // Use application name for all entries from start to end-1 423 mList.add(new DisplayResolveInfo(add, roLabel, 424 add.activityInfo.packageName, null)); 425 } else { 426 // Use package name for all entries from start to end-1 427 mList.add(new DisplayResolveInfo(add, roLabel, 428 add.activityInfo.applicationInfo.loadLabel(mPm), null)); 429 } 430 } 431 } 432 } 433 434 public ResolveInfo resolveInfoForPosition(int position) { 435 if (mList == null) { 436 return null; 437 } 438 439 return mList.get(position).ri; 440 } 441 442 public Intent intentForPosition(int position) { 443 if (mList == null) { 444 return null; 445 } 446 447 DisplayResolveInfo dri = mList.get(position); 448 449 Intent intent = new Intent(dri.origIntent != null 450 ? dri.origIntent : mIntent); 451 intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT 452 |Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); 453 ActivityInfo ai = dri.ri.activityInfo; 454 intent.setComponent(new ComponentName( 455 ai.applicationInfo.packageName, ai.name)); 456 return intent; 457 } 458 459 public int getCount() { 460 return mList != null ? mList.size() : 0; 461 } 462 463 public Object getItem(int position) { 464 return position; 465 } 466 467 public long getItemId(int position) { 468 return position; 469 } 470 471 public View getView(int position, View convertView, ViewGroup parent) { 472 View view; 473 if (convertView == null) { 474 view = mInflater.inflate( 475 com.android.internal.R.layout.resolve_list_item, parent, false); 476 } else { 477 view = convertView; 478 } 479 bindView(view, mList.get(position)); 480 return view; 481 } 482 483 private final void bindView(View view, DisplayResolveInfo info) { 484 TextView text = (TextView)view.findViewById(com.android.internal.R.id.text1); 485 TextView text2 = (TextView)view.findViewById(com.android.internal.R.id.text2); 486 ImageView icon = (ImageView)view.findViewById(R.id.icon); 487 text.setText(info.displayLabel); 488 if (info.extendedInfo != null) { 489 text2.setVisibility(View.VISIBLE); 490 text2.setText(info.extendedInfo); 491 } else { 492 text2.setVisibility(View.GONE); 493 } 494 if (info.displayIcon == null) { 495 info.displayIcon = info.ri.loadIcon(mPm); 496 } 497 icon.setImageDrawable(info.displayIcon); 498 } 499 } 500 501 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 502 if (mClearDefaultHint == null) return; 503 504 if(isChecked) { 505 mClearDefaultHint.setVisibility(View.VISIBLE); 506 } else { 507 mClearDefaultHint.setVisibility(View.GONE); 508 } 509 } 510 511 class ItemLongClickListener implements AdapterView.OnItemLongClickListener { 512 513 @Override 514 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { 515 ResolveInfo ri = mAdapter.resolveInfoForPosition(position); 516 Intent in = new Intent().setAction("android.settings.APPLICATION_DETAILS_SETTINGS") 517 .setData(Uri.fromParts("package", ri.activityInfo.packageName, null)); 518 startActivity(in); 519 return true; 520 } 521 522 } 523} 524 525