ResolverActivity.java revision 905577f6345c014fc2489a8068ea967ba8c18012
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 com.android.internal.R;
20import android.content.ComponentName;
21import android.content.Context;
22import android.content.DialogInterface;
23import android.content.Intent;
24import android.content.IntentFilter;
25import android.content.pm.ActivityInfo;
26import android.content.pm.LabeledIntent;
27import android.content.pm.PackageManager;
28import android.content.pm.ResolveInfo;
29import android.graphics.drawable.Drawable;
30import android.net.Uri;
31import android.os.Bundle;
32import android.os.PatternMatcher;
33import android.util.Log;
34import android.view.View;
35import android.view.ViewGroup;
36import android.view.LayoutInflater;
37import android.widget.BaseAdapter;
38import android.widget.CheckBox;
39import android.widget.CompoundButton;
40import android.widget.ImageView;
41import android.widget.TextView;
42import java.util.ArrayList;
43import java.util.Collections;
44import java.util.HashSet;
45import java.util.Iterator;
46import java.util.List;
47import java.util.Set;
48
49/**
50 * This activity is displayed when the system attempts to start an Intent for
51 * which there is more than one matching activity, allowing the user to decide
52 * which to go to.  It is not normally used directly by application developers.
53 */
54public class ResolverActivity extends AlertActivity implements
55        DialogInterface.OnClickListener, CheckBox.OnCheckedChangeListener {
56    private ResolveListAdapter mAdapter;
57    private CheckBox mAlwaysCheck;
58    private TextView mClearDefaultHint;
59    private PackageManager mPm;
60
61    private Intent makeMyIntent() {
62        Intent intent = new Intent(getIntent());
63        // The resolver activity is set to be hidden from recent tasks.
64        // we don't want this attribute to be propagated to the next activity
65        // being launched.  Note that if the original Intent also had this
66        // flag set, we are now losing it.  That should be a very rare case
67        // and we can live with this.
68        intent.setFlags(intent.getFlags()&~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
69        return intent;
70    }
71
72    @Override
73    protected void onCreate(Bundle savedInstanceState) {
74        onCreate(savedInstanceState, makeMyIntent(),
75                getResources().getText(com.android.internal.R.string.whichApplication),
76                null, null, true);
77    }
78
79    protected void onCreate(Bundle savedInstanceState, Intent intent,
80            CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList,
81            boolean alwaysUseOption) {
82        super.onCreate(savedInstanceState);
83        mPm = getPackageManager();
84        intent.setComponent(null);
85
86        AlertController.AlertParams ap = mAlertParams;
87
88        ap.mTitle = title;
89        ap.mOnClickListener = this;
90
91        if (alwaysUseOption) {
92            LayoutInflater inflater = (LayoutInflater) getSystemService(
93                    Context.LAYOUT_INFLATER_SERVICE);
94            ap.mView = inflater.inflate(R.layout.always_use_checkbox, null);
95            mAlwaysCheck = (CheckBox)ap.mView.findViewById(com.android.internal.R.id.alwaysUse);
96            mAlwaysCheck.setText(R.string.alwaysUse);
97            mAlwaysCheck.setOnCheckedChangeListener(this);
98            mClearDefaultHint = (TextView)ap.mView.findViewById(
99                                                        com.android.internal.R.id.clearDefaultHint);
100            mClearDefaultHint.setVisibility(View.GONE);
101        }
102        mAdapter = new ResolveListAdapter(this, intent, initialIntents, rList);
103        int count = mAdapter.getCount();
104        if (count > 1) {
105            ap.mAdapter = mAdapter;
106        } else if (count == 1) {
107            startActivity(mAdapter.intentForPosition(0));
108            finish();
109            return;
110        } else {
111            ap.mMessage = getResources().getText(com.android.internal.R.string.noApplications);
112        }
113
114        setupAlert();
115    }
116
117    public void onClick(DialogInterface dialog, int which) {
118        ResolveInfo ri = mAdapter.resolveInfoForPosition(which);
119        Intent intent = mAdapter.intentForPosition(which);
120        boolean alwaysCheck = (mAlwaysCheck != null && mAlwaysCheck.isChecked());
121        onIntentSelected(ri, intent, alwaysCheck);
122        finish();
123    }
124
125    protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {
126        if (alwaysCheck) {
127            // Build a reasonable intent filter, based on what matched.
128            IntentFilter filter = new IntentFilter();
129
130            if (intent.getAction() != null) {
131                filter.addAction(intent.getAction());
132            }
133            Set<String> categories = intent.getCategories();
134            if (categories != null) {
135                for (String cat : categories) {
136                    filter.addCategory(cat);
137                }
138            }
139            filter.addCategory(Intent.CATEGORY_DEFAULT);
140
141            int cat = ri.match&IntentFilter.MATCH_CATEGORY_MASK;
142            Uri data = intent.getData();
143            if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
144                String mimeType = intent.resolveType(this);
145                if (mimeType != null) {
146                    try {
147                        filter.addDataType(mimeType);
148                    } catch (IntentFilter.MalformedMimeTypeException e) {
149                        Log.w("ResolverActivity", e);
150                        filter = null;
151                    }
152                }
153            }
154            if (data != null && data.getScheme() != null) {
155                // We need the data specification if there was no type,
156                // OR if the scheme is not one of our magical "file:"
157                // or "content:" schemes (see IntentFilter for the reason).
158                if (cat != IntentFilter.MATCH_CATEGORY_TYPE
159                        || (!"file".equals(data.getScheme())
160                                && !"content".equals(data.getScheme()))) {
161                    filter.addDataScheme(data.getScheme());
162
163                    // Look through the resolved filter to determine which part
164                    // of it matched the original Intent.
165                    Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
166                    if (aIt != null) {
167                        while (aIt.hasNext()) {
168                            IntentFilter.AuthorityEntry a = aIt.next();
169                            if (a.match(data) >= 0) {
170                                int port = a.getPort();
171                                filter.addDataAuthority(a.getHost(),
172                                        port >= 0 ? Integer.toString(port) : null);
173                                break;
174                            }
175                        }
176                    }
177                    Iterator<PatternMatcher> pIt = ri.filter.pathsIterator();
178                    if (pIt != null) {
179                        String path = data.getPath();
180                        while (path != null && pIt.hasNext()) {
181                            PatternMatcher p = pIt.next();
182                            if (p.match(path)) {
183                                filter.addDataPath(p.getPath(), p.getType());
184                                break;
185                            }
186                        }
187                    }
188                }
189            }
190
191            if (filter != null) {
192                final int N = mAdapter.mList.size();
193                ComponentName[] set = new ComponentName[N];
194                int bestMatch = 0;
195                for (int i=0; i<N; i++) {
196                    ResolveInfo r = mAdapter.mList.get(i).ri;
197                    set[i] = new ComponentName(r.activityInfo.packageName,
198                            r.activityInfo.name);
199                    if (r.match > bestMatch) bestMatch = r.match;
200                }
201                getPackageManager().addPreferredActivity(filter, bestMatch, set,
202                        intent.getComponent());
203            }
204        }
205
206        if (intent != null) {
207            startActivity(intent);
208        }
209    }
210
211    private final class DisplayResolveInfo {
212        ResolveInfo ri;
213        CharSequence displayLabel;
214        Drawable displayIcon;
215        CharSequence extendedInfo;
216        Intent origIntent;
217
218        DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel,
219                CharSequence pInfo, Intent pOrigIntent) {
220            ri = pri;
221            displayLabel = pLabel;
222            extendedInfo = pInfo;
223            origIntent = pOrigIntent;
224        }
225    }
226
227    private final class ResolveListAdapter extends BaseAdapter {
228        private final Intent mIntent;
229        private final LayoutInflater mInflater;
230
231        private List<DisplayResolveInfo> mList;
232
233        public ResolveListAdapter(Context context, Intent intent,
234                Intent[] initialIntents, List<ResolveInfo> rList) {
235            mIntent = new Intent(intent);
236            mIntent.setComponent(null);
237            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
238
239            if (rList == null) {
240                rList = mPm.queryIntentActivities(
241                        intent, PackageManager.MATCH_DEFAULT_ONLY
242                        | (mAlwaysCheck != null ? PackageManager.GET_RESOLVED_FILTER : 0));
243            }
244            int N;
245            if ((rList != null) && ((N = rList.size()) > 0)) {
246                // Only display the first matches that are either of equal
247                // priority or have asked to be default options.
248                ResolveInfo r0 = rList.get(0);
249                for (int i=1; i<N; i++) {
250                    ResolveInfo ri = rList.get(i);
251                    if (false) Log.v(
252                        "ResolveListActivity",
253                        r0.activityInfo.name + "=" +
254                        r0.priority + "/" + r0.isDefault + " vs " +
255                        ri.activityInfo.name + "=" +
256                        ri.priority + "/" + ri.isDefault);
257                   if (r0.priority != ri.priority ||
258                        r0.isDefault != ri.isDefault) {
259                        while (i < N) {
260                            rList.remove(i);
261                            N--;
262                        }
263                    }
264                }
265                if (N > 1) {
266                    ResolveInfo.DisplayNameComparator rComparator =
267                            new ResolveInfo.DisplayNameComparator(mPm);
268                    Collections.sort(rList, rComparator);
269                }
270
271                mList = new ArrayList<DisplayResolveInfo>();
272
273                // First put the initial items at the top.
274                if (initialIntents != null) {
275                    for (int i=0; i<initialIntents.length; i++) {
276                        Intent ii = initialIntents[i];
277                        if (ii == null) {
278                            continue;
279                        }
280                        ActivityInfo ai = ii.resolveActivityInfo(
281                                getPackageManager(), 0);
282                        if (ai == null) {
283                            Log.w("ResolverActivity", "No activity found for "
284                                    + ii);
285                            continue;
286                        }
287                        ResolveInfo ri = new ResolveInfo();
288                        ri.activityInfo = ai;
289                        if (ii instanceof LabeledIntent) {
290                            LabeledIntent li = (LabeledIntent)ii;
291                            ri.resolvePackageName = li.getSourcePackage();
292                            ri.labelRes = li.getLabelResource();
293                            ri.nonLocalizedLabel = li.getNonLocalizedLabel();
294                            ri.icon = li.getIconResource();
295                        }
296                        mList.add(new DisplayResolveInfo(ri,
297                                ri.loadLabel(getPackageManager()), null, ii));
298                    }
299                }
300
301                // Check for applications with same name and use application name or
302                // package name if necessary
303                r0 = rList.get(0);
304                int start = 0;
305                CharSequence r0Label =  r0.loadLabel(mPm);
306                for (int i = 1; i < N; i++) {
307                    if (r0Label == null) {
308                        r0Label = r0.activityInfo.packageName;
309                    }
310                    ResolveInfo ri = rList.get(i);
311                    CharSequence riLabel = ri.loadLabel(mPm);
312                    if (riLabel == null) {
313                        riLabel = ri.activityInfo.packageName;
314                    }
315                    if (riLabel.equals(r0Label)) {
316                        continue;
317                    }
318                    processGroup(rList, start, (i-1), r0, r0Label);
319                    r0 = ri;
320                    r0Label = riLabel;
321                    start = i;
322                }
323                // Process last group
324                processGroup(rList, start, (N-1), r0, r0Label);
325            }
326        }
327
328        private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro,
329                CharSequence roLabel) {
330            // Process labels from start to i
331            int num = end - start+1;
332            if (num == 1) {
333                // No duplicate labels. Use label for entry at start
334                mList.add(new DisplayResolveInfo(ro, roLabel, null, null));
335            } else {
336                boolean usePkg = false;
337                CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm);
338                if (startApp == null) {
339                    usePkg = true;
340                }
341                if (!usePkg) {
342                    // Use HashSet to track duplicates
343                    HashSet<CharSequence> duplicates =
344                        new HashSet<CharSequence>();
345                    duplicates.add(startApp);
346                    for (int j = start+1; j <= end ; j++) {
347                        ResolveInfo jRi = rList.get(j);
348                        CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm);
349                        if ( (jApp == null) || (duplicates.contains(jApp))) {
350                            usePkg = true;
351                            break;
352                        } else {
353                            duplicates.add(jApp);
354                        }
355                    }
356                    // Clear HashSet for later use
357                    duplicates.clear();
358                }
359                for (int k = start; k <= end; k++) {
360                    ResolveInfo add = rList.get(k);
361                    if (usePkg) {
362                        // Use application name for all entries from start to end-1
363                        mList.add(new DisplayResolveInfo(add, roLabel,
364                                add.activityInfo.packageName, null));
365                    } else {
366                        // Use package name for all entries from start to end-1
367                        mList.add(new DisplayResolveInfo(add, roLabel,
368                                add.activityInfo.applicationInfo.loadLabel(mPm), null));
369                    }
370                }
371            }
372        }
373
374        public ResolveInfo resolveInfoForPosition(int position) {
375            if (mList == null) {
376                return null;
377            }
378
379            return mList.get(position).ri;
380        }
381
382        public Intent intentForPosition(int position) {
383            if (mList == null) {
384                return null;
385            }
386
387            DisplayResolveInfo dri = mList.get(position);
388
389            Intent intent = new Intent(dri.origIntent != null
390                    ? dri.origIntent : mIntent);
391            intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
392                    |Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
393            ActivityInfo ai = dri.ri.activityInfo;
394            intent.setComponent(new ComponentName(
395                    ai.applicationInfo.packageName, ai.name));
396            return intent;
397        }
398
399        public int getCount() {
400            return mList != null ? mList.size() : 0;
401        }
402
403        public Object getItem(int position) {
404            return position;
405        }
406
407        public long getItemId(int position) {
408            return position;
409        }
410
411        public View getView(int position, View convertView, ViewGroup parent) {
412            View view;
413            if (convertView == null) {
414                view = mInflater.inflate(
415                        com.android.internal.R.layout.resolve_list_item, parent, false);
416            } else {
417                view = convertView;
418            }
419            bindView(view, mList.get(position));
420            return view;
421        }
422
423        private final void bindView(View view, DisplayResolveInfo info) {
424            TextView text = (TextView)view.findViewById(com.android.internal.R.id.text1);
425            TextView text2 = (TextView)view.findViewById(com.android.internal.R.id.text2);
426            ImageView icon = (ImageView)view.findViewById(R.id.icon);
427            text.setText(info.displayLabel);
428            if (info.extendedInfo != null) {
429                text2.setVisibility(View.VISIBLE);
430                text2.setText(info.extendedInfo);
431            } else {
432                text2.setVisibility(View.GONE);
433            }
434            if (info.displayIcon == null) {
435                info.displayIcon = info.ri.loadIcon(mPm);
436            }
437            icon.setImageDrawable(info.displayIcon);
438        }
439    }
440
441    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
442        if (mClearDefaultHint == null) return;
443
444        if(isChecked) {
445            mClearDefaultHint.setVisibility(View.VISIBLE);
446        } else {
447            mClearDefaultHint.setVisibility(View.GONE);
448        }
449    }
450}
451
452