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