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