ResolverActivity.java revision 588dd2a3d67435652545645bca9562c066561cda
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.os.AsyncTask;
20import com.android.internal.R;
21import com.android.internal.content.PackageMonitor;
22
23import android.app.ActivityManager;
24import android.app.ActivityManagerNative;
25import android.app.AppGlobals;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.ActivityInfo;
31import android.content.pm.IPackageManager;
32import android.content.pm.LabeledIntent;
33import android.content.pm.PackageManager;
34import android.content.pm.PackageManager.NameNotFoundException;
35import android.content.pm.ResolveInfo;
36import android.content.res.Resources;
37import android.graphics.drawable.Drawable;
38import android.net.Uri;
39import android.os.Bundle;
40import android.os.PatternMatcher;
41import android.os.RemoteException;
42import android.os.UserHandle;
43import android.util.Log;
44import android.view.LayoutInflater;
45import android.view.View;
46import android.view.ViewGroup;
47import android.widget.AdapterView;
48import android.widget.BaseAdapter;
49import android.widget.Button;
50import android.widget.ImageView;
51import android.widget.ListView;
52import android.widget.TextView;
53
54import java.util.ArrayList;
55import java.util.Collections;
56import java.util.HashSet;
57import java.util.Iterator;
58import java.util.List;
59import java.util.Set;
60
61/**
62 * This activity is displayed when the system attempts to start an Intent for
63 * which there is more than one matching activity, allowing the user to decide
64 * which to go to.  It is not normally used directly by application developers.
65 */
66public class ResolverActivity extends AlertActivity implements AdapterView.OnItemClickListener {
67    private static final String TAG = "ResolverActivity";
68    private static final boolean DEBUG = false;
69
70    private int mLaunchedFromUid;
71    private ResolveListAdapter mAdapter;
72    private PackageManager mPm;
73    private boolean mAlwaysUseOption;
74    private boolean mShowExtended;
75    private ListView mListView;
76    private Button mAlwaysButton;
77    private Button mOnceButton;
78    private int mIconDpi;
79    private int mIconSize;
80    private int mMaxColumns;
81    private int mLastSelected = ListView.INVALID_POSITION;
82
83    private boolean mRegistered;
84    private final PackageMonitor mPackageMonitor = new PackageMonitor() {
85        @Override public void onSomePackagesChanged() {
86            mAdapter.handlePackagesChanged();
87        }
88    };
89
90    private Intent makeMyIntent() {
91        Intent intent = new Intent(getIntent());
92        // The resolver activity is set to be hidden from recent tasks.
93        // we don't want this attribute to be propagated to the next activity
94        // being launched.  Note that if the original Intent also had this
95        // flag set, we are now losing it.  That should be a very rare case
96        // and we can live with this.
97        intent.setFlags(intent.getFlags()&~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
98        return intent;
99    }
100
101    @Override
102    protected void onCreate(Bundle savedInstanceState) {
103        onCreate(savedInstanceState, makeMyIntent(),
104                getResources().getText(com.android.internal.R.string.whichApplication),
105                null, null, true);
106    }
107
108    protected void onCreate(Bundle savedInstanceState, Intent intent,
109            CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList,
110            boolean alwaysUseOption) {
111        setTheme(R.style.Theme_DeviceDefault_Light_Dialog_Alert);
112        super.onCreate(savedInstanceState);
113        try {
114            mLaunchedFromUid = ActivityManagerNative.getDefault().getLaunchedFromUid(
115                    getActivityToken());
116        } catch (RemoteException e) {
117            mLaunchedFromUid = -1;
118        }
119        mPm = getPackageManager();
120        mAlwaysUseOption = alwaysUseOption;
121        mMaxColumns = getResources().getInteger(R.integer.config_maxResolverActivityColumns);
122        intent.setComponent(null);
123
124        AlertController.AlertParams ap = mAlertParams;
125
126        ap.mTitle = title;
127
128        mPackageMonitor.register(this, getMainLooper(), false);
129        mRegistered = true;
130
131        final ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
132        mIconDpi = am.getLauncherLargeIconDensity();
133        mIconSize = am.getLauncherLargeIconSize();
134
135        mAdapter = new ResolveListAdapter(this, intent, initialIntents, rList,
136                mLaunchedFromUid);
137        int count = mAdapter.getCount();
138        if (mLaunchedFromUid < 0 || UserHandle.isIsolated(mLaunchedFromUid)) {
139            // Gulp!
140            finish();
141            return;
142        } else if (count > 1) {
143            ap.mView = getLayoutInflater().inflate(R.layout.resolver_list, null);
144            mListView = (ListView) ap.mView.findViewById(R.id.resolver_list);
145            mListView.setAdapter(mAdapter);
146            mListView.setOnItemClickListener(this);
147            mListView.setOnItemLongClickListener(new ItemLongClickListener());
148
149            if (alwaysUseOption) {
150                mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
151            }
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        final int initialHighlight = mAdapter.getInitialHighlight();
175        if (initialHighlight >= 0) {
176            mListView.setItemChecked(initialHighlight, true);
177            onItemClick(null, null, initialHighlight, 0); // Other entries are not used
178        }
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 = mListView.getCheckedItemPosition();
250            final boolean enabled = checkedPos != ListView.INVALID_POSITION;
251            mLastSelected = checkedPos;
252            mAlwaysButton.setEnabled(enabled);
253            mOnceButton.setEnabled(enabled);
254            if (enabled) {
255                mListView.setSelection(checkedPos);
256            }
257        }
258    }
259
260    @Override
261    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
262        final int checkedPos = mListView.getCheckedItemPosition();
263        final boolean hasValidSelection = checkedPos != ListView.INVALID_POSITION;
264        if (mAlwaysUseOption && (!hasValidSelection || mLastSelected != checkedPos)) {
265            mAlwaysButton.setEnabled(hasValidSelection);
266            mOnceButton.setEnabled(hasValidSelection);
267            if (hasValidSelection) {
268                mListView.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(mListView.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 (mAlwaysUseOption) {
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<PatternMatcher> pIt = ri.filter.schemeSpecificPartsIterator();
330                    if (pIt != null) {
331                        String ssp = data.getSchemeSpecificPart();
332                        while (ssp != null && pIt.hasNext()) {
333                            PatternMatcher p = pIt.next();
334                            if (p.match(ssp)) {
335                                filter.addDataSchemeSpecificPart(p.getPath(), p.getType());
336                                break;
337                            }
338                        }
339                    }
340                    Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
341                    if (aIt != null) {
342                        while (aIt.hasNext()) {
343                            IntentFilter.AuthorityEntry a = aIt.next();
344                            if (a.match(data) >= 0) {
345                                int port = a.getPort();
346                                filter.addDataAuthority(a.getHost(),
347                                        port >= 0 ? Integer.toString(port) : null);
348                                break;
349                            }
350                        }
351                    }
352                    pIt = ri.filter.pathsIterator();
353                    if (pIt != null) {
354                        String path = data.getPath();
355                        while (path != null && pIt.hasNext()) {
356                            PatternMatcher p = pIt.next();
357                            if (p.match(path)) {
358                                filter.addDataPath(p.getPath(), p.getType());
359                                break;
360                            }
361                        }
362                    }
363                }
364            }
365
366            if (filter != null) {
367                final int N = mAdapter.mList.size();
368                ComponentName[] set = new ComponentName[N];
369                int bestMatch = 0;
370                for (int i=0; i<N; i++) {
371                    ResolveInfo r = mAdapter.mList.get(i).ri;
372                    set[i] = new ComponentName(r.activityInfo.packageName,
373                            r.activityInfo.name);
374                    if (r.match > bestMatch) bestMatch = r.match;
375                }
376                if (alwaysCheck) {
377                    getPackageManager().addPreferredActivity(filter, bestMatch, set,
378                            intent.getComponent());
379                } else {
380                    try {
381                        AppGlobals.getPackageManager().setLastChosenActivity(intent,
382                                intent.resolveTypeIfNeeded(getContentResolver()),
383                                PackageManager.MATCH_DEFAULT_ONLY,
384                                filter, bestMatch, intent.getComponent());
385                    } catch (RemoteException re) {
386                        Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
387                    }
388                }
389            }
390        }
391
392        if (intent != null) {
393            startActivity(intent);
394        }
395    }
396
397    void showAppDetails(ResolveInfo ri) {
398        Intent in = new Intent().setAction("android.settings.APPLICATION_DETAILS_SETTINGS")
399                .setData(Uri.fromParts("package", ri.activityInfo.packageName, null))
400                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
401        startActivity(in);
402    }
403
404    private final class DisplayResolveInfo {
405        ResolveInfo ri;
406        CharSequence displayLabel;
407        Drawable displayIcon;
408        CharSequence extendedInfo;
409        Intent origIntent;
410
411        DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel,
412                CharSequence pInfo, Intent pOrigIntent) {
413            ri = pri;
414            displayLabel = pLabel;
415            extendedInfo = pInfo;
416            origIntent = pOrigIntent;
417        }
418    }
419
420    private final class ResolveListAdapter extends BaseAdapter {
421        private final Intent[] mInitialIntents;
422        private final List<ResolveInfo> mBaseResolveList;
423        private ResolveInfo mLastChosen;
424        private final Intent mIntent;
425        private final int mLaunchedFromUid;
426        private final LayoutInflater mInflater;
427
428        private List<DisplayResolveInfo> mList;
429        private int mInitialHighlight = -1;
430
431        public ResolveListAdapter(Context context, Intent intent,
432                Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid) {
433            mIntent = new Intent(intent);
434            mIntent.setComponent(null);
435            mInitialIntents = initialIntents;
436            mBaseResolveList = rList;
437            mLaunchedFromUid = launchedFromUid;
438            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
439            mList = new ArrayList<DisplayResolveInfo>();
440            rebuildList();
441        }
442
443        public void handlePackagesChanged() {
444            final int oldItemCount = getCount();
445            rebuildList();
446            notifyDataSetChanged();
447            final int newItemCount = getCount();
448            if (newItemCount == 0) {
449                // We no longer have any items...  just finish the activity.
450                finish();
451            }
452        }
453
454        public int getInitialHighlight() {
455            return mInitialHighlight;
456        }
457
458        private void rebuildList() {
459            List<ResolveInfo> currentResolveList;
460
461            try {
462                mLastChosen = AppGlobals.getPackageManager().getLastChosenActivity(
463                        mIntent, mIntent.resolveTypeIfNeeded(getContentResolver()),
464                        PackageManager.MATCH_DEFAULT_ONLY);
465            } catch (RemoteException re) {
466                Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
467            }
468
469            mList.clear();
470            if (mBaseResolveList != null) {
471                currentResolveList = mBaseResolveList;
472            } else {
473                currentResolveList = mPm.queryIntentActivities(
474                        mIntent, PackageManager.MATCH_DEFAULT_ONLY
475                        | (mAlwaysUseOption ? PackageManager.GET_RESOLVED_FILTER : 0));
476                // Filter out any activities that the launched uid does not
477                // have permission for.  We don't do this when we have an explicit
478                // list of resolved activities, because that only happens when
479                // we are being subclassed, so we can safely launch whatever
480                // they gave us.
481                if (currentResolveList != null) {
482                    for (int i=currentResolveList.size()-1; i >= 0; i--) {
483                        ActivityInfo ai = currentResolveList.get(i).activityInfo;
484                        int granted = ActivityManager.checkComponentPermission(
485                                ai.permission, mLaunchedFromUid,
486                                ai.applicationInfo.uid, ai.exported);
487                        if (granted != PackageManager.PERMISSION_GRANTED) {
488                            // Access not allowed!
489                            currentResolveList.remove(i);
490                        }
491                    }
492                }
493            }
494            int N;
495            if ((currentResolveList != null) && ((N = currentResolveList.size()) > 0)) {
496                // Only display the first matches that are either of equal
497                // priority or have asked to be default options.
498                ResolveInfo r0 = currentResolveList.get(0);
499                for (int i=1; i<N; i++) {
500                    ResolveInfo ri = currentResolveList.get(i);
501                    if (DEBUG) Log.v(
502                        "ResolveListActivity",
503                        r0.activityInfo.name + "=" +
504                        r0.priority + "/" + r0.isDefault + " vs " +
505                        ri.activityInfo.name + "=" +
506                        ri.priority + "/" + ri.isDefault);
507                    if (r0.priority != ri.priority ||
508                        r0.isDefault != ri.isDefault) {
509                        while (i < N) {
510                            currentResolveList.remove(i);
511                            N--;
512                        }
513                    }
514                }
515                if (N > 1) {
516                    ResolveInfo.DisplayNameComparator rComparator =
517                            new ResolveInfo.DisplayNameComparator(mPm);
518                    Collections.sort(currentResolveList, rComparator);
519                }
520                // First put the initial items at the top.
521                if (mInitialIntents != null) {
522                    for (int i=0; i<mInitialIntents.length; i++) {
523                        Intent ii = mInitialIntents[i];
524                        if (ii == null) {
525                            continue;
526                        }
527                        ActivityInfo ai = ii.resolveActivityInfo(
528                                getPackageManager(), 0);
529                        if (ai == null) {
530                            Log.w("ResolverActivity", "No activity found for "
531                                    + ii);
532                            continue;
533                        }
534                        ResolveInfo ri = new ResolveInfo();
535                        ri.activityInfo = ai;
536                        if (ii instanceof LabeledIntent) {
537                            LabeledIntent li = (LabeledIntent)ii;
538                            ri.resolvePackageName = li.getSourcePackage();
539                            ri.labelRes = li.getLabelResource();
540                            ri.nonLocalizedLabel = li.getNonLocalizedLabel();
541                            ri.icon = li.getIconResource();
542                        }
543                        mList.add(new DisplayResolveInfo(ri,
544                                ri.loadLabel(getPackageManager()), null, ii));
545                    }
546                }
547
548                // Check for applications with same name and use application name or
549                // package name if necessary
550                r0 = currentResolveList.get(0);
551                int start = 0;
552                CharSequence r0Label =  r0.loadLabel(mPm);
553                mShowExtended = false;
554                for (int i = 1; i < N; i++) {
555                    if (r0Label == null) {
556                        r0Label = r0.activityInfo.packageName;
557                    }
558                    ResolveInfo ri = currentResolveList.get(i);
559                    CharSequence riLabel = ri.loadLabel(mPm);
560                    if (riLabel == null) {
561                        riLabel = ri.activityInfo.packageName;
562                    }
563                    if (riLabel.equals(r0Label)) {
564                        continue;
565                    }
566                    processGroup(currentResolveList, start, (i-1), r0, r0Label);
567                    r0 = ri;
568                    r0Label = riLabel;
569                    start = i;
570                }
571                // Process last group
572                processGroup(currentResolveList, start, (N-1), r0, r0Label);
573            }
574        }
575
576        private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro,
577                CharSequence roLabel) {
578            // Process labels from start to i
579            int num = end - start+1;
580            if (num == 1) {
581                if (mLastChosen != null
582                        && mLastChosen.activityInfo.packageName.equals(
583                                ro.activityInfo.packageName)
584                        && mLastChosen.activityInfo.name.equals(ro.activityInfo.name)) {
585                    mInitialHighlight = mList.size();
586                }
587                // No duplicate labels. Use label for entry at start
588                mList.add(new DisplayResolveInfo(ro, roLabel, null, null));
589            } else {
590                mShowExtended = true;
591                boolean usePkg = false;
592                CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm);
593                if (startApp == null) {
594                    usePkg = true;
595                }
596                if (!usePkg) {
597                    // Use HashSet to track duplicates
598                    HashSet<CharSequence> duplicates =
599                        new HashSet<CharSequence>();
600                    duplicates.add(startApp);
601                    for (int j = start+1; j <= end ; j++) {
602                        ResolveInfo jRi = rList.get(j);
603                        CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm);
604                        if ( (jApp == null) || (duplicates.contains(jApp))) {
605                            usePkg = true;
606                            break;
607                        } else {
608                            duplicates.add(jApp);
609                        }
610                    }
611                    // Clear HashSet for later use
612                    duplicates.clear();
613                }
614                for (int k = start; k <= end; k++) {
615                    ResolveInfo add = rList.get(k);
616                    if (mLastChosen != null
617                            && mLastChosen.activityInfo.packageName.equals(
618                                    add.activityInfo.packageName)
619                            && mLastChosen.activityInfo.name.equals(add.activityInfo.name)) {
620                        mInitialHighlight = mList.size();
621                    }
622                    if (usePkg) {
623                        // Use application name for all entries from start to end-1
624                        mList.add(new DisplayResolveInfo(add, roLabel,
625                                add.activityInfo.packageName, null));
626                    } else {
627                        // Use package name for all entries from start to end-1
628                        mList.add(new DisplayResolveInfo(add, roLabel,
629                                add.activityInfo.applicationInfo.loadLabel(mPm), null));
630                    }
631                }
632            }
633        }
634
635        public ResolveInfo resolveInfoForPosition(int position) {
636            return mList.get(position).ri;
637        }
638
639        public Intent intentForPosition(int position) {
640            DisplayResolveInfo dri = mList.get(position);
641
642            Intent intent = new Intent(dri.origIntent != null
643                    ? dri.origIntent : mIntent);
644            intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
645                    |Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
646            ActivityInfo ai = dri.ri.activityInfo;
647            intent.setComponent(new ComponentName(
648                    ai.applicationInfo.packageName, ai.name));
649            return intent;
650        }
651
652        public int getCount() {
653            return mList.size();
654        }
655
656        public Object getItem(int position) {
657            return mList.get(position);
658        }
659
660        public long getItemId(int position) {
661            return position;
662        }
663
664        public View getView(int position, View convertView, ViewGroup parent) {
665            View view;
666            if (convertView == null) {
667                view = mInflater.inflate(
668                        com.android.internal.R.layout.resolve_list_item, parent, false);
669
670                final ViewHolder holder = new ViewHolder(view);
671                view.setTag(holder);
672
673                // Fix the icon size even if we have different sized resources
674                ViewGroup.LayoutParams lp = holder.icon.getLayoutParams();
675                lp.width = lp.height = mIconSize;
676            } else {
677                view = convertView;
678            }
679            bindView(view, mList.get(position));
680            return view;
681        }
682
683        private final void bindView(View view, DisplayResolveInfo info) {
684            final ViewHolder holder = (ViewHolder) view.getTag();
685            holder.text.setText(info.displayLabel);
686            if (mShowExtended) {
687                holder.text2.setVisibility(View.VISIBLE);
688                holder.text2.setText(info.extendedInfo);
689            } else {
690                holder.text2.setVisibility(View.GONE);
691            }
692            if (info.displayIcon == null) {
693                new LoadIconTask().execute(info);
694            }
695            holder.icon.setImageDrawable(info.displayIcon);
696        }
697    }
698
699    static class ViewHolder {
700        public TextView text;
701        public TextView text2;
702        public ImageView icon;
703
704        public ViewHolder(View view) {
705            text = (TextView) view.findViewById(com.android.internal.R.id.text1);
706            text2 = (TextView) view.findViewById(com.android.internal.R.id.text2);
707            icon = (ImageView) view.findViewById(R.id.icon);
708        }
709    }
710
711    class ItemLongClickListener implements AdapterView.OnItemLongClickListener {
712
713        @Override
714        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
715            ResolveInfo ri = mAdapter.resolveInfoForPosition(position);
716            showAppDetails(ri);
717            return true;
718        }
719
720    }
721
722    class LoadIconTask extends AsyncTask<DisplayResolveInfo, Void, DisplayResolveInfo> {
723        @Override
724        protected DisplayResolveInfo doInBackground(DisplayResolveInfo... params) {
725            final DisplayResolveInfo info = params[0];
726            if (info.displayIcon == null) {
727                info.displayIcon = loadIconForResolveInfo(info.ri);
728            }
729            return info;
730        }
731
732        @Override
733        protected void onPostExecute(DisplayResolveInfo info) {
734            mAdapter.notifyDataSetChanged();
735        }
736    }
737}
738
739