ResolverActivity.java revision 5dd072d88459ef434ab756e1adcdcd1ce5eb1beb
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.setOnDismissedListener(new ResolverDrawerLayout.OnDismissedListener() {
282                @Override
283                public void onDismissed() {
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            onActivityStarted(intent);
648            return;
649        }
650        try {
651            startActivityAsCaller(intent, null, UserHandle.USER_NULL);
652            onActivityStarted(intent);
653        } catch (RuntimeException e) {
654            String launchedFromPackage;
655            try {
656                launchedFromPackage = ActivityManagerNative.getDefault().getLaunchedFromPackage(
657                        getActivityToken());
658            } catch (RemoteException e2) {
659                launchedFromPackage = "??";
660            }
661            Slog.wtf(TAG, "Unable to launch as uid " + mLaunchedFromUid
662                    + " package " + launchedFromPackage + ", while running in "
663                    + ActivityThread.currentProcessName(), e);
664        }
665    }
666
667    public void onActivityStarted(Intent intent) {
668        // Do nothing
669    }
670
671    void showAppDetails(ResolveInfo ri) {
672        Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
673                .setData(Uri.fromParts("package", ri.activityInfo.packageName, null))
674                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
675        startActivity(in);
676    }
677
678    private final class DisplayResolveInfo {
679        ResolveInfo ri;
680        CharSequence displayLabel;
681        Drawable displayIcon;
682        CharSequence extendedInfo;
683        Intent origIntent;
684
685        DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel,
686                CharSequence pInfo, Intent pOrigIntent) {
687            ri = pri;
688            displayLabel = pLabel;
689            extendedInfo = pInfo;
690            origIntent = pOrigIntent;
691        }
692    }
693
694    private final class ResolveListAdapter extends BaseAdapter {
695        private final Intent[] mInitialIntents;
696        private final List<ResolveInfo> mBaseResolveList;
697        private ResolveInfo mLastChosen;
698        private final Intent mIntent;
699        private final int mLaunchedFromUid;
700        private final LayoutInflater mInflater;
701
702        List<DisplayResolveInfo> mList;
703        List<ResolveInfo> mOrigResolveList;
704
705        private int mLastChosenPosition = -1;
706        private boolean mFilterLastUsed;
707
708        public ResolveListAdapter(Context context, Intent intent,
709                Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
710                boolean filterLastUsed) {
711            mIntent = new Intent(intent);
712            mInitialIntents = initialIntents;
713            mBaseResolveList = rList;
714            mLaunchedFromUid = launchedFromUid;
715            mInflater = LayoutInflater.from(context);
716            mList = new ArrayList<DisplayResolveInfo>();
717            mFilterLastUsed = filterLastUsed;
718            rebuildList();
719        }
720
721        public void handlePackagesChanged() {
722            final int oldItemCount = getCount();
723            rebuildList();
724            notifyDataSetChanged();
725            final int newItemCount = getCount();
726            if (newItemCount == 0) {
727                // We no longer have any items...  just finish the activity.
728                finish();
729            }
730        }
731
732        public DisplayResolveInfo getFilteredItem() {
733            if (mFilterLastUsed && mLastChosenPosition >= 0) {
734                // Not using getItem since it offsets to dodge this position for the list
735                return mList.get(mLastChosenPosition);
736            }
737            return null;
738        }
739
740        public int getFilteredPosition() {
741            if (mFilterLastUsed && mLastChosenPosition >= 0) {
742                return mLastChosenPosition;
743            }
744            return AbsListView.INVALID_POSITION;
745        }
746
747        public boolean hasFilteredItem() {
748            return mFilterLastUsed && mLastChosenPosition >= 0;
749        }
750
751        private void rebuildList() {
752            List<ResolveInfo> currentResolveList;
753
754            try {
755                mLastChosen = AppGlobals.getPackageManager().getLastChosenActivity(
756                        mIntent, mIntent.resolveTypeIfNeeded(getContentResolver()),
757                        PackageManager.MATCH_DEFAULT_ONLY);
758            } catch (RemoteException re) {
759                Log.d(TAG, "Error calling setLastChosenActivity\n" + re);
760            }
761
762            mList.clear();
763            if (mBaseResolveList != null) {
764                currentResolveList = mOrigResolveList = mBaseResolveList;
765            } else {
766                currentResolveList = mOrigResolveList = mPm.queryIntentActivities(
767                        mIntent, PackageManager.MATCH_DEFAULT_ONLY
768                        | (mFilterLastUsed ? PackageManager.GET_RESOLVED_FILTER : 0));
769                // Filter out any activities that the launched uid does not
770                // have permission for.  We don't do this when we have an explicit
771                // list of resolved activities, because that only happens when
772                // we are being subclassed, so we can safely launch whatever
773                // they gave us.
774                if (currentResolveList != null) {
775                    for (int i=currentResolveList.size()-1; i >= 0; i--) {
776                        ActivityInfo ai = currentResolveList.get(i).activityInfo;
777                        int granted = ActivityManager.checkComponentPermission(
778                                ai.permission, mLaunchedFromUid,
779                                ai.applicationInfo.uid, ai.exported);
780                        if (granted != PackageManager.PERMISSION_GRANTED) {
781                            // Access not allowed!
782                            if (mOrigResolveList == currentResolveList) {
783                                mOrigResolveList = new ArrayList<ResolveInfo>(mOrigResolveList);
784                            }
785                            currentResolveList.remove(i);
786                        }
787                    }
788                }
789            }
790            int N;
791            if ((currentResolveList != null) && ((N = currentResolveList.size()) > 0)) {
792                // Only display the first matches that are either of equal
793                // priority or have asked to be default options.
794                ResolveInfo r0 = currentResolveList.get(0);
795                for (int i=1; i<N; i++) {
796                    ResolveInfo ri = currentResolveList.get(i);
797                    if (DEBUG) Log.v(
798                        TAG,
799                        r0.activityInfo.name + "=" +
800                        r0.priority + "/" + r0.isDefault + " vs " +
801                        ri.activityInfo.name + "=" +
802                        ri.priority + "/" + ri.isDefault);
803                    if (r0.priority != ri.priority ||
804                        r0.isDefault != ri.isDefault) {
805                        while (i < N) {
806                            if (mOrigResolveList == currentResolveList) {
807                                mOrigResolveList = new ArrayList<ResolveInfo>(mOrigResolveList);
808                            }
809                            currentResolveList.remove(i);
810                            N--;
811                        }
812                    }
813                }
814                if (N > 1) {
815                    Comparator<ResolveInfo> rComparator =
816                            new ResolverComparator(ResolverActivity.this);
817                    Collections.sort(currentResolveList, rComparator);
818                }
819                // First put the initial items at the top.
820                if (mInitialIntents != null) {
821                    for (int i=0; i<mInitialIntents.length; i++) {
822                        Intent ii = mInitialIntents[i];
823                        if (ii == null) {
824                            continue;
825                        }
826                        ActivityInfo ai = ii.resolveActivityInfo(
827                                getPackageManager(), 0);
828                        if (ai == null) {
829                            Log.w(TAG, "No activity found for " + ii);
830                            continue;
831                        }
832                        ResolveInfo ri = new ResolveInfo();
833                        ri.activityInfo = ai;
834                        UserManager userManager =
835                                (UserManager) getSystemService(Context.USER_SERVICE);
836                        if (userManager.isManagedProfile()) {
837                            ri.noResourceId = true;
838                        }
839                        if (ii instanceof LabeledIntent) {
840                            LabeledIntent li = (LabeledIntent)ii;
841                            ri.resolvePackageName = li.getSourcePackage();
842                            ri.labelRes = li.getLabelResource();
843                            ri.nonLocalizedLabel = li.getNonLocalizedLabel();
844                            ri.icon = li.getIconResource();
845                        }
846                        mList.add(new DisplayResolveInfo(ri,
847                                ri.loadLabel(getPackageManager()), null, ii));
848                    }
849                }
850
851                // Check for applications with same name and use application name or
852                // package name if necessary
853                r0 = currentResolveList.get(0);
854                int start = 0;
855                CharSequence r0Label =  r0.loadLabel(mPm);
856                mShowExtended = false;
857                for (int i = 1; i < N; i++) {
858                    if (r0Label == null) {
859                        r0Label = r0.activityInfo.packageName;
860                    }
861                    ResolveInfo ri = currentResolveList.get(i);
862                    CharSequence riLabel = ri.loadLabel(mPm);
863                    if (riLabel == null) {
864                        riLabel = ri.activityInfo.packageName;
865                    }
866                    if (riLabel.equals(r0Label)) {
867                        continue;
868                    }
869                    processGroup(currentResolveList, start, (i-1), r0, r0Label);
870                    r0 = ri;
871                    r0Label = riLabel;
872                    start = i;
873                }
874                // Process last group
875                processGroup(currentResolveList, start, (N-1), r0, r0Label);
876            }
877        }
878
879        private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro,
880                CharSequence roLabel) {
881            // Process labels from start to i
882            int num = end - start+1;
883            if (num == 1) {
884                if (mLastChosen != null
885                        && mLastChosen.activityInfo.packageName.equals(
886                                ro.activityInfo.packageName)
887                        && mLastChosen.activityInfo.name.equals(ro.activityInfo.name)) {
888                    mLastChosenPosition = mList.size();
889                }
890                // No duplicate labels. Use label for entry at start
891                mList.add(new DisplayResolveInfo(ro, roLabel, null, null));
892            } else {
893                mShowExtended = true;
894                boolean usePkg = false;
895                CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm);
896                if (startApp == null) {
897                    usePkg = true;
898                }
899                if (!usePkg) {
900                    // Use HashSet to track duplicates
901                    HashSet<CharSequence> duplicates =
902                        new HashSet<CharSequence>();
903                    duplicates.add(startApp);
904                    for (int j = start+1; j <= end ; j++) {
905                        ResolveInfo jRi = rList.get(j);
906                        CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm);
907                        if ( (jApp == null) || (duplicates.contains(jApp))) {
908                            usePkg = true;
909                            break;
910                        } else {
911                            duplicates.add(jApp);
912                        }
913                    }
914                    // Clear HashSet for later use
915                    duplicates.clear();
916                }
917                for (int k = start; k <= end; k++) {
918                    ResolveInfo add = rList.get(k);
919                    if (mLastChosen != null
920                            && mLastChosen.activityInfo.packageName.equals(
921                                    add.activityInfo.packageName)
922                            && mLastChosen.activityInfo.name.equals(add.activityInfo.name)) {
923                        mLastChosenPosition = mList.size();
924                    }
925                    if (usePkg) {
926                        // Use application name for all entries from start to end-1
927                        mList.add(new DisplayResolveInfo(add, roLabel,
928                                add.activityInfo.packageName, null));
929                    } else {
930                        // Use package name for all entries from start to end-1
931                        mList.add(new DisplayResolveInfo(add, roLabel,
932                                add.activityInfo.applicationInfo.loadLabel(mPm), null));
933                    }
934                }
935            }
936        }
937
938        public ResolveInfo resolveInfoForPosition(int position, boolean filtered) {
939            return (filtered ? getItem(position) : mList.get(position)).ri;
940        }
941
942        public Intent intentForPosition(int position, boolean filtered) {
943            DisplayResolveInfo dri = filtered ? getItem(position) : mList.get(position);
944
945            Intent intent = new Intent(dri.origIntent != null ? dri.origIntent :
946                    getReplacementIntent(dri.ri.activityInfo.packageName, mIntent));
947            intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
948                    |Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
949            ActivityInfo ai = dri.ri.activityInfo;
950            intent.setComponent(new ComponentName(
951                    ai.applicationInfo.packageName, ai.name));
952            return intent;
953        }
954
955        public int getCount() {
956            int result = mList.size();
957            if (mFilterLastUsed && mLastChosenPosition >= 0) {
958                result--;
959            }
960            return result;
961        }
962
963        public DisplayResolveInfo getItem(int position) {
964            if (mFilterLastUsed && mLastChosenPosition >= 0 && position >= mLastChosenPosition) {
965                position++;
966            }
967            return mList.get(position);
968        }
969
970        public long getItemId(int position) {
971            return position;
972        }
973
974        public View getView(int position, View convertView, ViewGroup parent) {
975            View view = convertView;
976            if (view == null) {
977                view = mInflater.inflate(
978                        com.android.internal.R.layout.resolve_list_item, parent, false);
979
980                final ViewHolder holder = new ViewHolder(view);
981                view.setTag(holder);
982            }
983            bindView(view, getItem(position));
984            return view;
985        }
986
987        private final void bindView(View view, DisplayResolveInfo info) {
988            final ViewHolder holder = (ViewHolder) view.getTag();
989            holder.text.setText(info.displayLabel);
990            if (mShowExtended) {
991                holder.text2.setVisibility(View.VISIBLE);
992                holder.text2.setText(info.extendedInfo);
993            } else {
994                holder.text2.setVisibility(View.GONE);
995            }
996            if (info.displayIcon == null) {
997                new LoadIconTask().execute(info);
998            }
999            holder.icon.setImageDrawable(info.displayIcon);
1000        }
1001    }
1002
1003    static class ViewHolder {
1004        public TextView text;
1005        public TextView text2;
1006        public ImageView icon;
1007
1008        public ViewHolder(View view) {
1009            text = (TextView) view.findViewById(com.android.internal.R.id.text1);
1010            text2 = (TextView) view.findViewById(com.android.internal.R.id.text2);
1011            icon = (ImageView) view.findViewById(R.id.icon);
1012        }
1013    }
1014
1015    class ItemLongClickListener implements AdapterView.OnItemLongClickListener {
1016
1017        @Override
1018        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
1019            position -= mListView.getHeaderViewsCount();
1020            if (position < 0) {
1021                // Header views don't count.
1022                return false;
1023            }
1024            ResolveInfo ri = mAdapter.resolveInfoForPosition(position, true);
1025            showAppDetails(ri);
1026            return true;
1027        }
1028
1029    }
1030
1031    class LoadIconTask extends AsyncTask<DisplayResolveInfo, Void, DisplayResolveInfo> {
1032        @Override
1033        protected DisplayResolveInfo doInBackground(DisplayResolveInfo... params) {
1034            final DisplayResolveInfo info = params[0];
1035            if (info.displayIcon == null) {
1036                info.displayIcon = loadIconForResolveInfo(info.ri);
1037            }
1038            return info;
1039        }
1040
1041        @Override
1042        protected void onPostExecute(DisplayResolveInfo info) {
1043            mAdapter.notifyDataSetChanged();
1044        }
1045    }
1046
1047    class LoadIconIntoViewTask extends AsyncTask<DisplayResolveInfo, Void, DisplayResolveInfo> {
1048        final ImageView mTargetView;
1049
1050        public LoadIconIntoViewTask(ImageView target) {
1051            mTargetView = target;
1052        }
1053
1054        @Override
1055        protected DisplayResolveInfo doInBackground(DisplayResolveInfo... params) {
1056            final DisplayResolveInfo info = params[0];
1057            if (info.displayIcon == null) {
1058                info.displayIcon = loadIconForResolveInfo(info.ri);
1059            }
1060            return info;
1061        }
1062
1063        @Override
1064        protected void onPostExecute(DisplayResolveInfo info) {
1065            mTargetView.setImageDrawable(info.displayIcon);
1066        }
1067    }
1068
1069    class ResolverComparator implements Comparator<ResolveInfo> {
1070        private final Collator mCollator;
1071
1072        public ResolverComparator(Context context) {
1073            mCollator = Collator.getInstance(context.getResources().getConfiguration().locale);
1074        }
1075
1076        @Override
1077        public int compare(ResolveInfo lhs, ResolveInfo rhs) {
1078            // We want to put the one targeted to another user at the end of the dialog.
1079            if (lhs.targetUserId != UserHandle.USER_CURRENT) {
1080                return 1;
1081            }
1082
1083            if (mStats != null) {
1084                final long timeDiff =
1085                        getPackageTimeSpent(rhs.activityInfo.packageName) -
1086                        getPackageTimeSpent(lhs.activityInfo.packageName);
1087
1088                if (timeDiff != 0) {
1089                    return timeDiff > 0 ? 1 : -1;
1090                }
1091            }
1092
1093            CharSequence  sa = lhs.loadLabel(mPm);
1094            if (sa == null) sa = lhs.activityInfo.name;
1095            CharSequence  sb = rhs.loadLabel(mPm);
1096            if (sb == null) sb = rhs.activityInfo.name;
1097
1098            return mCollator.compare(sa.toString(), sb.toString());
1099        }
1100
1101        private long getPackageTimeSpent(String packageName) {
1102            if (mStats != null) {
1103                final UsageStats stats = mStats.get(packageName);
1104                if (stats != null) {
1105                    return stats.getTotalTimeInForeground();
1106                }
1107
1108            }
1109            return 0;
1110        }
1111    }
1112}
1113
1114