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