ResolverActivity.java revision 27c3ab630afd6296ff1ff7b2b71638caa8f2ec54
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.app.Activity;
20import android.app.ActivityThread;
21import android.app.usage.UsageStats;
22import android.app.usage.UsageStatsManager;
23import android.os.AsyncTask;
24import android.provider.Settings;
25import android.text.TextUtils;
26import android.util.Slog;
27import android.widget.AbsListView;
28import com.android.internal.R;
29import com.android.internal.content.PackageMonitor;
30
31import android.app.ActivityManager;
32import android.app.ActivityManagerNative;
33import android.app.AppGlobals;
34import android.content.ComponentName;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.pm.ActivityInfo;
39import android.content.pm.ApplicationInfo;
40import android.content.pm.LabeledIntent;
41import android.content.pm.PackageManager;
42import android.content.pm.PackageManager.NameNotFoundException;
43import android.content.pm.ResolveInfo;
44import android.content.pm.UserInfo;
45import android.content.res.Resources;
46import android.graphics.drawable.Drawable;
47import android.net.Uri;
48import android.os.Build;
49import android.os.Bundle;
50import android.os.PatternMatcher;
51import android.os.RemoteException;
52import android.os.UserHandle;
53import android.os.UserManager;
54import android.util.Log;
55import android.view.LayoutInflater;
56import android.view.View;
57import android.view.ViewGroup;
58import android.widget.AdapterView;
59import android.widget.BaseAdapter;
60import android.widget.Button;
61import android.widget.ImageView;
62import android.widget.ListView;
63import android.widget.TextView;
64import android.widget.Toast;
65import com.android.internal.widget.ResolverDrawerLayout;
66
67import java.text.Collator;
68import java.util.ArrayList;
69import java.util.Collections;
70import java.util.Comparator;
71import java.util.HashSet;
72import java.util.Iterator;
73import java.util.List;
74import java.util.Map;
75import java.util.Set;
76
77import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
78import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
79
80/**
81 * This activity is displayed when the system attempts to start an Intent for
82 * which there is more than one matching activity, allowing the user to decide
83 * which to go to.  It is not normally used directly by application developers.
84 */
85public class ResolverActivity extends Activity implements AdapterView.OnItemClickListener {
86    private static final String TAG = "ResolverActivity";
87    private static final boolean DEBUG = false;
88
89    private int mLaunchedFromUid;
90    private ResolveListAdapter mAdapter;
91    private PackageManager mPm;
92    private boolean mSafeForwardingMode;
93    private boolean mAlwaysUseOption;
94    private boolean mShowExtended;
95    private ListView mListView;
96    private Button mAlwaysButton;
97    private Button mOnceButton;
98    private int mIconDpi;
99    private int mIconSize;
100    private int mMaxColumns;
101    private int mLastSelected = ListView.INVALID_POSITION;
102    private boolean mResolvingHome = false;
103
104    private UsageStatsManager mUsm;
105    private Map<String, UsageStats> mStats;
106    private static final long USAGE_STATS_PERIOD = 1000 * 60 * 60 * 24 * 14;
107
108    private boolean mRegistered;
109    private final PackageMonitor mPackageMonitor = new PackageMonitor() {
110        @Override public void onSomePackagesChanged() {
111            mAdapter.handlePackagesChanged();
112        }
113    };
114
115    private enum ActionTitle {
116        VIEW(Intent.ACTION_VIEW,
117                com.android.internal.R.string.whichViewApplication,
118                com.android.internal.R.string.whichViewApplicationNamed),
119        EDIT(Intent.ACTION_EDIT,
120                com.android.internal.R.string.whichEditApplication,
121                com.android.internal.R.string.whichEditApplicationNamed),
122        SEND(Intent.ACTION_SEND,
123                com.android.internal.R.string.whichSendApplication,
124                com.android.internal.R.string.whichSendApplicationNamed),
125        SENDTO(Intent.ACTION_SENDTO,
126                com.android.internal.R.string.whichSendApplication,
127                com.android.internal.R.string.whichSendApplicationNamed),
128        SEND_MULTIPLE(Intent.ACTION_SEND_MULTIPLE,
129                com.android.internal.R.string.whichSendApplication,
130                com.android.internal.R.string.whichSendApplicationNamed),
131        DEFAULT(null,
132                com.android.internal.R.string.whichApplication,
133                com.android.internal.R.string.whichApplicationNamed),
134        HOME(Intent.ACTION_MAIN,
135                com.android.internal.R.string.whichHomeApplication,
136                com.android.internal.R.string.whichHomeApplicationNamed);
137
138        public final String action;
139        public final int titleRes;
140        public final int namedTitleRes;
141
142        ActionTitle(String action, int titleRes, int namedTitleRes) {
143            this.action = action;
144            this.titleRes = titleRes;
145            this.namedTitleRes = namedTitleRes;
146        }
147
148        public static ActionTitle forAction(String action) {
149            for (ActionTitle title : values()) {
150                if (title != HOME && action != null && action.equals(title.action)) {
151                    return title;
152                }
153            }
154            return DEFAULT;
155        }
156    }
157
158    private Intent makeMyIntent() {
159        Intent intent = new Intent(getIntent());
160        intent.setComponent(null);
161        // The resolver activity is set to be hidden from recent tasks.
162        // we don't want this attribute to be propagated to the next activity
163        // being launched.  Note that if the original Intent also had this
164        // flag set, we are now losing it.  That should be a very rare case
165        // and we can live with this.
166        intent.setFlags(intent.getFlags()&~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
167        return intent;
168    }
169
170    @Override
171    protected void onCreate(Bundle savedInstanceState) {
172        // Use a specialized prompt when we're handling the 'Home' app startActivity()
173        final Intent intent = makeMyIntent();
174        final Set<String> categories = intent.getCategories();
175        if (Intent.ACTION_MAIN.equals(intent.getAction())
176                && categories != null
177                && categories.size() == 1
178                && categories.contains(Intent.CATEGORY_HOME)) {
179            // Note: this field is not set to true in the compatibility version.
180            mResolvingHome = true;
181        }
182
183        setSafeForwardingMode(true);
184
185        onCreate(savedInstanceState, intent, null, 0, null, null, true);
186    }
187
188    /**
189     * Compatibility version for other bundled services that use this ocerload without
190     * a default title resource
191     */
192    protected void onCreate(Bundle savedInstanceState, Intent intent,
193            CharSequence title, Intent[] initialIntents,
194            List<ResolveInfo> rList, boolean alwaysUseOption) {
195        onCreate(savedInstanceState, intent, title, 0, initialIntents, rList, alwaysUseOption);
196    }
197
198    protected void onCreate(Bundle savedInstanceState, Intent intent,
199            CharSequence title, int defaultTitleRes, Intent[] initialIntents,
200            List<ResolveInfo> rList, boolean alwaysUseOption) {
201        setTheme(R.style.Theme_DeviceDefault_Resolver);
202        super.onCreate(savedInstanceState);
203        try {
204            mLaunchedFromUid = ActivityManagerNative.getDefault().getLaunchedFromUid(
205                    getActivityToken());
206        } catch (RemoteException e) {
207            mLaunchedFromUid = -1;
208        }
209        mPm = getPackageManager();
210        mUsm = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
211
212        final long sinceTime = System.currentTimeMillis() - USAGE_STATS_PERIOD;
213        mStats = mUsm.queryAndAggregateUsageStats(sinceTime, System.currentTimeMillis());
214        Log.d(TAG, "sinceTime=" + sinceTime);
215
216        mMaxColumns = getResources().getInteger(R.integer.config_maxResolverActivityColumns);
217
218        mPackageMonitor.register(this, getMainLooper(), false);
219        mRegistered = true;
220
221        final ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
222        mIconDpi = am.getLauncherLargeIconDensity();
223        mIconSize = am.getLauncherLargeIconSize();
224
225        mAdapter = new ResolveListAdapter(this, intent, initialIntents, rList,
226                mLaunchedFromUid, alwaysUseOption);
227
228        final int layoutId;
229        final boolean useHeader;
230        if (mAdapter.hasFilteredItem()) {
231            layoutId = R.layout.resolver_list_with_default;
232            alwaysUseOption = false;
233            useHeader = true;
234        } else {
235            useHeader = false;
236            layoutId = R.layout.resolver_list;
237        }
238        mAlwaysUseOption = alwaysUseOption;
239
240        int count = mAdapter.mList.size();
241        if (mLaunchedFromUid < 0 || UserHandle.isIsolated(mLaunchedFromUid)) {
242            // Gulp!
243            finish();
244            return;
245        } else if (count > 1) {
246            setContentView(layoutId);
247            mListView = (ListView) findViewById(R.id.resolver_list);
248            mListView.setAdapter(mAdapter);
249            mListView.setOnItemClickListener(this);
250            mListView.setOnItemLongClickListener(new ItemLongClickListener());
251
252            if (alwaysUseOption) {
253                mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
254            }
255
256            if (useHeader) {
257                mListView.addHeaderView(LayoutInflater.from(this).inflate(
258                        R.layout.resolver_different_item_header, mListView, false));
259            }
260        } else if (count == 1) {
261            safelyStartActivity(mAdapter.intentForPosition(0, false));
262            mPackageMonitor.unregister();
263            mRegistered = false;
264            finish();
265            return;
266        } else {
267            setContentView(R.layout.resolver_list);
268
269            final TextView empty = (TextView) findViewById(R.id.empty);
270            empty.setVisibility(View.VISIBLE);
271
272            mListView = (ListView) findViewById(R.id.resolver_list);
273            mListView.setVisibility(View.GONE);
274        }
275        // Prevent the Resolver window from becoming the top fullscreen window and thus from taking
276        // control of the system bars.
277        getWindow().clearFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR);
278
279        final ResolverDrawerLayout rdl = (ResolverDrawerLayout) findViewById(R.id.contentPanel);
280        if (rdl != null) {
281            rdl.setOnClickOutsideListener(new View.OnClickListener() {
282                @Override
283                public void onClick(View v) {
284                    finish();
285                }
286            });
287        }
288
289        if (title == null) {
290            title = getTitleForAction(intent.getAction(), defaultTitleRes);
291        }
292        if (!TextUtils.isEmpty(title)) {
293            final TextView titleView = (TextView) findViewById(R.id.title);
294            if (titleView != null) {
295                titleView.setText(title);
296            }
297            setTitle(title);
298        }
299
300        final ImageView iconView = (ImageView) findViewById(R.id.icon);
301        final DisplayResolveInfo iconInfo = mAdapter.getFilteredItem();
302        if (iconView != null && iconInfo != null) {
303            new LoadIconIntoViewTask(iconView).execute(iconInfo);
304        }
305
306        if (alwaysUseOption || mAdapter.hasFilteredItem()) {
307            final ViewGroup buttonLayout = (ViewGroup) findViewById(R.id.button_bar);
308            if (buttonLayout != null) {
309                buttonLayout.setVisibility(View.VISIBLE);
310                mAlwaysButton = (Button) buttonLayout.findViewById(R.id.button_always);
311                mOnceButton = (Button) buttonLayout.findViewById(R.id.button_once);
312            } else {
313                mAlwaysUseOption = false;
314            }
315        }
316
317        if (mAdapter.hasFilteredItem()) {
318            setAlwaysButtonEnabled(true, mAdapter.getFilteredPosition(), false);
319            mOnceButton.setEnabled(true);
320        }
321    }
322
323    /**
324     * Turn on launch mode that is safe to use when forwarding intents received from
325     * applications and running in system processes.  This mode uses Activity.startActivityAsCaller
326     * instead of the normal Activity.startActivity for launching the activity selected
327     * by the user.
328     *
329     * <p>This mode is set to true by default if the activity is initialized through
330     * {@link #onCreate(android.os.Bundle)}.  If a subclass calls one of the other onCreate
331     * methods, it is set to false by default.  You must set it before calling one of the
332     * more detailed onCreate methods, so that it will be set correctly in the case where
333     * there is only one intent to resolve and it is thus started immediately.</p>
334     */
335    public void setSafeForwardingMode(boolean safeForwarding) {
336        mSafeForwardingMode = safeForwarding;
337    }
338
339    protected CharSequence getTitleForAction(String action, int defaultTitleRes) {
340        final ActionTitle title = mResolvingHome ? ActionTitle.HOME : ActionTitle.forAction(action);
341        final boolean named = mAdapter.hasFilteredItem();
342        if (title == ActionTitle.DEFAULT && defaultTitleRes != 0) {
343            return getString(defaultTitleRes);
344        } else {
345            return named ? getString(title.namedTitleRes, mAdapter.getFilteredItem().displayLabel) :
346                    getString(title.titleRes);
347        }
348    }
349
350    void dismiss() {
351        if (!isFinishing()) {
352            finish();
353        }
354    }
355
356    Drawable getIcon(Resources res, int resId) {
357        Drawable result;
358        try {
359            result = res.getDrawableForDensity(resId, mIconDpi);
360        } catch (Resources.NotFoundException e) {
361            result = null;
362        }
363
364        return result;
365    }
366
367    Drawable loadIconForResolveInfo(ResolveInfo ri) {
368        Drawable dr;
369        try {
370            if (ri.resolvePackageName != null && ri.icon != 0) {
371                dr = getIcon(mPm.getResourcesForApplication(ri.resolvePackageName), ri.icon);
372                if (dr != null) {
373                    return dr;
374                }
375            }
376            final int iconRes = ri.getIconResource();
377            if (iconRes != 0) {
378                dr = getIcon(mPm.getResourcesForApplication(ri.activityInfo.packageName), iconRes);
379                if (dr != null) {
380                    return dr;
381                }
382            }
383        } catch (NameNotFoundException e) {
384            Log.e(TAG, "Couldn't find resources for package", e);
385        }
386        return ri.loadIcon(mPm);
387    }
388
389    @Override
390    protected void onRestart() {
391        super.onRestart();
392        if (!mRegistered) {
393            mPackageMonitor.register(this, getMainLooper(), false);
394            mRegistered = true;
395        }
396        mAdapter.handlePackagesChanged();
397    }
398
399    @Override
400    protected void onStop() {
401        super.onStop();
402        if (mRegistered) {
403            mPackageMonitor.unregister();
404            mRegistered = false;
405        }
406        if ((getIntent().getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
407            // This resolver is in the unusual situation where it has been
408            // launched at the top of a new task.  We don't let it be added
409            // to the recent tasks shown to the user, and we need to make sure
410            // that each time we are launched we get the correct launching
411            // uid (not re-using the same resolver from an old launching uid),
412            // so we will now finish ourself since being no longer visible,
413            // the user probably can't get back to us.
414            if (!isChangingConfigurations()) {
415                finish();
416            }
417        }
418    }
419
420    @Override
421    protected void onRestoreInstanceState(Bundle savedInstanceState) {
422        super.onRestoreInstanceState(savedInstanceState);
423        if (mAlwaysUseOption) {
424            final int checkedPos = mListView.getCheckedItemPosition();
425            final boolean hasValidSelection = checkedPos != ListView.INVALID_POSITION;
426            mLastSelected = checkedPos;
427            setAlwaysButtonEnabled(hasValidSelection, checkedPos, true);
428            mOnceButton.setEnabled(hasValidSelection);
429            if (hasValidSelection) {
430                mListView.setSelection(checkedPos);
431            }
432        }
433    }
434
435    @Override
436    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
437        position -= mListView.getHeaderViewsCount();
438        if (position < 0) {
439            // Header views don't count.
440            return;
441        }
442        ResolveInfo resolveInfo = mAdapter.resolveInfoForPosition(position, true);
443        if (mResolvingHome && hasManagedProfile()
444                && !supportsManagedProfiles(resolveInfo)) {
445            Toast.makeText(this, String.format(getResources().getString(
446                    com.android.internal.R.string.activity_resolver_work_profiles_support),
447                    resolveInfo.activityInfo.loadLabel(getPackageManager()).toString()),
448                    Toast.LENGTH_LONG).show();
449            return;
450        }
451        final int checkedPos = mListView.getCheckedItemPosition();
452        final boolean hasValidSelection = checkedPos != ListView.INVALID_POSITION;
453        if (mAlwaysUseOption && (!hasValidSelection || mLastSelected != checkedPos)) {
454            setAlwaysButtonEnabled(hasValidSelection, checkedPos, true);
455            mOnceButton.setEnabled(hasValidSelection);
456            if (hasValidSelection) {
457                mListView.smoothScrollToPosition(checkedPos);
458            }
459            mLastSelected = checkedPos;
460        } else {
461            startSelected(position, false, true);
462        }
463    }
464
465    private boolean hasManagedProfile() {
466        UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
467        if (userManager == null) {
468            return false;
469        }
470
471        try {
472            List<UserInfo> profiles = userManager.getProfiles(getUserId());
473            for (UserInfo userInfo : profiles) {
474                if (userInfo != null && userInfo.isManagedProfile()) {
475                    return true;
476                }
477            }
478        } catch (SecurityException e) {
479            return false;
480        }
481        return false;
482    }
483
484    private boolean supportsManagedProfiles(ResolveInfo resolveInfo) {
485        try {
486            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(
487                    resolveInfo.activityInfo.packageName, 0 /* default flags */);
488            return versionNumberAtLeastL(appInfo.targetSdkVersion);
489        } catch (NameNotFoundException e) {
490            return false;
491        }
492    }
493
494    private boolean versionNumberAtLeastL(int versionNumber) {
495        return versionNumber >= Build.VERSION_CODES.LOLLIPOP;
496    }
497
498    private void setAlwaysButtonEnabled(boolean hasValidSelection, int checkedPos,
499            boolean filtered) {
500        boolean enabled = false;
501        if (hasValidSelection) {
502            ResolveInfo ri = mAdapter.resolveInfoForPosition(checkedPos, filtered);
503            if (ri.targetUserId == UserHandle.USER_CURRENT) {
504                enabled = true;
505            }
506        }
507        mAlwaysButton.setEnabled(enabled);
508    }
509
510    public void onButtonClick(View v) {
511        final int id = v.getId();
512        startSelected(mAlwaysUseOption ?
513                mListView.getCheckedItemPosition() : mAdapter.getFilteredPosition(),
514                id == R.id.button_always,
515                mAlwaysUseOption);
516        dismiss();
517    }
518
519    void startSelected(int which, boolean always, boolean filtered) {
520        if (isFinishing()) {
521            return;
522        }
523        ResolveInfo ri = mAdapter.resolveInfoForPosition(which, filtered);
524        Intent intent = mAdapter.intentForPosition(which, filtered);
525        onIntentSelected(ri, intent, always);
526        finish();
527    }
528
529    /**
530     * Replace me in subclasses!
531     */
532    public Intent getReplacementIntent(String packageName, Intent defIntent) {
533        return defIntent;
534    }
535
536    protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {
537        if ((mAlwaysUseOption || mAdapter.hasFilteredItem()) && mAdapter.mOrigResolveList != null) {
538            // Build a reasonable intent filter, based on what matched.
539            IntentFilter filter = new IntentFilter();
540
541            if (intent.getAction() != null) {
542                filter.addAction(intent.getAction());
543            }
544            Set<String> categories = intent.getCategories();
545            if (categories != null) {
546                for (String cat : categories) {
547                    filter.addCategory(cat);
548                }
549            }
550            filter.addCategory(Intent.CATEGORY_DEFAULT);
551
552            int cat = ri.match&IntentFilter.MATCH_CATEGORY_MASK;
553            Uri data = intent.getData();
554            if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
555                String mimeType = intent.resolveType(this);
556                if (mimeType != null) {
557                    try {
558                        filter.addDataType(mimeType);
559                    } catch (IntentFilter.MalformedMimeTypeException e) {
560                        Log.w("ResolverActivity", e);
561                        filter = null;
562                    }
563                }
564            }
565            if (data != null && data.getScheme() != null) {
566                // We need the data specification if there was no type,
567                // OR if the scheme is not one of our magical "file:"
568                // or "content:" schemes (see IntentFilter for the reason).
569                if (cat != IntentFilter.MATCH_CATEGORY_TYPE
570                        || (!"file".equals(data.getScheme())
571                                && !"content".equals(data.getScheme()))) {
572                    filter.addDataScheme(data.getScheme());
573
574                    // Look through the resolved filter to determine which part
575                    // of it matched the original Intent.
576                    Iterator<PatternMatcher> pIt = ri.filter.schemeSpecificPartsIterator();
577                    if (pIt != null) {
578                        String ssp = data.getSchemeSpecificPart();
579                        while (ssp != null && pIt.hasNext()) {
580                            PatternMatcher p = pIt.next();
581                            if (p.match(ssp)) {
582                                filter.addDataSchemeSpecificPart(p.getPath(), p.getType());
583                                break;
584                            }
585                        }
586                    }
587                    Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
588                    if (aIt != null) {
589                        while (aIt.hasNext()) {
590                            IntentFilter.AuthorityEntry a = aIt.next();
591                            if (a.match(data) >= 0) {
592                                int port = a.getPort();
593                                filter.addDataAuthority(a.getHost(),
594                                        port >= 0 ? Integer.toString(port) : null);
595                                break;
596                            }
597                        }
598                    }
599                    pIt = ri.filter.pathsIterator();
600                    if (pIt != null) {
601                        String path = data.getPath();
602                        while (path != null && pIt.hasNext()) {
603                            PatternMatcher p = pIt.next();
604                            if (p.match(path)) {
605                                filter.addDataPath(p.getPath(), p.getType());
606                                break;
607                            }
608                        }
609                    }
610                }
611            }
612
613            if (filter != null) {
614                final int N = mAdapter.mOrigResolveList.size();
615                ComponentName[] set = new ComponentName[N];
616                int bestMatch = 0;
617                for (int i=0; i<N; i++) {
618                    ResolveInfo r = mAdapter.mOrigResolveList.get(i);
619                    set[i] = new ComponentName(r.activityInfo.packageName,
620                            r.activityInfo.name);
621                    if (r.match > bestMatch) bestMatch = r.match;
622                }
623                if (alwaysCheck) {
624                    getPackageManager().addPreferredActivity(filter, bestMatch, set,
625                            intent.getComponent());
626                } else {
627                    try {
628                        AppGlobals.getPackageManager().setLastChosenActivity(intent,
629                                intent.resolveTypeIfNeeded(getContentResolver()),
630                                PackageManager.MATCH_DEFAULT_ONLY,
631                                filter, bestMatch, intent.getComponent());
632                    } catch (RemoteException re) {
633                        Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
634                    }
635                }
636            }
637        }
638
639        if (intent != null) {
640            safelyStartActivity(intent);
641        }
642    }
643
644    public void safelyStartActivity(Intent intent) {
645        if (!mSafeForwardingMode) {
646            startActivity(intent);
647            return;
648        }
649        try {
650            startActivityAsCaller(intent, null, UserHandle.USER_NULL);
651        } catch (RuntimeException e) {
652            String launchedFromPackage;
653            try {
654                launchedFromPackage = ActivityManagerNative.getDefault().getLaunchedFromPackage(
655                        getActivityToken());
656            } catch (RemoteException e2) {
657                launchedFromPackage = "??";
658            }
659            Slog.wtf(TAG, "Unable to launch as uid " + mLaunchedFromUid
660                    + " package " + launchedFromPackage + ", while running in "
661                    + ActivityThread.currentProcessName(), e);
662        }
663    }
664
665    void showAppDetails(ResolveInfo ri) {
666        Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
667                .setData(Uri.fromParts("package", ri.activityInfo.packageName, null))
668                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
669        startActivity(in);
670    }
671
672    private final class DisplayResolveInfo {
673        ResolveInfo ri;
674        CharSequence displayLabel;
675        Drawable displayIcon;
676        CharSequence extendedInfo;
677        Intent origIntent;
678
679        DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel,
680                CharSequence pInfo, Intent pOrigIntent) {
681            ri = pri;
682            displayLabel = pLabel;
683            extendedInfo = pInfo;
684            origIntent = pOrigIntent;
685        }
686    }
687
688    private final class ResolveListAdapter extends BaseAdapter {
689        private final Intent[] mInitialIntents;
690        private final List<ResolveInfo> mBaseResolveList;
691        private ResolveInfo mLastChosen;
692        private final Intent mIntent;
693        private final int mLaunchedFromUid;
694        private final LayoutInflater mInflater;
695
696        List<DisplayResolveInfo> mList;
697        List<ResolveInfo> mOrigResolveList;
698
699        private int mLastChosenPosition = -1;
700        private boolean mFilterLastUsed;
701
702        public ResolveListAdapter(Context context, Intent intent,
703                Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
704                boolean filterLastUsed) {
705            mIntent = new Intent(intent);
706            mInitialIntents = initialIntents;
707            mBaseResolveList = rList;
708            mLaunchedFromUid = launchedFromUid;
709            mInflater = LayoutInflater.from(context);
710            mList = new ArrayList<DisplayResolveInfo>();
711            mFilterLastUsed = filterLastUsed;
712            rebuildList();
713        }
714
715        public void handlePackagesChanged() {
716            final int oldItemCount = getCount();
717            rebuildList();
718            notifyDataSetChanged();
719            final int newItemCount = getCount();
720            if (newItemCount == 0) {
721                // We no longer have any items...  just finish the activity.
722                finish();
723            }
724        }
725
726        public DisplayResolveInfo getFilteredItem() {
727            if (mFilterLastUsed && mLastChosenPosition >= 0) {
728                // Not using getItem since it offsets to dodge this position for the list
729                return mList.get(mLastChosenPosition);
730            }
731            return null;
732        }
733
734        public int getFilteredPosition() {
735            if (mFilterLastUsed && mLastChosenPosition >= 0) {
736                return mLastChosenPosition;
737            }
738            return AbsListView.INVALID_POSITION;
739        }
740
741        public boolean hasFilteredItem() {
742            return mFilterLastUsed && mLastChosenPosition >= 0;
743        }
744
745        private void rebuildList() {
746            List<ResolveInfo> currentResolveList;
747
748            try {
749                mLastChosen = AppGlobals.getPackageManager().getLastChosenActivity(
750                        mIntent, mIntent.resolveTypeIfNeeded(getContentResolver()),
751                        PackageManager.MATCH_DEFAULT_ONLY);
752            } catch (RemoteException re) {
753                Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
754            }
755
756            mList.clear();
757            if (mBaseResolveList != null) {
758                currentResolveList = mOrigResolveList = mBaseResolveList;
759            } else {
760                currentResolveList = mOrigResolveList = mPm.queryIntentActivities(
761                        mIntent, PackageManager.MATCH_DEFAULT_ONLY
762                        | (mFilterLastUsed ? PackageManager.GET_RESOLVED_FILTER : 0));
763                // Filter out any activities that the launched uid does not
764                // have permission for.  We don't do this when we have an explicit
765                // list of resolved activities, because that only happens when
766                // we are being subclassed, so we can safely launch whatever
767                // they gave us.
768                if (currentResolveList != null) {
769                    for (int i=currentResolveList.size()-1; i >= 0; i--) {
770                        ActivityInfo ai = currentResolveList.get(i).activityInfo;
771                        int granted = ActivityManager.checkComponentPermission(
772                                ai.permission, mLaunchedFromUid,
773                                ai.applicationInfo.uid, ai.exported);
774                        if (granted != PackageManager.PERMISSION_GRANTED) {
775                            // Access not allowed!
776                            if (mOrigResolveList == currentResolveList) {
777                                mOrigResolveList = new ArrayList<ResolveInfo>(mOrigResolveList);
778                            }
779                            currentResolveList.remove(i);
780                        }
781                    }
782                }
783            }
784            int N;
785            if ((currentResolveList != null) && ((N = currentResolveList.size()) > 0)) {
786                // Only display the first matches that are either of equal
787                // priority or have asked to be default options.
788                ResolveInfo r0 = currentResolveList.get(0);
789                for (int i=1; i<N; i++) {
790                    ResolveInfo ri = currentResolveList.get(i);
791                    if (DEBUG) Log.v(
792                        TAG,
793                        r0.activityInfo.name + "=" +
794                        r0.priority + "/" + r0.isDefault + " vs " +
795                        ri.activityInfo.name + "=" +
796                        ri.priority + "/" + ri.isDefault);
797                    if (r0.priority != ri.priority ||
798                        r0.isDefault != ri.isDefault) {
799                        while (i < N) {
800                            if (mOrigResolveList == currentResolveList) {
801                                mOrigResolveList = new ArrayList<ResolveInfo>(mOrigResolveList);
802                            }
803                            currentResolveList.remove(i);
804                            N--;
805                        }
806                    }
807                }
808                if (N > 1) {
809                    Comparator<ResolveInfo> rComparator =
810                            new ResolverComparator(ResolverActivity.this);
811                    Collections.sort(currentResolveList, rComparator);
812                }
813                // First put the initial items at the top.
814                if (mInitialIntents != null) {
815                    for (int i=0; i<mInitialIntents.length; i++) {
816                        Intent ii = mInitialIntents[i];
817                        if (ii == null) {
818                            continue;
819                        }
820                        ActivityInfo ai = ii.resolveActivityInfo(
821                                getPackageManager(), 0);
822                        if (ai == null) {
823                            Log.w(TAG, "No activity found for " + ii);
824                            continue;
825                        }
826                        ResolveInfo ri = new ResolveInfo();
827                        ri.activityInfo = ai;
828                        UserManager userManager =
829                                (UserManager) getSystemService(Context.USER_SERVICE);
830                        if (userManager.isManagedProfile()) {
831                            ri.noResourceId = true;
832                        }
833                        if (ii instanceof LabeledIntent) {
834                            LabeledIntent li = (LabeledIntent)ii;
835                            ri.resolvePackageName = li.getSourcePackage();
836                            ri.labelRes = li.getLabelResource();
837                            ri.nonLocalizedLabel = li.getNonLocalizedLabel();
838                            ri.icon = li.getIconResource();
839                        }
840                        mList.add(new DisplayResolveInfo(ri,
841                                ri.loadLabel(getPackageManager()), null, ii));
842                    }
843                }
844
845                // Check for applications with same name and use application name or
846                // package name if necessary
847                r0 = currentResolveList.get(0);
848                int start = 0;
849                CharSequence r0Label =  r0.loadLabel(mPm);
850                mShowExtended = false;
851                for (int i = 1; i < N; i++) {
852                    if (r0Label == null) {
853                        r0Label = r0.activityInfo.packageName;
854                    }
855                    ResolveInfo ri = currentResolveList.get(i);
856                    CharSequence riLabel = ri.loadLabel(mPm);
857                    if (riLabel == null) {
858                        riLabel = ri.activityInfo.packageName;
859                    }
860                    if (riLabel.equals(r0Label)) {
861                        continue;
862                    }
863                    processGroup(currentResolveList, start, (i-1), r0, r0Label);
864                    r0 = ri;
865                    r0Label = riLabel;
866                    start = i;
867                }
868                // Process last group
869                processGroup(currentResolveList, start, (N-1), r0, r0Label);
870            }
871        }
872
873        private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro,
874                CharSequence roLabel) {
875            // Process labels from start to i
876            int num = end - start+1;
877            if (num == 1) {
878                if (mLastChosen != null
879                        && mLastChosen.activityInfo.packageName.equals(
880                                ro.activityInfo.packageName)
881                        && mLastChosen.activityInfo.name.equals(ro.activityInfo.name)) {
882                    mLastChosenPosition = mList.size();
883                }
884                // No duplicate labels. Use label for entry at start
885                mList.add(new DisplayResolveInfo(ro, roLabel, null, null));
886            } else {
887                mShowExtended = true;
888                boolean usePkg = false;
889                CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm);
890                if (startApp == null) {
891                    usePkg = true;
892                }
893                if (!usePkg) {
894                    // Use HashSet to track duplicates
895                    HashSet<CharSequence> duplicates =
896                        new HashSet<CharSequence>();
897                    duplicates.add(startApp);
898                    for (int j = start+1; j <= end ; j++) {
899                        ResolveInfo jRi = rList.get(j);
900                        CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm);
901                        if ( (jApp == null) || (duplicates.contains(jApp))) {
902                            usePkg = true;
903                            break;
904                        } else {
905                            duplicates.add(jApp);
906                        }
907                    }
908                    // Clear HashSet for later use
909                    duplicates.clear();
910                }
911                for (int k = start; k <= end; k++) {
912                    ResolveInfo add = rList.get(k);
913                    if (mLastChosen != null
914                            && mLastChosen.activityInfo.packageName.equals(
915                                    add.activityInfo.packageName)
916                            && mLastChosen.activityInfo.name.equals(add.activityInfo.name)) {
917                        mLastChosenPosition = mList.size();
918                    }
919                    if (usePkg) {
920                        // Use application name for all entries from start to end-1
921                        mList.add(new DisplayResolveInfo(add, roLabel,
922                                add.activityInfo.packageName, null));
923                    } else {
924                        // Use package name for all entries from start to end-1
925                        mList.add(new DisplayResolveInfo(add, roLabel,
926                                add.activityInfo.applicationInfo.loadLabel(mPm), null));
927                    }
928                }
929            }
930        }
931
932        public ResolveInfo resolveInfoForPosition(int position, boolean filtered) {
933            return (filtered ? getItem(position) : mList.get(position)).ri;
934        }
935
936        public Intent intentForPosition(int position, boolean filtered) {
937            DisplayResolveInfo dri = filtered ? getItem(position) : mList.get(position);
938
939            Intent intent = new Intent(dri.origIntent != null ? dri.origIntent :
940                    getReplacementIntent(dri.ri.activityInfo.packageName, mIntent));
941            intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
942                    |Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
943            ActivityInfo ai = dri.ri.activityInfo;
944            intent.setComponent(new ComponentName(
945                    ai.applicationInfo.packageName, ai.name));
946            return intent;
947        }
948
949        public int getCount() {
950            int result = mList.size();
951            if (mFilterLastUsed && mLastChosenPosition >= 0) {
952                result--;
953            }
954            return result;
955        }
956
957        public DisplayResolveInfo getItem(int position) {
958            if (mFilterLastUsed && mLastChosenPosition >= 0 && position >= mLastChosenPosition) {
959                position++;
960            }
961            return mList.get(position);
962        }
963
964        public long getItemId(int position) {
965            return position;
966        }
967
968        public View getView(int position, View convertView, ViewGroup parent) {
969            View view = convertView;
970            if (view == null) {
971                view = mInflater.inflate(
972                        com.android.internal.R.layout.resolve_list_item, parent, false);
973
974                final ViewHolder holder = new ViewHolder(view);
975                view.setTag(holder);
976            }
977            bindView(view, getItem(position));
978            return view;
979        }
980
981        private final void bindView(View view, DisplayResolveInfo info) {
982            final ViewHolder holder = (ViewHolder) view.getTag();
983            holder.text.setText(info.displayLabel);
984            if (mShowExtended) {
985                holder.text2.setVisibility(View.VISIBLE);
986                holder.text2.setText(info.extendedInfo);
987            } else {
988                holder.text2.setVisibility(View.GONE);
989            }
990            if (info.displayIcon == null) {
991                new LoadIconTask().execute(info);
992            }
993            holder.icon.setImageDrawable(info.displayIcon);
994        }
995    }
996
997    static class ViewHolder {
998        public TextView text;
999        public TextView text2;
1000        public ImageView icon;
1001
1002        public ViewHolder(View view) {
1003            text = (TextView) view.findViewById(com.android.internal.R.id.text1);
1004            text2 = (TextView) view.findViewById(com.android.internal.R.id.text2);
1005            icon = (ImageView) view.findViewById(R.id.icon);
1006        }
1007    }
1008
1009    class ItemLongClickListener implements AdapterView.OnItemLongClickListener {
1010
1011        @Override
1012        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
1013            position -= mListView.getHeaderViewsCount();
1014            if (position < 0) {
1015                // Header views don't count.
1016                return false;
1017            }
1018            ResolveInfo ri = mAdapter.resolveInfoForPosition(position, true);
1019            showAppDetails(ri);
1020            return true;
1021        }
1022
1023    }
1024
1025    class LoadIconTask extends AsyncTask<DisplayResolveInfo, Void, DisplayResolveInfo> {
1026        @Override
1027        protected DisplayResolveInfo doInBackground(DisplayResolveInfo... params) {
1028            final DisplayResolveInfo info = params[0];
1029            if (info.displayIcon == null) {
1030                info.displayIcon = loadIconForResolveInfo(info.ri);
1031            }
1032            return info;
1033        }
1034
1035        @Override
1036        protected void onPostExecute(DisplayResolveInfo info) {
1037            mAdapter.notifyDataSetChanged();
1038        }
1039    }
1040
1041    class LoadIconIntoViewTask extends AsyncTask<DisplayResolveInfo, Void, DisplayResolveInfo> {
1042        final ImageView mTargetView;
1043
1044        public LoadIconIntoViewTask(ImageView target) {
1045            mTargetView = target;
1046        }
1047
1048        @Override
1049        protected DisplayResolveInfo doInBackground(DisplayResolveInfo... params) {
1050            final DisplayResolveInfo info = params[0];
1051            if (info.displayIcon == null) {
1052                info.displayIcon = loadIconForResolveInfo(info.ri);
1053            }
1054            return info;
1055        }
1056
1057        @Override
1058        protected void onPostExecute(DisplayResolveInfo info) {
1059            mTargetView.setImageDrawable(info.displayIcon);
1060        }
1061    }
1062
1063    class ResolverComparator implements Comparator<ResolveInfo> {
1064        private final Collator mCollator;
1065
1066        public ResolverComparator(Context context) {
1067            mCollator = Collator.getInstance(context.getResources().getConfiguration().locale);
1068        }
1069
1070        @Override
1071        public int compare(ResolveInfo lhs, ResolveInfo rhs) {
1072            // We want to put the one targeted to another user at the end of the dialog.
1073            if (lhs.targetUserId != UserHandle.USER_CURRENT) {
1074                return 1;
1075            }
1076
1077            if (mStats != null) {
1078                final long timeDiff =
1079                        getPackageTimeSpent(rhs.activityInfo.packageName) -
1080                        getPackageTimeSpent(lhs.activityInfo.packageName);
1081
1082                if (timeDiff != 0) {
1083                    return timeDiff > 0 ? 1 : -1;
1084                }
1085            }
1086
1087            CharSequence  sa = lhs.loadLabel(mPm);
1088            if (sa == null) sa = lhs.activityInfo.name;
1089            CharSequence  sb = rhs.loadLabel(mPm);
1090            if (sb == null) sb = rhs.activityInfo.name;
1091
1092            return mCollator.compare(sa.toString(), sb.toString());
1093        }
1094
1095        private long getPackageTimeSpent(String packageName) {
1096            if (mStats != null) {
1097                final UsageStats stats = mStats.get(packageName);
1098                if (stats != null) {
1099                    return stats.getTotalTimeInForeground();
1100                }
1101
1102            }
1103            return 0;
1104        }
1105    }
1106}
1107
1108