下面列出了怎么用android.os.PatternMatcher的API类实例代码及写法,或者点击链接到github查看源代码。
private static void printProviderInfo(ProviderInfo providerInfo, int i) {
String name = providerInfo.name;
String authority = providerInfo.authority;
String readPermission = providerInfo.readPermission;
String writePermission = providerInfo.writePermission;
boolean grantUriPermissions = providerInfo.grantUriPermissions;
boolean multiProcess = providerInfo.multiprocess;
int initOrder = providerInfo.initOrder;
PatternMatcher[] uriPermissionPatterns = providerInfo.uriPermissionPatterns;
PathPermission[] pathPermissions = providerInfo.pathPermissions;
Log.d(TAG, i + "==============");
Log.d(TAG, "name:" + name);
Log.d(TAG, "authority:" + authority);
Log.d(TAG, "readPermission:" + readPermission);
Log.d(TAG, "writePermission:" + writePermission);
Log.d(TAG, "grantUriPermissions:" + grantUriPermissions);
Log.d(TAG, "multiprocess:" + multiProcess);
Log.d(TAG, "initOrder:" + initOrder);
Log.d(TAG, "uriPermissionPatterns:" + Arrays.toString(uriPermissionPatterns));
Log.d(TAG, "pathPermissions:" + Arrays.toString(pathPermissions));
Log.d(TAG, "applicationInfo.packageName:" + providerInfo.applicationInfo.packageName);
Log.d(TAG, "applicationInfo.name:" + providerInfo.applicationInfo.name);
Log.d(TAG, i + "==============");
}
private void maybeRegisterPackageChangeReceiverLocked(String packageName) {
// Unregister IntentFilter listening for previous always-on package change
unregisterPackageChangeReceiverLocked();
if (!isNullOrLegacyVpn(packageName)) {
mIsPackageIntentReceiverRegistered = true;
IntentFilter intentFilter = new IntentFilter();
// Protected intent can only be sent by system. No permission required in register.
intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
intentFilter.addDataSchemeSpecificPart(packageName, PatternMatcher.PATTERN_LITERAL);
mContext.registerReceiverAsUser(
mPackageIntentReceiver, UserHandle.of(mUserHandle), intentFilter, null, null);
}
}
/**
* @param activity The activity that's requesting dispatch
* @param adapter NfcAdapter for the current context
*/
private void enableForegroundDispatch(Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
String[][] techList = new String[][]{};
// Notice that this is the same filter as in our manifest.
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
filters[0].addDataScheme("https");
filters[0].addDataAuthority(Constants.FLOW_DOMAIN, null);
filters[0].addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);
adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
public TrustAgentWrapper(Context context, TrustManagerService trustManagerService,
Intent intent, UserHandle user) {
mContext = context;
mTrustManagerService = trustManagerService;
mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
mUserId = user.getIdentifier();
mName = intent.getComponent();
mAlarmIntent = new Intent(TRUST_EXPIRED_ACTION).putExtra(EXTRA_COMPONENT_NAME, mName);
mAlarmIntent.setData(Uri.parse(mAlarmIntent.toUri(Intent.URI_INTENT_SCHEME)));
mAlarmIntent.setPackage(context.getPackageName());
final IntentFilter alarmFilter = new IntentFilter(TRUST_EXPIRED_ACTION);
alarmFilter.addDataScheme(mAlarmIntent.getScheme());
final String pathUri = mAlarmIntent.toUri(Intent.URI_INTENT_SCHEME);
alarmFilter.addDataPath(pathUri, PatternMatcher.PATTERN_LITERAL);
// Schedules a restart for when connecting times out. If the connection succeeds,
// the restart is canceled in mCallback's onConnected.
scheduleRestart();
mBound = context.bindServiceAsUser(intent, mConnection,
Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE, user);
if (mBound) {
mContext.registerReceiver(mBroadcastReceiver, alarmFilter, PERMISSION, null);
} else {
Log.e(TAG, "Can't bind to TrustAgent " + mName.flattenToShortString());
}
}
@Override
public void initialize(String updaterAppPackageName, String dataAppPackageName,
PackageTracker packageTracker) {
mUpdaterAppPackageName = updaterAppPackageName;
// Register for events of interest.
// The intent filter that triggers when package update events happen that indicate there may
// be work to do.
IntentFilter packageIntentFilter = new IntentFilter();
packageIntentFilter.addDataScheme("package");
packageIntentFilter.addDataSchemeSpecificPart(
updaterAppPackageName, PatternMatcher.PATTERN_LITERAL);
packageIntentFilter.addDataSchemeSpecificPart(
dataAppPackageName, PatternMatcher.PATTERN_LITERAL);
// ACTION_PACKAGE_ADDED is fired when a package is upgraded or downgraded (in addition to
// ACTION_PACKAGE_REMOVED and ACTION_PACKAGE_REPLACED). A system/priv-app can never be
// removed entirely so we do not need to trigger on ACTION_PACKAGE_REMOVED or
// ACTION_PACKAGE_FULLY_REMOVED.
packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
// ACTION_PACKAGE_CHANGED is used when a package is disabled / re-enabled. It is not
// strictly necessary to trigger on this but it won't hurt anything and may catch some cases
// where a package has changed while disabled.
// Note: ACTION_PACKAGE_CHANGED is not fired when updating a suspended app, but
// ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and ACTION_PACKAGE_REPLACED are (and the app
// is left in an unsuspended state after this).
packageIntentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
// We do not register for ACTION_PACKAGE_RESTARTED because it doesn't imply an update.
// We do not register for ACTION_PACKAGE_DATA_CLEARED because the updater / data apps are
// not expected to need local data.
Receiver packageUpdateReceiver = new Receiver(packageTracker);
mContext.registerReceiverAsUser(
packageUpdateReceiver, UserHandle.SYSTEM, packageIntentFilter,
null /* broadcastPermission */, null /* default handler */);
}
private void registerBroadcastReceiver() {
BroadcastReceiver updateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_SYSTEM)
!= UserHandle.USER_SYSTEM) {
// Ignore broadcast for non system users. We don't want to update system
// service multiple times.
return;
}
switch (intent.getAction()) {
case Intent.ACTION_PACKAGE_REMOVED:
if (intent.getExtras().getBoolean(Intent.EXTRA_REPLACING)) {
// The existing package is updated. Will be handled with the
// following ACTION_PACKAGE_ADDED case.
return;
}
packageStateChanged();
break;
case Intent.ACTION_PACKAGE_CHANGED:
packageStateChanged();
break;
case Intent.ACTION_PACKAGE_ADDED:
packageStateChanged();
break;
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
filter.addDataSchemeSpecificPart(MEDIA_UPDATE_PACKAGE_NAME, PatternMatcher.PATTERN_LITERAL);
getContext().registerReceiverAsUser(updateReceiver, UserHandle.ALL, filter,
null /* broadcast permission */, null /* handler */);
}
/**
* New IntentFilter containing a copy of an existing filter.
*
* @param o The original filter to copy.
*/
public IntentFilter(IntentFilter o) {
mPriority = o.mPriority;
mOrder = o.mOrder;
mActions = new ArrayList<String>(o.mActions);
if (o.mCategories != null) {
mCategories = new ArrayList<String>(o.mCategories);
}
if (o.mDataTypes != null) {
mDataTypes = new ArrayList<String>(o.mDataTypes);
}
if (o.mDataSchemes != null) {
mDataSchemes = new ArrayList<String>(o.mDataSchemes);
}
if (o.mDataSchemeSpecificParts != null) {
mDataSchemeSpecificParts = new ArrayList<PatternMatcher>(o.mDataSchemeSpecificParts);
}
if (o.mDataAuthorities != null) {
mDataAuthorities = new ArrayList<AuthorityEntry>(o.mDataAuthorities);
}
if (o.mDataPaths != null) {
mDataPaths = new ArrayList<PatternMatcher>(o.mDataPaths);
}
mHasPartialTypes = o.mHasPartialTypes;
mVerifyState = o.mVerifyState;
mInstantAppVisibility = o.mInstantAppVisibility;
}
/** @hide */
public final void addDataSchemeSpecificPart(PatternMatcher ssp) {
if (mDataSchemeSpecificParts == null) {
mDataSchemeSpecificParts = new ArrayList<PatternMatcher>();
}
mDataSchemeSpecificParts.add(ssp);
}
/**
* Is the given data scheme specific part included in the filter? Note that if the
* filter does not include any scheme specific parts, false will <em>always</em> be
* returned.
*
* @param data The scheme specific part that is being looked for.
*
* @return Returns true if the data string matches a scheme specific part listed in the
* filter.
*/
public final boolean hasDataSchemeSpecificPart(String data) {
if (mDataSchemeSpecificParts == null) {
return false;
}
final int numDataSchemeSpecificParts = mDataSchemeSpecificParts.size();
for (int i = 0; i < numDataSchemeSpecificParts; i++) {
final PatternMatcher pe = mDataSchemeSpecificParts.get(i);
if (pe.match(data)) {
return true;
}
}
return false;
}
/** @hide */
public final boolean hasDataSchemeSpecificPart(PatternMatcher ssp) {
if (mDataSchemeSpecificParts == null) {
return false;
}
final int numDataSchemeSpecificParts = mDataSchemeSpecificParts.size();
for (int i = 0; i < numDataSchemeSpecificParts; i++) {
final PatternMatcher pe = mDataSchemeSpecificParts.get(i);
if (pe.getType() == ssp.getType() && pe.getPath().equals(ssp.getPath())) {
return true;
}
}
return false;
}
/**
* Is the given data path included in the filter? Note that if the
* filter does not include any paths, false will <em>always</em> be
* returned.
*
* @param data The data path to look for. This is without the scheme
* prefix.
*
* @return True if the data string matches a path listed in the
* filter.
*/
public final boolean hasDataPath(String data) {
if (mDataPaths == null) {
return false;
}
final int numDataPaths = mDataPaths.size();
for (int i = 0; i < numDataPaths; i++) {
final PatternMatcher pe = mDataPaths.get(i);
if (pe.match(data)) {
return true;
}
}
return false;
}
/** @hide */
public final boolean hasDataPath(PatternMatcher path) {
if (mDataPaths == null) {
return false;
}
final int numDataPaths = mDataPaths.size();
for (int i = 0; i < numDataPaths; i++) {
final PatternMatcher pe = mDataPaths.get(i);
if (pe.getType() == path.getType() && pe.getPath().equals(path.getPath())) {
return true;
}
}
return false;
}
private ProviderInfo(Parcel in) {
super(in);
authority = in.readString();
readPermission = in.readString();
writePermission = in.readString();
grantUriPermissions = in.readInt() != 0;
uriPermissionPatterns = in.createTypedArray(PatternMatcher.CREATOR);
pathPermissions = in.createTypedArray(PathPermission.CREATOR);
multiprocess = in.readInt() != 0;
initOrder = in.readInt();
flags = in.readInt();
isSyncable = in.readInt() != 0;
}
/**
* 获得 path 匹配类型
*/
int getPatternMatcherType() {
if (TextUtils.isEmpty(pathPattern) && TextUtils.isEmpty(pathPattern)) {
return PatternMatcher.PATTERN_LITERAL;
} else if (!TextUtils.isEmpty(pathPrefix)) {
return PatternMatcher.PATTERN_PREFIX;
} else {
return PatternMatcher.PATTERN_SIMPLE_GLOB;
}
}
/**
* 获得 path 匹配类型
*/
public int getPatternMatcherType() {
if (TextUtils.isEmpty(pathPattern) && TextUtils.isEmpty(pathPattern)) {
return PatternMatcher.PATTERN_LITERAL;
} else if (!TextUtils.isEmpty(pathPrefix)) {
return PatternMatcher.PATTERN_PREFIX;
} else {
return PatternMatcher.PATTERN_SIMPLE_GLOB;
}
}
private static boolean startActivityByCrossProfileIntentFilter(final Context context, final Intent intent) {
final Uri uri = Objects.requireNonNull(intent.getData());
new DevicePolicies(context).addCrossProfileIntentFilter(IntentFilters.forAction(intent.getAction())
.withData(uri.getScheme(), uri.getSchemeSpecificPart(), PatternMatcher.PATTERN_LITERAL), FLAG_PARENT_CAN_ACCESS_MANAGED);
@SuppressLint("WrongConstant") final List<ResolveInfo> resolves
= context.getPackageManager().queryIntentActivities(intent, Hacks.MATCH_ANY_USER_AND_UNINSTALLED);
for (final ResolveInfo resolve : resolves) if ("android".equals(resolve.activityInfo.packageName)) { // IntentForwarder
context.startActivity(intent.setComponent(new ComponentName(resolve.activityInfo.packageName, resolve.activityInfo.name)));
return true;
}
return false;
}
/**
* Gets an {@link IntentFilter} for matching events from the install
* process based on {@code canonicalUri}, which is the global unique
* ID for a package going through the install process.
*
* @see InstallManagerService for more about {@code canonicalUri}
*/
public static IntentFilter getInstallIntentFilter(Uri canonicalUri) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Installer.ACTION_INSTALL_STARTED);
intentFilter.addAction(Installer.ACTION_INSTALL_COMPLETE);
intentFilter.addAction(Installer.ACTION_INSTALL_INTERRUPTED);
intentFilter.addAction(Installer.ACTION_INSTALL_USER_INTERACTION);
intentFilter.addDataScheme(canonicalUri.getScheme());
intentFilter.addDataAuthority(canonicalUri.getHost(), String.valueOf(canonicalUri.getPort()));
intentFilter.addDataPath(canonicalUri.getPath(), PatternMatcher.PATTERN_LITERAL);
return intentFilter;
}
public static IntentFilter getUninstallIntentFilter(String packageName) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Installer.ACTION_UNINSTALL_STARTED);
intentFilter.addAction(Installer.ACTION_UNINSTALL_COMPLETE);
intentFilter.addAction(Installer.ACTION_UNINSTALL_INTERRUPTED);
intentFilter.addAction(Installer.ACTION_UNINSTALL_USER_INTERACTION);
intentFilter.addDataScheme("package");
intentFilter.addDataPath(packageName, PatternMatcher.PATTERN_LITERAL);
return intentFilter;
}
/**
* Get a prepared {@link IntentFilter} for use for matching this service's action events.
*
* @param canonicalUrl the URL used as the unique ID for the specific package
*/
public static IntentFilter getIntentFilter(String canonicalUrl) {
Uri uri = Uri.parse(canonicalUrl);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Downloader.ACTION_STARTED);
intentFilter.addAction(Downloader.ACTION_PROGRESS);
intentFilter.addAction(Downloader.ACTION_COMPLETE);
intentFilter.addAction(Downloader.ACTION_INTERRUPTED);
intentFilter.addAction(Downloader.ACTION_CONNECTION_FAILED);
intentFilter.addDataScheme(uri.getScheme());
intentFilter.addDataAuthority(uri.getHost(), String.valueOf(uri.getPort()));
intentFilter.addDataPath(uri.getPath(), PatternMatcher.PATTERN_LITERAL);
return intentFilter;
}
private static boolean equal_patterns(final Iterator<PatternMatcher> a, final Iterator<PatternMatcher> b) {
if (a == b) return true;
if (a == null || b == null) return false;
while (a.hasNext()) {
if (! b.hasNext()) return false;
final PatternMatcher o1 = a.next();
final PatternMatcher o2 = b.next();
if (! equal(o1, o2)) return false;
}
return ! b.hasNext();
}
@Override
public void onStart() {
mWebViewUpdatedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
switch (intent.getAction()) {
case Intent.ACTION_PACKAGE_REMOVED:
// When a package is replaced we will receive two intents, one
// representing the removal of the old package and one representing the
// addition of the new package.
// In the case where we receive an intent to remove the old version of
// the package that is being replaced we early-out here so that we don't
// run the update-logic twice.
if (intent.getExtras().getBoolean(Intent.EXTRA_REPLACING)) return;
mImpl.packageStateChanged(packageNameFromIntent(intent),
PACKAGE_REMOVED, userId);
break;
case Intent.ACTION_PACKAGE_CHANGED:
// Ensure that we only heed PACKAGE_CHANGED intents if they change an
// entire package, not just a component
if (entirePackageChanged(intent)) {
mImpl.packageStateChanged(packageNameFromIntent(intent),
PACKAGE_CHANGED, userId);
}
break;
case Intent.ACTION_PACKAGE_ADDED:
mImpl.packageStateChanged(packageNameFromIntent(intent),
(intent.getExtras().getBoolean(Intent.EXTRA_REPLACING)
? PACKAGE_ADDED_REPLACED : PACKAGE_ADDED), userId);
break;
case Intent.ACTION_USER_STARTED:
mImpl.handleNewUser(userId);
break;
case Intent.ACTION_USER_REMOVED:
mImpl.handleUserRemoved(userId);
break;
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
// Make sure we only receive intents for WebView packages from our config file.
for (WebViewProviderInfo provider : mImpl.getWebViewPackages()) {
filter.addDataSchemeSpecificPart(provider.packageName, PatternMatcher.PATTERN_LITERAL);
}
getContext().registerReceiverAsUser(mWebViewUpdatedReceiver, UserHandle.ALL, filter,
null /* broadcast permission */, null /* handler */);
IntentFilter userAddedFilter = new IntentFilter();
userAddedFilter.addAction(Intent.ACTION_USER_STARTED);
userAddedFilter.addAction(Intent.ACTION_USER_REMOVED);
getContext().registerReceiverAsUser(mWebViewUpdatedReceiver, UserHandle.ALL,
userAddedFilter, null /* broadcast permission */, null /* handler */);
publishBinderService("webviewupdate", new BinderService(), true /*allowIsolated*/);
}
public PatternStringFilter(ValueProvider valueProvider, String attrValue) {
super(valueProvider);
mPattern = new PatternMatcher(attrValue, PatternMatcher.PATTERN_SIMPLE_GLOB);
}
/**
* Return a data scheme specific part in the filter.
*/
public final PatternMatcher getDataSchemeSpecificPart(int index) {
return mDataSchemeSpecificParts.get(index);
}
/**
* Return an iterator over the filter's data scheme specific parts.
*/
public final Iterator<PatternMatcher> schemeSpecificPartsIterator() {
return mDataSchemeSpecificParts != null ? mDataSchemeSpecificParts.iterator() : null;
}
/** @hide */
public final void addDataPath(PatternMatcher path) {
if (mDataPaths == null) mDataPaths = new ArrayList<PatternMatcher>();
mDataPaths.add(path);
}
/**
* Return a data path in the filter.
*/
public final PatternMatcher getDataPath(int index) {
return mDataPaths.get(index);
}
/**
* Return an iterator over the filter's data paths.
*/
public final Iterator<PatternMatcher> pathsIterator() {
return mDataPaths != null ? mDataPaths.iterator() : null;
}
/** @hide */
public IntentFilter(Parcel source) {
mActions = new ArrayList<String>();
source.readStringList(mActions);
if (source.readInt() != 0) {
mCategories = new ArrayList<String>();
source.readStringList(mCategories);
}
if (source.readInt() != 0) {
mDataSchemes = new ArrayList<String>();
source.readStringList(mDataSchemes);
}
if (source.readInt() != 0) {
mDataTypes = new ArrayList<String>();
source.readStringList(mDataTypes);
}
int N = source.readInt();
if (N > 0) {
mDataSchemeSpecificParts = new ArrayList<PatternMatcher>(N);
for (int i=0; i<N; i++) {
mDataSchemeSpecificParts.add(new PatternMatcher(source));
}
}
N = source.readInt();
if (N > 0) {
mDataAuthorities = new ArrayList<AuthorityEntry>(N);
for (int i=0; i<N; i++) {
mDataAuthorities.add(new AuthorityEntry(source));
}
}
N = source.readInt();
if (N > 0) {
mDataPaths = new ArrayList<PatternMatcher>(N);
for (int i=0; i<N; i++) {
mDataPaths.add(new PatternMatcher(source));
}
}
mPriority = source.readInt();
mHasPartialTypes = source.readInt() > 0;
setAutoVerify(source.readInt() > 0);
setVisibilityToInstantApp(source.readInt());
mOrder = source.readInt();
}
public IntentFilter toIntentFilter(int type)
{
if (1 == type)
{
return toIntentFilter();
}
IntentFilter filter = toIntentFilter();
try
{
//for mimetype
if (type >= 1)
{
if (! StringUtil.isEmpty(dataAndType.getType()))
{
if (! StringUtil.isEmpty(dataAndType.getSubtype()))
{
filter.addDataType(dataAndType.getType() + "/" + dataAndType.getSubtype());
filterType = 2;
}
else
{
filter.addDataType(dataAndType.getType());
filterType = 2;
}
}
}
//for data
if (type >= 2)
{
if (! StringUtil.isEmpty(dataAndType.getHost()))
{
if (! StringUtil.isEmpty(dataAndType.getPort()))
{
filter.addDataAuthority(dataAndType.getHost(), dataAndType.getPort());
}
else
{
filter.addDataAuthority(dataAndType.getHost(), null);
}
filterType = 3;
}
if (! StringUtil.isEmpty(dataAndType.getPath()))
{
filter.addDataPath(dataAndType.getPath(), PatternMatcher.PATTERN_LITERAL);
filterType = 3;
}
if (! StringUtil.isEmpty(dataAndType.getScheme()))
{
filter.addDataScheme(dataAndType.getScheme());
filterType = 3;
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return filter;
}
private static boolean equal(final PatternMatcher a, final PatternMatcher b) {
return a == b || (a != null && b != null && a.getType() == b.getType() && equal(a.getPath(), b.getPath()));
}