• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006 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 
17 package android.content;
18 
19 import android.net.Uri;
20 import android.os.Parcel;
21 import android.os.Parcelable;
22 import android.os.PatternMatcher;
23 import android.util.AndroidException;
24 import android.util.Log;
25 import android.util.Printer;
26 
27 import com.android.internal.util.XmlUtils;
28 
29 import org.xmlpull.v1.XmlPullParser;
30 import org.xmlpull.v1.XmlPullParserException;
31 import org.xmlpull.v1.XmlSerializer;
32 
33 import java.io.IOException;
34 import java.util.ArrayList;
35 import java.util.Iterator;
36 import java.util.Set;
37 
38 /**
39  * Structured description of Intent values to be matched.  An IntentFilter can
40  * match against actions, categories, and data (either via its type, scheme,
41  * and/or path) in an Intent.  It also includes a "priority" value which is
42  * used to order multiple matching filters.
43  *
44  * <p>IntentFilter objects are often created in XML as part of a package's
45  * {@link android.R.styleable#AndroidManifest AndroidManifest.xml} file,
46  * using {@link android.R.styleable#AndroidManifestIntentFilter intent-filter}
47  * tags.
48  *
49  * <p>There are three Intent characteristics you can filter on: the
50  * <em>action</em>, <em>data</em>, and <em>categories</em>.  For each of these
51  * characteristics you can provide
52  * multiple possible matching values (via {@link #addAction},
53  * {@link #addDataType}, {@link #addDataScheme}, {@link #addDataSchemeSpecificPart},
54  * {@link #addDataAuthority}, {@link #addDataPath}, and {@link #addCategory}, respectively).
55  * For actions, the field
56  * will not be tested if no values have been given (treating it as a wildcard);
57  * if no data characteristics are specified, however, then the filter will
58  * only match intents that contain no data.
59  *
60  * <p>The data characteristic is
61  * itself divided into three attributes: type, scheme, authority, and path.
62  * Any that are
63  * specified must match the contents of the Intent.  If you specify a scheme
64  * but no type, only Intent that does not have a type (such as mailto:) will
65  * match; a content: URI will never match because they always have a MIME type
66  * that is supplied by their content provider.  Specifying a type with no scheme
67  * has somewhat special meaning: it will match either an Intent with no URI
68  * field, or an Intent with a content: or file: URI.  If you specify neither,
69  * then only an Intent with no data or type will match.  To specify an authority,
70  * you must also specify one or more schemes that it is associated with.
71  * To specify a path, you also must specify both one or more authorities and
72  * one or more schemes it is associated with.
73  *
74  * <div class="special reference">
75  * <h3>Developer Guides</h3>
76  * <p>For information about how to create and resolve intents, read the
77  * <a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>
78  * developer guide.</p>
79  * </div>
80  *
81  * <h3>Filter Rules</h3>
82  * <p>A match is based on the following rules.  Note that
83  * for an IntentFilter to match an Intent, three conditions must hold:
84  * the <strong>action</strong> and <strong>category</strong> must match, and
85  * the data (both the <strong>data type</strong> and
86  * <strong>data scheme+authority+path</strong> if specified) must match
87  * (see {@link #match(ContentResolver, Intent, boolean, String)} for more details
88  * on how the data fields match).
89  *
90  * <p><strong>Action</strong> matches if any of the given values match the
91  * Intent action; if the filter specifies no actions, then it will only match
92  * Intents that do not contain an action.
93  *
94  * <p><strong>Data Type</strong> matches if any of the given values match the
95  * Intent type.  The Intent
96  * type is determined by calling {@link Intent#resolveType}.  A wildcard can be
97  * used for the MIME sub-type, in both the Intent and IntentFilter, so that the
98  * type "audio/*" will match "audio/mpeg", "audio/aiff", "audio/*", etc.
99  * <em>Note that MIME type matching here is <b>case sensitive</b>, unlike
100  * formal RFC MIME types!</em>  You should thus always use lower case letters
101  * for your MIME types.
102  *
103  * <p><strong>Data Scheme</strong> matches if any of the given values match the
104  * Intent data's scheme.
105  * The Intent scheme is determined by calling {@link Intent#getData}
106  * and {@link android.net.Uri#getScheme} on that URI.
107  * <em>Note that scheme matching here is <b>case sensitive</b>, unlike
108  * formal RFC schemes!</em>  You should thus always use lower case letters
109  * for your schemes.
110  *
111  * <p><strong>Data Scheme Specific Part</strong> matches if any of the given values match
112  * the Intent's data scheme specific part <em>and</em> one of the data schemes in the filter
113  * has matched the Intent, <em>or</em> no scheme specific parts were supplied in the filter.
114  * The Intent scheme specific part is determined by calling
115  * {@link Intent#getData} and {@link android.net.Uri#getSchemeSpecificPart} on that URI.
116  * <em>Note that scheme specific part matching is <b>case sensitive</b>.</em>
117  *
118  * <p><strong>Data Authority</strong> matches if any of the given values match
119  * the Intent's data authority <em>and</em> one of the data schemes in the filter
120  * has matched the Intent, <em>or</em> no authories were supplied in the filter.
121  * The Intent authority is determined by calling
122  * {@link Intent#getData} and {@link android.net.Uri#getAuthority} on that URI.
123  * <em>Note that authority matching here is <b>case sensitive</b>, unlike
124  * formal RFC host names!</em>  You should thus always use lower case letters
125  * for your authority.
126  *
127  * <p><strong>Data Path</strong> matches if any of the given values match the
128  * Intent's data path <em>and</em> both a scheme and authority in the filter
129  * has matched against the Intent, <em>or</em> no paths were supplied in the
130  * filter.  The Intent authority is determined by calling
131  * {@link Intent#getData} and {@link android.net.Uri#getPath} on that URI.
132  *
133  * <p><strong>Categories</strong> match if <em>all</em> of the categories in
134  * the Intent match categories given in the filter.  Extra categories in the
135  * filter that are not in the Intent will not cause the match to fail.  Note
136  * that unlike the action, an IntentFilter with no categories
137  * will only match an Intent that does not have any categories.
138  */
139 public class IntentFilter implements Parcelable {
140     private static final String SGLOB_STR = "sglob";
141     private static final String PREFIX_STR = "prefix";
142     private static final String LITERAL_STR = "literal";
143     private static final String PATH_STR = "path";
144     private static final String PORT_STR = "port";
145     private static final String HOST_STR = "host";
146     private static final String AUTH_STR = "auth";
147     private static final String SSP_STR = "ssp";
148     private static final String SCHEME_STR = "scheme";
149     private static final String TYPE_STR = "type";
150     private static final String CAT_STR = "cat";
151     private static final String NAME_STR = "name";
152     private static final String ACTION_STR = "action";
153 
154     /**
155      * The filter {@link #setPriority} value at which system high-priority
156      * receivers are placed; that is, receivers that should execute before
157      * application code. Applications should never use filters with this or
158      * higher priorities.
159      *
160      * @see #setPriority
161      */
162     public static final int SYSTEM_HIGH_PRIORITY = 1000;
163 
164     /**
165      * The filter {@link #setPriority} value at which system low-priority
166      * receivers are placed; that is, receivers that should execute after
167      * application code. Applications should never use filters with this or
168      * lower priorities.
169      *
170      * @see #setPriority
171      */
172     public static final int SYSTEM_LOW_PRIORITY = -1000;
173 
174     /**
175      * The part of a match constant that describes the category of match
176      * that occurred.  May be either {@link #MATCH_CATEGORY_EMPTY},
177      * {@link #MATCH_CATEGORY_SCHEME}, {@link #MATCH_CATEGORY_SCHEME_SPECIFIC_PART},
178      * {@link #MATCH_CATEGORY_HOST}, {@link #MATCH_CATEGORY_PORT},
179      * {@link #MATCH_CATEGORY_PATH}, or {@link #MATCH_CATEGORY_TYPE}.  Higher
180      * values indicate a better match.
181      */
182     public static final int MATCH_CATEGORY_MASK = 0xfff0000;
183 
184     /**
185      * The part of a match constant that applies a quality adjustment to the
186      * basic category of match.  The value {@link #MATCH_ADJUSTMENT_NORMAL}
187      * is no adjustment; higher numbers than that improve the quality, while
188      * lower numbers reduce it.
189      */
190     public static final int MATCH_ADJUSTMENT_MASK = 0x000ffff;
191 
192     /**
193      * Quality adjustment applied to the category of match that signifies
194      * the default, base value; higher numbers improve the quality while
195      * lower numbers reduce it.
196      */
197     public static final int MATCH_ADJUSTMENT_NORMAL = 0x8000;
198 
199     /**
200      * The filter matched an intent that had no data specified.
201      */
202     public static final int MATCH_CATEGORY_EMPTY = 0x0100000;
203     /**
204      * The filter matched an intent with the same data URI scheme.
205      */
206     public static final int MATCH_CATEGORY_SCHEME = 0x0200000;
207     /**
208      * The filter matched an intent with the same data URI scheme and
209      * authority host.
210      */
211     public static final int MATCH_CATEGORY_HOST = 0x0300000;
212     /**
213      * The filter matched an intent with the same data URI scheme and
214      * authority host and port.
215      */
216     public static final int MATCH_CATEGORY_PORT = 0x0400000;
217     /**
218      * The filter matched an intent with the same data URI scheme,
219      * authority, and path.
220      */
221     public static final int MATCH_CATEGORY_PATH = 0x0500000;
222     /**
223      * The filter matched an intent with the same data URI scheme and
224      * scheme specific part.
225      */
226     public static final int MATCH_CATEGORY_SCHEME_SPECIFIC_PART = 0x0580000;
227     /**
228      * The filter matched an intent with the same data MIME type.
229      */
230     public static final int MATCH_CATEGORY_TYPE = 0x0600000;
231 
232     /**
233      * The filter didn't match due to different MIME types.
234      */
235     public static final int NO_MATCH_TYPE = -1;
236     /**
237      * The filter didn't match due to different data URIs.
238      */
239     public static final int NO_MATCH_DATA = -2;
240     /**
241      * The filter didn't match due to different actions.
242      */
243     public static final int NO_MATCH_ACTION = -3;
244     /**
245      * The filter didn't match because it required one or more categories
246      * that were not in the Intent.
247      */
248     public static final int NO_MATCH_CATEGORY = -4;
249 
250     private int mPriority;
251     private final ArrayList<String> mActions;
252     private ArrayList<String> mCategories = null;
253     private ArrayList<String> mDataSchemes = null;
254     private ArrayList<PatternMatcher> mDataSchemeSpecificParts = null;
255     private ArrayList<AuthorityEntry> mDataAuthorities = null;
256     private ArrayList<PatternMatcher> mDataPaths = null;
257     private ArrayList<String> mDataTypes = null;
258     private boolean mHasPartialTypes = false;
259 
260     // These functions are the start of more optimized code for managing
261     // the string sets...  not yet implemented.
262 
findStringInSet(String[] set, String string, int[] lengths, int lenPos)263     private static int findStringInSet(String[] set, String string,
264             int[] lengths, int lenPos) {
265         if (set == null) return -1;
266         final int N = lengths[lenPos];
267         for (int i=0; i<N; i++) {
268             if (set[i].equals(string)) return i;
269         }
270         return -1;
271     }
272 
addStringToSet(String[] set, String string, int[] lengths, int lenPos)273     private static String[] addStringToSet(String[] set, String string,
274             int[] lengths, int lenPos) {
275         if (findStringInSet(set, string, lengths, lenPos) >= 0) return set;
276         if (set == null) {
277             set = new String[2];
278             set[0] = string;
279             lengths[lenPos] = 1;
280             return set;
281         }
282         final int N = lengths[lenPos];
283         if (N < set.length) {
284             set[N] = string;
285             lengths[lenPos] = N+1;
286             return set;
287         }
288 
289         String[] newSet = new String[(N*3)/2 + 2];
290         System.arraycopy(set, 0, newSet, 0, N);
291         set = newSet;
292         set[N] = string;
293         lengths[lenPos] = N+1;
294         return set;
295     }
296 
removeStringFromSet(String[] set, String string, int[] lengths, int lenPos)297     private static String[] removeStringFromSet(String[] set, String string,
298             int[] lengths, int lenPos) {
299         int pos = findStringInSet(set, string, lengths, lenPos);
300         if (pos < 0) return set;
301         final int N = lengths[lenPos];
302         if (N > (set.length/4)) {
303             int copyLen = N-(pos+1);
304             if (copyLen > 0) {
305                 System.arraycopy(set, pos+1, set, pos, copyLen);
306             }
307             set[N-1] = null;
308             lengths[lenPos] = N-1;
309             return set;
310         }
311 
312         String[] newSet = new String[set.length/3];
313         if (pos > 0) System.arraycopy(set, 0, newSet, 0, pos);
314         if ((pos+1) < N) System.arraycopy(set, pos+1, newSet, pos, N-(pos+1));
315         return newSet;
316     }
317 
318     /**
319      * This exception is thrown when a given MIME type does not have a valid
320      * syntax.
321      */
322     public static class MalformedMimeTypeException extends AndroidException {
MalformedMimeTypeException()323         public MalformedMimeTypeException() {
324         }
325 
MalformedMimeTypeException(String name)326         public MalformedMimeTypeException(String name) {
327             super(name);
328         }
329     };
330 
331     /**
332      * Create a new IntentFilter instance with a specified action and MIME
333      * type, where you know the MIME type is correctly formatted.  This catches
334      * the {@link MalformedMimeTypeException} exception that the constructor
335      * can call and turns it into a runtime exception.
336      *
337      * @param action The action to match, i.e. Intent.ACTION_VIEW.
338      * @param dataType The type to match, i.e. "vnd.android.cursor.dir/person".
339      *
340      * @return A new IntentFilter for the given action and type.
341      *
342      * @see #IntentFilter(String, String)
343      */
create(String action, String dataType)344     public static IntentFilter create(String action, String dataType) {
345         try {
346             return new IntentFilter(action, dataType);
347         } catch (MalformedMimeTypeException e) {
348             throw new RuntimeException("Bad MIME type", e);
349         }
350     }
351 
352     /**
353      * New empty IntentFilter.
354      */
IntentFilter()355     public IntentFilter() {
356         mPriority = 0;
357         mActions = new ArrayList<String>();
358     }
359 
360     /**
361      * New IntentFilter that matches a single action with no data.  If
362      * no data characteristics are subsequently specified, then the
363      * filter will only match intents that contain no data.
364      *
365      * @param action The action to match, i.e. Intent.ACTION_MAIN.
366      */
IntentFilter(String action)367     public IntentFilter(String action) {
368         mPriority = 0;
369         mActions = new ArrayList<String>();
370         addAction(action);
371     }
372 
373     /**
374      * New IntentFilter that matches a single action and data type.
375      *
376      * <p><em>Note: MIME type matching in the Android framework is
377      * case-sensitive, unlike formal RFC MIME types.  As a result,
378      * you should always write your MIME types with lower case letters,
379      * and any MIME types you receive from outside of Android should be
380      * converted to lower case before supplying them here.</em></p>
381      *
382      * <p>Throws {@link MalformedMimeTypeException} if the given MIME type is
383      * not syntactically correct.
384      *
385      * @param action The action to match, i.e. Intent.ACTION_VIEW.
386      * @param dataType The type to match, i.e. "vnd.android.cursor.dir/person".
387      *
388      */
IntentFilter(String action, String dataType)389     public IntentFilter(String action, String dataType)
390         throws MalformedMimeTypeException {
391         mPriority = 0;
392         mActions = new ArrayList<String>();
393         addAction(action);
394         addDataType(dataType);
395     }
396 
397     /**
398      * New IntentFilter containing a copy of an existing filter.
399      *
400      * @param o The original filter to copy.
401      */
IntentFilter(IntentFilter o)402     public IntentFilter(IntentFilter o) {
403         mPriority = o.mPriority;
404         mActions = new ArrayList<String>(o.mActions);
405         if (o.mCategories != null) {
406             mCategories = new ArrayList<String>(o.mCategories);
407         }
408         if (o.mDataTypes != null) {
409             mDataTypes = new ArrayList<String>(o.mDataTypes);
410         }
411         if (o.mDataSchemes != null) {
412             mDataSchemes = new ArrayList<String>(o.mDataSchemes);
413         }
414         if (o.mDataSchemeSpecificParts != null) {
415             mDataSchemeSpecificParts = new ArrayList<PatternMatcher>(o.mDataSchemeSpecificParts);
416         }
417         if (o.mDataAuthorities != null) {
418             mDataAuthorities = new ArrayList<AuthorityEntry>(o.mDataAuthorities);
419         }
420         if (o.mDataPaths != null) {
421             mDataPaths = new ArrayList<PatternMatcher>(o.mDataPaths);
422         }
423         mHasPartialTypes = o.mHasPartialTypes;
424     }
425 
426     /**
427      * Modify priority of this filter.  The default priority is 0. Positive
428      * values will be before the default, lower values will be after it.
429      * Applications must use a value that is larger than
430      * {@link #SYSTEM_LOW_PRIORITY} and smaller than
431      * {@link #SYSTEM_HIGH_PRIORITY} .
432      *
433      * @param priority The new priority value.
434      *
435      * @see #getPriority
436      * @see #SYSTEM_LOW_PRIORITY
437      * @see #SYSTEM_HIGH_PRIORITY
438      */
setPriority(int priority)439     public final void setPriority(int priority) {
440         mPriority = priority;
441     }
442 
443     /**
444      * Return the priority of this filter.
445      *
446      * @return The priority of the filter.
447      *
448      * @see #setPriority
449      */
getPriority()450     public final int getPriority() {
451         return mPriority;
452     }
453 
454     /**
455      * Add a new Intent action to match against.  If any actions are included
456      * in the filter, then an Intent's action must be one of those values for
457      * it to match.  If no actions are included, the Intent action is ignored.
458      *
459      * @param action Name of the action to match, i.e. Intent.ACTION_VIEW.
460      */
addAction(String action)461     public final void addAction(String action) {
462         if (!mActions.contains(action)) {
463             mActions.add(action.intern());
464         }
465     }
466 
467     /**
468      * Return the number of actions in the filter.
469      */
countActions()470     public final int countActions() {
471         return mActions.size();
472     }
473 
474     /**
475      * Return an action in the filter.
476      */
getAction(int index)477     public final String getAction(int index) {
478         return mActions.get(index);
479     }
480 
481     /**
482      * Is the given action included in the filter?  Note that if the filter
483      * does not include any actions, false will <em>always</em> be returned.
484      *
485      * @param action The action to look for.
486      *
487      * @return True if the action is explicitly mentioned in the filter.
488      */
hasAction(String action)489     public final boolean hasAction(String action) {
490         return action != null && mActions.contains(action);
491     }
492 
493     /**
494      * Match this filter against an Intent's action.  If the filter does not
495      * specify any actions, the match will always fail.
496      *
497      * @param action The desired action to look for.
498      *
499      * @return True if the action is listed in the filter.
500      */
matchAction(String action)501     public final boolean matchAction(String action) {
502         return hasAction(action);
503     }
504 
505     /**
506      * Return an iterator over the filter's actions.  If there are no actions,
507      * returns null.
508      */
actionsIterator()509     public final Iterator<String> actionsIterator() {
510         return mActions != null ? mActions.iterator() : null;
511     }
512 
513     /**
514      * Add a new Intent data type to match against.  If any types are
515      * included in the filter, then an Intent's data must be <em>either</em>
516      * one of these types <em>or</em> a matching scheme.  If no data types
517      * are included, then an Intent will only match if it specifies no data.
518      *
519      * <p><em>Note: MIME type matching in the Android framework is
520      * case-sensitive, unlike formal RFC MIME types.  As a result,
521      * you should always write your MIME types with lower case letters,
522      * and any MIME types you receive from outside of Android should be
523      * converted to lower case before supplying them here.</em></p>
524      *
525      * <p>Throws {@link MalformedMimeTypeException} if the given MIME type is
526      * not syntactically correct.
527      *
528      * @param type Name of the data type to match, i.e. "vnd.android.cursor.dir/person".
529      *
530      * @see #matchData
531      */
addDataType(String type)532     public final void addDataType(String type)
533         throws MalformedMimeTypeException {
534         final int slashpos = type.indexOf('/');
535         final int typelen = type.length();
536         if (slashpos > 0 && typelen >= slashpos+2) {
537             if (mDataTypes == null) mDataTypes = new ArrayList<String>();
538             if (typelen == slashpos+2 && type.charAt(slashpos+1) == '*') {
539                 String str = type.substring(0, slashpos);
540                 if (!mDataTypes.contains(str)) {
541                     mDataTypes.add(str.intern());
542                 }
543                 mHasPartialTypes = true;
544             } else {
545                 if (!mDataTypes.contains(type)) {
546                     mDataTypes.add(type.intern());
547                 }
548             }
549             return;
550         }
551 
552         throw new MalformedMimeTypeException(type);
553     }
554 
555     /**
556      * Is the given data type included in the filter?  Note that if the filter
557      * does not include any type, false will <em>always</em> be returned.
558      *
559      * @param type The data type to look for.
560      *
561      * @return True if the type is explicitly mentioned in the filter.
562      */
hasDataType(String type)563     public final boolean hasDataType(String type) {
564         return mDataTypes != null && findMimeType(type);
565     }
566 
567     /**
568      * Return the number of data types in the filter.
569      */
countDataTypes()570     public final int countDataTypes() {
571         return mDataTypes != null ? mDataTypes.size() : 0;
572     }
573 
574     /**
575      * Return a data type in the filter.
576      */
getDataType(int index)577     public final String getDataType(int index) {
578         return mDataTypes.get(index);
579     }
580 
581     /**
582      * Return an iterator over the filter's data types.
583      */
typesIterator()584     public final Iterator<String> typesIterator() {
585         return mDataTypes != null ? mDataTypes.iterator() : null;
586     }
587 
588     /**
589      * Add a new Intent data scheme to match against.  If any schemes are
590      * included in the filter, then an Intent's data must be <em>either</em>
591      * one of these schemes <em>or</em> a matching data type.  If no schemes
592      * are included, then an Intent will match only if it includes no data.
593      *
594      * <p><em>Note: scheme matching in the Android framework is
595      * case-sensitive, unlike formal RFC schemes.  As a result,
596      * you should always write your schemes with lower case letters,
597      * and any schemes you receive from outside of Android should be
598      * converted to lower case before supplying them here.</em></p>
599      *
600      * @param scheme Name of the scheme to match, i.e. "http".
601      *
602      * @see #matchData
603      */
addDataScheme(String scheme)604     public final void addDataScheme(String scheme) {
605         if (mDataSchemes == null) mDataSchemes = new ArrayList<String>();
606         if (!mDataSchemes.contains(scheme)) {
607             mDataSchemes.add(scheme.intern());
608         }
609     }
610 
611     /**
612      * Return the number of data schemes in the filter.
613      */
countDataSchemes()614     public final int countDataSchemes() {
615         return mDataSchemes != null ? mDataSchemes.size() : 0;
616     }
617 
618     /**
619      * Return a data scheme in the filter.
620      */
getDataScheme(int index)621     public final String getDataScheme(int index) {
622         return mDataSchemes.get(index);
623     }
624 
625     /**
626      * Is the given data scheme included in the filter?  Note that if the
627      * filter does not include any scheme, false will <em>always</em> be
628      * returned.
629      *
630      * @param scheme The data scheme to look for.
631      *
632      * @return True if the scheme is explicitly mentioned in the filter.
633      */
hasDataScheme(String scheme)634     public final boolean hasDataScheme(String scheme) {
635         return mDataSchemes != null && mDataSchemes.contains(scheme);
636     }
637 
638     /**
639      * Return an iterator over the filter's data schemes.
640      */
schemesIterator()641     public final Iterator<String> schemesIterator() {
642         return mDataSchemes != null ? mDataSchemes.iterator() : null;
643     }
644 
645     /**
646      * This is an entry for a single authority in the Iterator returned by
647      * {@link #authoritiesIterator()}.
648      */
649     public final static class AuthorityEntry {
650         private final String mOrigHost;
651         private final String mHost;
652         private final boolean mWild;
653         private final int mPort;
654 
AuthorityEntry(String host, String port)655         public AuthorityEntry(String host, String port) {
656             mOrigHost = host;
657             mWild = host.length() > 0 && host.charAt(0) == '*';
658             mHost = mWild ? host.substring(1).intern() : host;
659             mPort = port != null ? Integer.parseInt(port) : -1;
660         }
661 
AuthorityEntry(Parcel src)662         AuthorityEntry(Parcel src) {
663             mOrigHost = src.readString();
664             mHost = src.readString();
665             mWild = src.readInt() != 0;
666             mPort = src.readInt();
667         }
668 
writeToParcel(Parcel dest)669         void writeToParcel(Parcel dest) {
670             dest.writeString(mOrigHost);
671             dest.writeString(mHost);
672             dest.writeInt(mWild ? 1 : 0);
673             dest.writeInt(mPort);
674         }
675 
getHost()676         public String getHost() {
677             return mOrigHost;
678         }
679 
getPort()680         public int getPort() {
681             return mPort;
682         }
683 
684         /**
685          * Determine whether this AuthorityEntry matches the given data Uri.
686          * <em>Note that this comparison is case-sensitive, unlike formal
687          * RFC host names.  You thus should always normalize to lower-case.</em>
688          *
689          * @param data The Uri to match.
690          * @return Returns either {@link IntentFilter#NO_MATCH_DATA},
691          * {@link IntentFilter#MATCH_CATEGORY_PORT}, or
692          * {@link IntentFilter#MATCH_CATEGORY_HOST}.
693          */
match(Uri data)694         public int match(Uri data) {
695             String host = data.getHost();
696             if (host == null) {
697                 return NO_MATCH_DATA;
698             }
699             if (false) Log.v("IntentFilter",
700                     "Match host " + host + ": " + mHost);
701             if (mWild) {
702                 if (host.length() < mHost.length()) {
703                     return NO_MATCH_DATA;
704                 }
705                 host = host.substring(host.length()-mHost.length());
706             }
707             if (host.compareToIgnoreCase(mHost) != 0) {
708                 return NO_MATCH_DATA;
709             }
710             if (mPort >= 0) {
711                 if (mPort != data.getPort()) {
712                     return NO_MATCH_DATA;
713                 }
714                 return MATCH_CATEGORY_PORT;
715             }
716             return MATCH_CATEGORY_HOST;
717         }
718     };
719 
720     /**
721      * Add a new Intent data "scheme specific part" to match against.  The filter must
722      * include one or more schemes (via {@link #addDataScheme}) for the
723      * scheme specific part to be considered.  If any scheme specific parts are
724      * included in the filter, then an Intent's data must match one of
725      * them.  If no scheme specific parts are included, then only the scheme must match.
726      *
727      * <p>The "scheme specific part" that this matches against is the string returned
728      * by {@link android.net.Uri#getSchemeSpecificPart() Uri.getSchemeSpecificPart}.
729      * For Uris that contain a path, this kind of matching is not generally of interest,
730      * since {@link #addDataAuthority(String, String)} and
731      * {@link #addDataPath(String, int)} can provide a better mechanism for matching
732      * them.  However, for Uris that do not contain a path, the authority and path
733      * are empty, so this is the only way to match against the non-scheme part.</p>
734      *
735      * @param ssp Either a raw string that must exactly match the scheme specific part
736      * path, or a simple pattern, depending on <var>type</var>.
737      * @param type Determines how <var>ssp</var> will be compared to
738      * determine a match: either {@link PatternMatcher#PATTERN_LITERAL},
739      * {@link PatternMatcher#PATTERN_PREFIX}, or
740      * {@link PatternMatcher#PATTERN_SIMPLE_GLOB}.
741      *
742      * @see #matchData
743      * @see #addDataScheme
744      */
addDataSchemeSpecificPart(String ssp, int type)745     public final void addDataSchemeSpecificPart(String ssp, int type) {
746         addDataSchemeSpecificPart(new PatternMatcher(ssp, type));
747     }
748 
749     /** @hide */
addDataSchemeSpecificPart(PatternMatcher ssp)750     public final void addDataSchemeSpecificPart(PatternMatcher ssp) {
751         if (mDataSchemeSpecificParts == null) {
752             mDataSchemeSpecificParts = new ArrayList<PatternMatcher>();
753         }
754         mDataSchemeSpecificParts.add(ssp);
755     }
756 
757     /**
758      * Return the number of data scheme specific parts in the filter.
759      */
countDataSchemeSpecificParts()760     public final int countDataSchemeSpecificParts() {
761         return mDataSchemeSpecificParts != null ? mDataSchemeSpecificParts.size() : 0;
762     }
763 
764     /**
765      * Return a data scheme specific part in the filter.
766      */
getDataSchemeSpecificPart(int index)767     public final PatternMatcher getDataSchemeSpecificPart(int index) {
768         return mDataSchemeSpecificParts.get(index);
769     }
770 
771     /**
772      * Is the given data scheme specific part included in the filter?  Note that if the
773      * filter does not include any scheme specific parts, false will <em>always</em> be
774      * returned.
775      *
776      * @param data The scheme specific part that is being looked for.
777      *
778      * @return Returns true if the data string matches a scheme specific part listed in the
779      *         filter.
780      */
hasDataSchemeSpecificPart(String data)781     public final boolean hasDataSchemeSpecificPart(String data) {
782         if (mDataSchemeSpecificParts == null) {
783             return false;
784         }
785         final int numDataSchemeSpecificParts = mDataSchemeSpecificParts.size();
786         for (int i = 0; i < numDataSchemeSpecificParts; i++) {
787             final PatternMatcher pe = mDataSchemeSpecificParts.get(i);
788             if (pe.match(data)) {
789                 return true;
790             }
791         }
792         return false;
793     }
794 
795     /**
796      * Return an iterator over the filter's data scheme specific parts.
797      */
schemeSpecificPartsIterator()798     public final Iterator<PatternMatcher> schemeSpecificPartsIterator() {
799         return mDataSchemeSpecificParts != null ? mDataSchemeSpecificParts.iterator() : null;
800     }
801 
802     /**
803      * Add a new Intent data authority to match against.  The filter must
804      * include one or more schemes (via {@link #addDataScheme}) for the
805      * authority to be considered.  If any authorities are
806      * included in the filter, then an Intent's data must match one of
807      * them.  If no authorities are included, then only the scheme must match.
808      *
809      * <p><em>Note: host name in the Android framework is
810      * case-sensitive, unlike formal RFC host names.  As a result,
811      * you should always write your host names with lower case letters,
812      * and any host names you receive from outside of Android should be
813      * converted to lower case before supplying them here.</em></p>
814      *
815      * @param host The host part of the authority to match.  May start with a
816      *             single '*' to wildcard the front of the host name.
817      * @param port Optional port part of the authority to match.  If null, any
818      *             port is allowed.
819      *
820      * @see #matchData
821      * @see #addDataScheme
822      */
addDataAuthority(String host, String port)823     public final void addDataAuthority(String host, String port) {
824         if (port != null) port = port.intern();
825         addDataAuthority(new AuthorityEntry(host.intern(), port));
826     }
827 
828     /** @hide */
addDataAuthority(AuthorityEntry ent)829     public final void addDataAuthority(AuthorityEntry ent) {
830         if (mDataAuthorities == null) mDataAuthorities =
831                 new ArrayList<AuthorityEntry>();
832         mDataAuthorities.add(ent);
833     }
834 
835     /**
836      * Return the number of data authorities in the filter.
837      */
countDataAuthorities()838     public final int countDataAuthorities() {
839         return mDataAuthorities != null ? mDataAuthorities.size() : 0;
840     }
841 
842     /**
843      * Return a data authority in the filter.
844      */
getDataAuthority(int index)845     public final AuthorityEntry getDataAuthority(int index) {
846         return mDataAuthorities.get(index);
847     }
848 
849     /**
850      * Is the given data authority included in the filter?  Note that if the
851      * filter does not include any authorities, false will <em>always</em> be
852      * returned.
853      *
854      * @param data The data whose authority is being looked for.
855      *
856      * @return Returns true if the data string matches an authority listed in the
857      *         filter.
858      */
hasDataAuthority(Uri data)859     public final boolean hasDataAuthority(Uri data) {
860         return matchDataAuthority(data) >= 0;
861     }
862 
863     /**
864      * Return an iterator over the filter's data authorities.
865      */
authoritiesIterator()866     public final Iterator<AuthorityEntry> authoritiesIterator() {
867         return mDataAuthorities != null ? mDataAuthorities.iterator() : null;
868     }
869 
870     /**
871      * Add a new Intent data path to match against.  The filter must
872      * include one or more schemes (via {@link #addDataScheme}) <em>and</em>
873      * one or more authorities (via {@link #addDataAuthority}) for the
874      * path to be considered.  If any paths are
875      * included in the filter, then an Intent's data must match one of
876      * them.  If no paths are included, then only the scheme/authority must
877      * match.
878      *
879      * <p>The path given here can either be a literal that must directly
880      * match or match against a prefix, or it can be a simple globbing pattern.
881      * If the latter, you can use '*' anywhere in the pattern to match zero
882      * or more instances of the previous character, '.' as a wildcard to match
883      * any character, and '\' to escape the next character.
884      *
885      * @param path Either a raw string that must exactly match the file
886      * path, or a simple pattern, depending on <var>type</var>.
887      * @param type Determines how <var>path</var> will be compared to
888      * determine a match: either {@link PatternMatcher#PATTERN_LITERAL},
889      * {@link PatternMatcher#PATTERN_PREFIX}, or
890      * {@link PatternMatcher#PATTERN_SIMPLE_GLOB}.
891      *
892      * @see #matchData
893      * @see #addDataScheme
894      * @see #addDataAuthority
895      */
addDataPath(String path, int type)896     public final void addDataPath(String path, int type) {
897         addDataPath(new PatternMatcher(path.intern(), type));
898     }
899 
900     /** @hide */
addDataPath(PatternMatcher path)901     public final void addDataPath(PatternMatcher path) {
902         if (mDataPaths == null) mDataPaths = new ArrayList<PatternMatcher>();
903         mDataPaths.add(path);
904     }
905 
906     /**
907      * Return the number of data paths in the filter.
908      */
countDataPaths()909     public final int countDataPaths() {
910         return mDataPaths != null ? mDataPaths.size() : 0;
911     }
912 
913     /**
914      * Return a data path in the filter.
915      */
getDataPath(int index)916     public final PatternMatcher getDataPath(int index) {
917         return mDataPaths.get(index);
918     }
919 
920     /**
921      * Is the given data path included in the filter?  Note that if the
922      * filter does not include any paths, false will <em>always</em> be
923      * returned.
924      *
925      * @param data The data path to look for.  This is without the scheme
926      *             prefix.
927      *
928      * @return True if the data string matches a path listed in the
929      *         filter.
930      */
hasDataPath(String data)931     public final boolean hasDataPath(String data) {
932         if (mDataPaths == null) {
933             return false;
934         }
935         final int numDataPaths = mDataPaths.size();
936         for (int i = 0; i < numDataPaths; i++) {
937             final PatternMatcher pe = mDataPaths.get(i);
938             if (pe.match(data)) {
939                 return true;
940             }
941         }
942         return false;
943     }
944 
945     /**
946      * Return an iterator over the filter's data paths.
947      */
pathsIterator()948     public final Iterator<PatternMatcher> pathsIterator() {
949         return mDataPaths != null ? mDataPaths.iterator() : null;
950     }
951 
952     /**
953      * Match this intent filter against the given Intent data.  This ignores
954      * the data scheme -- unlike {@link #matchData}, the authority will match
955      * regardless of whether there is a matching scheme.
956      *
957      * @param data The data whose authority is being looked for.
958      *
959      * @return Returns either {@link #MATCH_CATEGORY_HOST},
960      * {@link #MATCH_CATEGORY_PORT}, {@link #NO_MATCH_DATA}.
961      */
matchDataAuthority(Uri data)962     public final int matchDataAuthority(Uri data) {
963         if (mDataAuthorities == null) {
964             return NO_MATCH_DATA;
965         }
966         final int numDataAuthorities = mDataAuthorities.size();
967         for (int i = 0; i < numDataAuthorities; i++) {
968             final AuthorityEntry ae = mDataAuthorities.get(i);
969             int match = ae.match(data);
970             if (match >= 0) {
971                 return match;
972             }
973         }
974         return NO_MATCH_DATA;
975     }
976 
977     /**
978      * Match this filter against an Intent's data (type, scheme and path). If
979      * the filter does not specify any types and does not specify any
980      * schemes/paths, the match will only succeed if the intent does not
981      * also specify a type or data.  If the filter does not specify any schemes,
982      * it will implicitly match intents with no scheme, or the schemes "content:"
983      * or "file:" (basically performing a MIME-type only match).  If the filter
984      * does not specify any MIME types, the Intent also must not specify a MIME
985      * type.
986      *
987      * <p>Be aware that to match against an authority, you must also specify a base
988      * scheme the authority is in.  To match against a data path, both a scheme
989      * and authority must be specified.  If the filter does not specify any
990      * types or schemes that it matches against, it is considered to be empty
991      * (any authority or data path given is ignored, as if it were empty as
992      * well).
993      *
994      * <p><em>Note: MIME type, Uri scheme, and host name matching in the
995      * Android framework is case-sensitive, unlike the formal RFC definitions.
996      * As a result, you should always write these elements with lower case letters,
997      * and normalize any MIME types or Uris you receive from
998      * outside of Android to ensure these elements are lower case before
999      * supplying them here.</em></p>
1000      *
1001      * @param type The desired data type to look for, as returned by
1002      *             Intent.resolveType().
1003      * @param scheme The desired data scheme to look for, as returned by
1004      *               Intent.getScheme().
1005      * @param data The full data string to match against, as supplied in
1006      *             Intent.data.
1007      *
1008      * @return Returns either a valid match constant (a combination of
1009      * {@link #MATCH_CATEGORY_MASK} and {@link #MATCH_ADJUSTMENT_MASK}),
1010      * or one of the error codes {@link #NO_MATCH_TYPE} if the type didn't match
1011      * or {@link #NO_MATCH_DATA} if the scheme/path didn't match.
1012      *
1013      * @see #match
1014      */
matchData(String type, String scheme, Uri data)1015     public final int matchData(String type, String scheme, Uri data) {
1016         final ArrayList<String> types = mDataTypes;
1017         final ArrayList<String> schemes = mDataSchemes;
1018 
1019         int match = MATCH_CATEGORY_EMPTY;
1020 
1021         if (types == null && schemes == null) {
1022             return ((type == null && data == null)
1023                 ? (MATCH_CATEGORY_EMPTY+MATCH_ADJUSTMENT_NORMAL) : NO_MATCH_DATA);
1024         }
1025 
1026         if (schemes != null) {
1027             if (schemes.contains(scheme != null ? scheme : "")) {
1028                 match = MATCH_CATEGORY_SCHEME;
1029             } else {
1030                 return NO_MATCH_DATA;
1031             }
1032 
1033             final ArrayList<PatternMatcher> schemeSpecificParts = mDataSchemeSpecificParts;
1034             if (schemeSpecificParts != null) {
1035                 match = hasDataSchemeSpecificPart(data.getSchemeSpecificPart())
1036                         ? MATCH_CATEGORY_SCHEME_SPECIFIC_PART : NO_MATCH_DATA;
1037             }
1038             if (match != MATCH_CATEGORY_SCHEME_SPECIFIC_PART) {
1039                 // If there isn't any matching ssp, we need to match an authority.
1040                 final ArrayList<AuthorityEntry> authorities = mDataAuthorities;
1041                 if (authorities != null) {
1042                     int authMatch = matchDataAuthority(data);
1043                     if (authMatch >= 0) {
1044                         final ArrayList<PatternMatcher> paths = mDataPaths;
1045                         if (paths == null) {
1046                             match = authMatch;
1047                         } else if (hasDataPath(data.getPath())) {
1048                             match = MATCH_CATEGORY_PATH;
1049                         } else {
1050                             return NO_MATCH_DATA;
1051                         }
1052                     } else {
1053                         return NO_MATCH_DATA;
1054                     }
1055                 }
1056             }
1057             // If neither an ssp nor an authority matched, we're done.
1058             if (match == NO_MATCH_DATA) {
1059                 return NO_MATCH_DATA;
1060             }
1061         } else {
1062             // Special case: match either an Intent with no data URI,
1063             // or with a scheme: URI.  This is to give a convenience for
1064             // the common case where you want to deal with data in a
1065             // content provider, which is done by type, and we don't want
1066             // to force everyone to say they handle content: or file: URIs.
1067             if (scheme != null && !"".equals(scheme)
1068                     && !"content".equals(scheme)
1069                     && !"file".equals(scheme)) {
1070                 return NO_MATCH_DATA;
1071             }
1072         }
1073 
1074         if (types != null) {
1075             if (findMimeType(type)) {
1076                 match = MATCH_CATEGORY_TYPE;
1077             } else {
1078                 return NO_MATCH_TYPE;
1079             }
1080         } else {
1081             // If no MIME types are specified, then we will only match against
1082             // an Intent that does not have a MIME type.
1083             if (type != null) {
1084                 return NO_MATCH_TYPE;
1085             }
1086         }
1087 
1088         return match + MATCH_ADJUSTMENT_NORMAL;
1089     }
1090 
1091     /**
1092      * Add a new Intent category to match against.  The semantics of
1093      * categories is the opposite of actions -- an Intent includes the
1094      * categories that it requires, all of which must be included in the
1095      * filter in order to match.  In other words, adding a category to the
1096      * filter has no impact on matching unless that category is specified in
1097      * the intent.
1098      *
1099      * @param category Name of category to match, i.e. Intent.CATEGORY_EMBED.
1100      */
addCategory(String category)1101     public final void addCategory(String category) {
1102         if (mCategories == null) mCategories = new ArrayList<String>();
1103         if (!mCategories.contains(category)) {
1104             mCategories.add(category.intern());
1105         }
1106     }
1107 
1108     /**
1109      * Return the number of categories in the filter.
1110      */
countCategories()1111     public final int countCategories() {
1112         return mCategories != null ? mCategories.size() : 0;
1113     }
1114 
1115     /**
1116      * Return a category in the filter.
1117      */
getCategory(int index)1118     public final String getCategory(int index) {
1119         return mCategories.get(index);
1120     }
1121 
1122     /**
1123      * Is the given category included in the filter?
1124      *
1125      * @param category The category that the filter supports.
1126      *
1127      * @return True if the category is explicitly mentioned in the filter.
1128      */
hasCategory(String category)1129     public final boolean hasCategory(String category) {
1130         return mCategories != null && mCategories.contains(category);
1131     }
1132 
1133     /**
1134      * Return an iterator over the filter's categories.
1135      *
1136      * @return Iterator if this filter has categories or {@code null} if none.
1137      */
categoriesIterator()1138     public final Iterator<String> categoriesIterator() {
1139         return mCategories != null ? mCategories.iterator() : null;
1140     }
1141 
1142     /**
1143      * Match this filter against an Intent's categories.  Each category in
1144      * the Intent must be specified by the filter; if any are not in the
1145      * filter, the match fails.
1146      *
1147      * @param categories The categories included in the intent, as returned by
1148      *                   Intent.getCategories().
1149      *
1150      * @return If all categories match (success), null; else the name of the
1151      *         first category that didn't match.
1152      */
matchCategories(Set<String> categories)1153     public final String matchCategories(Set<String> categories) {
1154         if (categories == null) {
1155             return null;
1156         }
1157 
1158         Iterator<String> it = categories.iterator();
1159 
1160         if (mCategories == null) {
1161             return it.hasNext() ? it.next() : null;
1162         }
1163 
1164         while (it.hasNext()) {
1165             final String category = it.next();
1166             if (!mCategories.contains(category)) {
1167                 return category;
1168             }
1169         }
1170 
1171         return null;
1172     }
1173 
1174     /**
1175      * Test whether this filter matches the given <var>intent</var>.
1176      *
1177      * @param intent The Intent to compare against.
1178      * @param resolve If true, the intent's type will be resolved by calling
1179      *                Intent.resolveType(); otherwise a simple match against
1180      *                Intent.type will be performed.
1181      * @param logTag Tag to use in debugging messages.
1182      *
1183      * @return Returns either a valid match constant (a combination of
1184      * {@link #MATCH_CATEGORY_MASK} and {@link #MATCH_ADJUSTMENT_MASK}),
1185      * or one of the error codes {@link #NO_MATCH_TYPE} if the type didn't match,
1186      * {@link #NO_MATCH_DATA} if the scheme/path didn't match,
1187      * {@link #NO_MATCH_ACTION if the action didn't match, or
1188      * {@link #NO_MATCH_CATEGORY} if one or more categories didn't match.
1189      *
1190      * @return How well the filter matches.  Negative if it doesn't match,
1191      *         zero or positive positive value if it does with a higher
1192      *         value representing a better match.
1193      *
1194      * @see #match(String, String, String, android.net.Uri , Set, String)
1195      */
match(ContentResolver resolver, Intent intent, boolean resolve, String logTag)1196     public final int match(ContentResolver resolver, Intent intent,
1197             boolean resolve, String logTag) {
1198         String type = resolve ? intent.resolveType(resolver) : intent.getType();
1199         return match(intent.getAction(), type, intent.getScheme(),
1200                      intent.getData(), intent.getCategories(), logTag);
1201     }
1202 
1203     /**
1204      * Test whether this filter matches the given intent data.  A match is
1205      * only successful if the actions and categories in the Intent match
1206      * against the filter, as described in {@link IntentFilter}; in that case,
1207      * the match result returned will be as per {@link #matchData}.
1208      *
1209      * @param action The intent action to match against (Intent.getAction).
1210      * @param type The intent type to match against (Intent.resolveType()).
1211      * @param scheme The data scheme to match against (Intent.getScheme()).
1212      * @param data The data URI to match against (Intent.getData()).
1213      * @param categories The categories to match against
1214      *                   (Intent.getCategories()).
1215      * @param logTag Tag to use in debugging messages.
1216      *
1217      * @return Returns either a valid match constant (a combination of
1218      * {@link #MATCH_CATEGORY_MASK} and {@link #MATCH_ADJUSTMENT_MASK}),
1219      * or one of the error codes {@link #NO_MATCH_TYPE} if the type didn't match,
1220      * {@link #NO_MATCH_DATA} if the scheme/path didn't match,
1221      * {@link #NO_MATCH_ACTION if the action didn't match, or
1222      * {@link #NO_MATCH_CATEGORY} if one or more categories didn't match.
1223      *
1224      * @see #matchData
1225      * @see Intent#getAction
1226      * @see Intent#resolveType
1227      * @see Intent#getScheme
1228      * @see Intent#getData
1229      * @see Intent#getCategories
1230      */
match(String action, String type, String scheme, Uri data, Set<String> categories, String logTag)1231     public final int match(String action, String type, String scheme,
1232             Uri data, Set<String> categories, String logTag) {
1233         if (action != null && !matchAction(action)) {
1234             if (false) Log.v(
1235                 logTag, "No matching action " + action + " for " + this);
1236             return NO_MATCH_ACTION;
1237         }
1238 
1239         int dataMatch = matchData(type, scheme, data);
1240         if (dataMatch < 0) {
1241             if (false) {
1242                 if (dataMatch == NO_MATCH_TYPE) {
1243                     Log.v(logTag, "No matching type " + type
1244                           + " for " + this);
1245                 }
1246                 if (dataMatch == NO_MATCH_DATA) {
1247                     Log.v(logTag, "No matching scheme/path " + data
1248                           + " for " + this);
1249                 }
1250             }
1251             return dataMatch;
1252         }
1253 
1254         String categoryMismatch = matchCategories(categories);
1255         if (categoryMismatch != null) {
1256             if (false) {
1257                 Log.v(logTag, "No matching category " + categoryMismatch + " for " + this);
1258             }
1259             return NO_MATCH_CATEGORY;
1260         }
1261 
1262         // It would be nice to treat container activities as more
1263         // important than ones that can be embedded, but this is not the way...
1264         if (false) {
1265             if (categories != null) {
1266                 dataMatch -= mCategories.size() - categories.size();
1267             }
1268         }
1269 
1270         return dataMatch;
1271     }
1272 
1273     /**
1274      * Write the contents of the IntentFilter as an XML stream.
1275      */
writeToXml(XmlSerializer serializer)1276     public void writeToXml(XmlSerializer serializer) throws IOException {
1277         int N = countActions();
1278         for (int i=0; i<N; i++) {
1279             serializer.startTag(null, ACTION_STR);
1280             serializer.attribute(null, NAME_STR, mActions.get(i));
1281             serializer.endTag(null, ACTION_STR);
1282         }
1283         N = countCategories();
1284         for (int i=0; i<N; i++) {
1285             serializer.startTag(null, CAT_STR);
1286             serializer.attribute(null, NAME_STR, mCategories.get(i));
1287             serializer.endTag(null, CAT_STR);
1288         }
1289         N = countDataTypes();
1290         for (int i=0; i<N; i++) {
1291             serializer.startTag(null, TYPE_STR);
1292             String type = mDataTypes.get(i);
1293             if (type.indexOf('/') < 0) type = type + "/*";
1294             serializer.attribute(null, NAME_STR, type);
1295             serializer.endTag(null, TYPE_STR);
1296         }
1297         N = countDataSchemes();
1298         for (int i=0; i<N; i++) {
1299             serializer.startTag(null, SCHEME_STR);
1300             serializer.attribute(null, NAME_STR, mDataSchemes.get(i));
1301             serializer.endTag(null, SCHEME_STR);
1302         }
1303         N = countDataSchemeSpecificParts();
1304         for (int i=0; i<N; i++) {
1305             serializer.startTag(null, SSP_STR);
1306             PatternMatcher pe = mDataSchemeSpecificParts.get(i);
1307             switch (pe.getType()) {
1308                 case PatternMatcher.PATTERN_LITERAL:
1309                     serializer.attribute(null, LITERAL_STR, pe.getPath());
1310                     break;
1311                 case PatternMatcher.PATTERN_PREFIX:
1312                     serializer.attribute(null, PREFIX_STR, pe.getPath());
1313                     break;
1314                 case PatternMatcher.PATTERN_SIMPLE_GLOB:
1315                     serializer.attribute(null, SGLOB_STR, pe.getPath());
1316                     break;
1317             }
1318             serializer.endTag(null, SSP_STR);
1319         }
1320         N = countDataAuthorities();
1321         for (int i=0; i<N; i++) {
1322             serializer.startTag(null, AUTH_STR);
1323             AuthorityEntry ae = mDataAuthorities.get(i);
1324             serializer.attribute(null, HOST_STR, ae.getHost());
1325             if (ae.getPort() >= 0) {
1326                 serializer.attribute(null, PORT_STR, Integer.toString(ae.getPort()));
1327             }
1328             serializer.endTag(null, AUTH_STR);
1329         }
1330         N = countDataPaths();
1331         for (int i=0; i<N; i++) {
1332             serializer.startTag(null, PATH_STR);
1333             PatternMatcher pe = mDataPaths.get(i);
1334             switch (pe.getType()) {
1335                 case PatternMatcher.PATTERN_LITERAL:
1336                     serializer.attribute(null, LITERAL_STR, pe.getPath());
1337                     break;
1338                 case PatternMatcher.PATTERN_PREFIX:
1339                     serializer.attribute(null, PREFIX_STR, pe.getPath());
1340                     break;
1341                 case PatternMatcher.PATTERN_SIMPLE_GLOB:
1342                     serializer.attribute(null, SGLOB_STR, pe.getPath());
1343                     break;
1344             }
1345             serializer.endTag(null, PATH_STR);
1346         }
1347     }
1348 
readFromXml(XmlPullParser parser)1349     public void readFromXml(XmlPullParser parser) throws XmlPullParserException,
1350             IOException {
1351         int outerDepth = parser.getDepth();
1352         int type;
1353         while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1354                && (type != XmlPullParser.END_TAG
1355                        || parser.getDepth() > outerDepth)) {
1356             if (type == XmlPullParser.END_TAG
1357                     || type == XmlPullParser.TEXT) {
1358                 continue;
1359             }
1360 
1361             String tagName = parser.getName();
1362             if (tagName.equals(ACTION_STR)) {
1363                 String name = parser.getAttributeValue(null, NAME_STR);
1364                 if (name != null) {
1365                     addAction(name);
1366                 }
1367             } else if (tagName.equals(CAT_STR)) {
1368                 String name = parser.getAttributeValue(null, NAME_STR);
1369                 if (name != null) {
1370                     addCategory(name);
1371                 }
1372             } else if (tagName.equals(TYPE_STR)) {
1373                 String name = parser.getAttributeValue(null, NAME_STR);
1374                 if (name != null) {
1375                     try {
1376                         addDataType(name);
1377                     } catch (MalformedMimeTypeException e) {
1378                     }
1379                 }
1380             } else if (tagName.equals(SCHEME_STR)) {
1381                 String name = parser.getAttributeValue(null, NAME_STR);
1382                 if (name != null) {
1383                     addDataScheme(name);
1384                 }
1385             } else if (tagName.equals(SSP_STR)) {
1386                 String ssp = parser.getAttributeValue(null, LITERAL_STR);
1387                 if (ssp != null) {
1388                     addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_LITERAL);
1389                 } else if ((ssp=parser.getAttributeValue(null, PREFIX_STR)) != null) {
1390                     addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_PREFIX);
1391                 } else if ((ssp=parser.getAttributeValue(null, SGLOB_STR)) != null) {
1392                     addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_SIMPLE_GLOB);
1393                 }
1394             } else if (tagName.equals(AUTH_STR)) {
1395                 String host = parser.getAttributeValue(null, HOST_STR);
1396                 String port = parser.getAttributeValue(null, PORT_STR);
1397                 if (host != null) {
1398                     addDataAuthority(host, port);
1399                 }
1400             } else if (tagName.equals(PATH_STR)) {
1401                 String path = parser.getAttributeValue(null, LITERAL_STR);
1402                 if (path != null) {
1403                     addDataPath(path, PatternMatcher.PATTERN_LITERAL);
1404                 } else if ((path=parser.getAttributeValue(null, PREFIX_STR)) != null) {
1405                     addDataPath(path, PatternMatcher.PATTERN_PREFIX);
1406                 } else if ((path=parser.getAttributeValue(null, SGLOB_STR)) != null) {
1407                     addDataPath(path, PatternMatcher.PATTERN_SIMPLE_GLOB);
1408                 }
1409             } else {
1410                 Log.w("IntentFilter", "Unknown tag parsing IntentFilter: " + tagName);
1411             }
1412             XmlUtils.skipCurrentTag(parser);
1413         }
1414     }
1415 
dump(Printer du, String prefix)1416     public void dump(Printer du, String prefix) {
1417         StringBuilder sb = new StringBuilder(256);
1418         if (mActions.size() > 0) {
1419             Iterator<String> it = mActions.iterator();
1420             while (it.hasNext()) {
1421                 sb.setLength(0);
1422                 sb.append(prefix); sb.append("Action: \"");
1423                         sb.append(it.next()); sb.append("\"");
1424                 du.println(sb.toString());
1425             }
1426         }
1427         if (mCategories != null) {
1428             Iterator<String> it = mCategories.iterator();
1429             while (it.hasNext()) {
1430                 sb.setLength(0);
1431                 sb.append(prefix); sb.append("Category: \"");
1432                         sb.append(it.next()); sb.append("\"");
1433                 du.println(sb.toString());
1434             }
1435         }
1436         if (mDataSchemes != null) {
1437             Iterator<String> it = mDataSchemes.iterator();
1438             while (it.hasNext()) {
1439                 sb.setLength(0);
1440                 sb.append(prefix); sb.append("Scheme: \"");
1441                         sb.append(it.next()); sb.append("\"");
1442                 du.println(sb.toString());
1443             }
1444         }
1445         if (mDataSchemeSpecificParts != null) {
1446             Iterator<PatternMatcher> it = mDataSchemeSpecificParts.iterator();
1447             while (it.hasNext()) {
1448                 PatternMatcher pe = it.next();
1449                 sb.setLength(0);
1450                 sb.append(prefix); sb.append("Ssp: \"");
1451                         sb.append(pe); sb.append("\"");
1452                 du.println(sb.toString());
1453             }
1454         }
1455         if (mDataAuthorities != null) {
1456             Iterator<AuthorityEntry> it = mDataAuthorities.iterator();
1457             while (it.hasNext()) {
1458                 AuthorityEntry ae = it.next();
1459                 sb.setLength(0);
1460                 sb.append(prefix); sb.append("Authority: \"");
1461                         sb.append(ae.mHost); sb.append("\": ");
1462                         sb.append(ae.mPort);
1463                 if (ae.mWild) sb.append(" WILD");
1464                 du.println(sb.toString());
1465             }
1466         }
1467         if (mDataPaths != null) {
1468             Iterator<PatternMatcher> it = mDataPaths.iterator();
1469             while (it.hasNext()) {
1470                 PatternMatcher pe = it.next();
1471                 sb.setLength(0);
1472                 sb.append(prefix); sb.append("Path: \"");
1473                         sb.append(pe); sb.append("\"");
1474                 du.println(sb.toString());
1475             }
1476         }
1477         if (mDataTypes != null) {
1478             Iterator<String> it = mDataTypes.iterator();
1479             while (it.hasNext()) {
1480                 sb.setLength(0);
1481                 sb.append(prefix); sb.append("Type: \"");
1482                         sb.append(it.next()); sb.append("\"");
1483                 du.println(sb.toString());
1484             }
1485         }
1486         if (mPriority != 0 || mHasPartialTypes) {
1487             sb.setLength(0);
1488             sb.append(prefix); sb.append("mPriority="); sb.append(mPriority);
1489                     sb.append(", mHasPartialTypes="); sb.append(mHasPartialTypes);
1490             du.println(sb.toString());
1491         }
1492     }
1493 
1494     public static final Parcelable.Creator<IntentFilter> CREATOR
1495             = new Parcelable.Creator<IntentFilter>() {
1496         public IntentFilter createFromParcel(Parcel source) {
1497             return new IntentFilter(source);
1498         }
1499 
1500         public IntentFilter[] newArray(int size) {
1501             return new IntentFilter[size];
1502         }
1503     };
1504 
describeContents()1505     public final int describeContents() {
1506         return 0;
1507     }
1508 
writeToParcel(Parcel dest, int flags)1509     public final void writeToParcel(Parcel dest, int flags) {
1510         dest.writeStringList(mActions);
1511         if (mCategories != null) {
1512             dest.writeInt(1);
1513             dest.writeStringList(mCategories);
1514         } else {
1515             dest.writeInt(0);
1516         }
1517         if (mDataSchemes != null) {
1518             dest.writeInt(1);
1519             dest.writeStringList(mDataSchemes);
1520         } else {
1521             dest.writeInt(0);
1522         }
1523         if (mDataTypes != null) {
1524             dest.writeInt(1);
1525             dest.writeStringList(mDataTypes);
1526         } else {
1527             dest.writeInt(0);
1528         }
1529         if (mDataSchemeSpecificParts != null) {
1530             final int N = mDataSchemeSpecificParts.size();
1531             dest.writeInt(N);
1532             for (int i=0; i<N; i++) {
1533                 mDataSchemeSpecificParts.get(i).writeToParcel(dest, flags);
1534             }
1535         } else {
1536             dest.writeInt(0);
1537         }
1538         if (mDataAuthorities != null) {
1539             final int N = mDataAuthorities.size();
1540             dest.writeInt(N);
1541             for (int i=0; i<N; i++) {
1542                 mDataAuthorities.get(i).writeToParcel(dest);
1543             }
1544         } else {
1545             dest.writeInt(0);
1546         }
1547         if (mDataPaths != null) {
1548             final int N = mDataPaths.size();
1549             dest.writeInt(N);
1550             for (int i=0; i<N; i++) {
1551                 mDataPaths.get(i).writeToParcel(dest, flags);
1552             }
1553         } else {
1554             dest.writeInt(0);
1555         }
1556         dest.writeInt(mPriority);
1557         dest.writeInt(mHasPartialTypes ? 1 : 0);
1558     }
1559 
1560     /**
1561      * For debugging -- perform a check on the filter, return true if it passed
1562      * or false if it failed.
1563      *
1564      * {@hide}
1565      */
debugCheck()1566     public boolean debugCheck() {
1567         return true;
1568 
1569         // This code looks for intent filters that do not specify data.
1570         /*
1571         if (mActions != null && mActions.size() == 1
1572                 && mActions.contains(Intent.ACTION_MAIN)) {
1573             return true;
1574         }
1575 
1576         if (mDataTypes == null && mDataSchemes == null) {
1577             Log.w("IntentFilter", "QUESTIONABLE INTENT FILTER:");
1578             dump(Log.WARN, "IntentFilter", "  ");
1579             return false;
1580         }
1581 
1582         return true;
1583         */
1584     }
1585 
IntentFilter(Parcel source)1586     private IntentFilter(Parcel source) {
1587         mActions = new ArrayList<String>();
1588         source.readStringList(mActions);
1589         if (source.readInt() != 0) {
1590             mCategories = new ArrayList<String>();
1591             source.readStringList(mCategories);
1592         }
1593         if (source.readInt() != 0) {
1594             mDataSchemes = new ArrayList<String>();
1595             source.readStringList(mDataSchemes);
1596         }
1597         if (source.readInt() != 0) {
1598             mDataTypes = new ArrayList<String>();
1599             source.readStringList(mDataTypes);
1600         }
1601         int N = source.readInt();
1602         if (N > 0) {
1603             mDataSchemeSpecificParts = new ArrayList<PatternMatcher>(N);
1604             for (int i=0; i<N; i++) {
1605                 mDataSchemeSpecificParts.add(new PatternMatcher(source));
1606             }
1607         }
1608         N = source.readInt();
1609         if (N > 0) {
1610             mDataAuthorities = new ArrayList<AuthorityEntry>(N);
1611             for (int i=0; i<N; i++) {
1612                 mDataAuthorities.add(new AuthorityEntry(source));
1613             }
1614         }
1615         N = source.readInt();
1616         if (N > 0) {
1617             mDataPaths = new ArrayList<PatternMatcher>(N);
1618             for (int i=0; i<N; i++) {
1619                 mDataPaths.add(new PatternMatcher(source));
1620             }
1621         }
1622         mPriority = source.readInt();
1623         mHasPartialTypes = source.readInt() > 0;
1624     }
1625 
findMimeType(String type)1626     private final boolean findMimeType(String type) {
1627         final ArrayList<String> t = mDataTypes;
1628 
1629         if (type == null) {
1630             return false;
1631         }
1632 
1633         if (t.contains(type)) {
1634             return true;
1635         }
1636 
1637         // Deal with an Intent wanting to match every type in the IntentFilter.
1638         final int typeLength = type.length();
1639         if (typeLength == 3 && type.equals("*/*")) {
1640             return !t.isEmpty();
1641         }
1642 
1643         // Deal with this IntentFilter wanting to match every Intent type.
1644         if (mHasPartialTypes && t.contains("*")) {
1645             return true;
1646         }
1647 
1648         final int slashpos = type.indexOf('/');
1649         if (slashpos > 0) {
1650             if (mHasPartialTypes && t.contains(type.substring(0, slashpos))) {
1651                 return true;
1652             }
1653             if (typeLength == slashpos+2 && type.charAt(slashpos+1) == '*') {
1654                 // Need to look through all types for one that matches
1655                 // our base...
1656                 final int numTypes = t.size();
1657                 for (int i = 0; i < numTypes; i++) {
1658                     final String v = t.get(i);
1659                     if (type.regionMatches(0, v, 0, slashpos+1)) {
1660                         return true;
1661                     }
1662                 }
1663             }
1664         }
1665 
1666         return false;
1667     }
1668 }
1669