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