下面列出了android.content.pm.InstrumentationInfo#android.content.pm.ProviderInfo 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void installContentProviders(
Context context, List<ProviderInfo> providers) {
final ArrayList<IActivityManager.ContentProviderHolder> results =
new ArrayList<IActivityManager.ContentProviderHolder>();
for (ProviderInfo cpi : providers) {
StringBuilder buf = new StringBuilder(128);
buf.append("Pub ");
buf.append(cpi.authority);
buf.append(": ");
buf.append(cpi.name);
Log.i(TAG, buf.toString());
IActivityManager.ContentProviderHolder cph = installProvider(context, null, cpi,
false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
if (cph != null) {
cph.noReleaseNeeded = true;
results.add(cph);
}
}
try {
ActivityManagerNative.getDefault().publishContentProviders(
getApplicationThread(), results);
} catch (RemoteException ex) {
}
}
@Override
protected void afterInvoke(Object receiver, Method method, Object[] args, Object invokeResult) throws Throwable {
if (args != null) {
if (invokeResult == null) {
final int index0 = 0, index1 = 1;
if (args.length >= 2 && args[index0] instanceof String && args[index1] instanceof Integer) {
String name = (String) args[index0];
Integer flags = (Integer) args[index1];
ProviderInfo info = PluginManager.getInstance().resolveContentProvider(name, flags);
if (info != null) {
setFakedResult(info);
}
}
}
}
super.afterInvoke(receiver, method, args, invokeResult);
}
@Override
public ProviderInfo getProviderInfo(ComponentName className, int flags)
throws NameNotFoundException {
final int userId = getUserId();
try {
ProviderInfo pi = mPM.getProviderInfo(className,
updateFlagsForComponent(flags, userId, null), userId);
if (pi != null) {
return pi;
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
throw new NameNotFoundException(className.toString());
}
/**
* 安装阶段调用,把package对应的provider存入sp中。
*
* @param hostContext Context
* @param providers ProviderInfo[]
*/
public static void addProviders(Context hostContext, ProviderInfo[] providers) {
if (hostContext == null || providers == null || providers.length == 0) {
return;
}
SharedPreferences sp = hostContext.getSharedPreferences(SP_FILENAME, Context.MODE_PRIVATE);
Editor editor = sp.edit();
for (ProviderInfo provider : providers) {
String packageName = provider.packageName;
String authority = provider.authority;
if (sp.contains(authority)) {
if (Constants.DEBUG) {
Log.e("ContentProviderProxy", packageName + "的provider: " + authority
+ " 已经存在 , replace it.");
}
}
editor.putString(authority, packageName);
}
editor.commit();
}
/**
* Lists all defined providers with additional meta-data
*
* @param packageInfo from {@link PackageManager#getPackageInfo(String, int)} requiring {@link PackageManager#GET_PROVIDERS} flag
* @return entries
*/
public static List<PageEntry<?>> createPmProviderInfo(@NonNull PackageInfo packageInfo) {
List<PageEntry<?>> entries = new ArrayList<>();
if (packageInfo.providers != null) {
for (ProviderInfo provider : packageInfo.providers) {
if (provider != null) {
entries.add(Hood.get().createPropertyEntry(provider.name,
"exported: " + provider.exported + "\n" +
"enabled: " + provider.enabled + "\n" +
"authorities: " + provider.authority + "\n" +
"multi-process: " + provider.multiprocess + "\n" +
"read-perm: " + provider.readPermission + "\n" +
"write-perm: " + provider.writePermission + "\n", true));
}
}
}
return entries;
}
@Override
public void attachInfo(Context context, ProviderInfo info) {
// applicationId is expected to be prepended. See AndroidManifest.xml
if (SentryInitProvider.class.getName().equals(info.authority)) {
throw new IllegalStateException(
"An applicationId is required to fulfill the manifest placeholder.");
}
super.attachInfo(context, info);
}
public static Drawable loadPackageIcon(Context context, String authority, int icon) {
if (icon != 0) {
if (authority != null) {
final PackageManager pm = context.getPackageManager();
final ProviderInfo info = pm.resolveContentProvider(authority, 0);
if (info != null) {
return pm.getDrawable(info.packageName, icon, info.applicationInfo);
}
} else {
return ContextCompat.getDrawable(context, icon);
}
}
return null;
}
/**
* Check if the installed Gmail app supports querying for label information.
*
* @param c an application Context
* @return true if it's safe to make label API queries
*/
public static boolean canReadLabels(Context c) {
boolean supported = false;
try {
final PackageInfo info = c.getPackageManager().getPackageInfo(PACKAGE,
PackageManager.GET_PROVIDERS | PackageManager.GET_PERMISSIONS);
boolean allowRead = false;
if (info.permissions != null) {
for (int i = 0, len = info.permissions.length; i < len; i++) {
final PermissionInfo perm = info.permissions[i];
if (PERMISSION.equals(perm.name)
&& perm.protectionLevel < PermissionInfo.PROTECTION_SIGNATURE) {
allowRead = true;
break;
}
}
}
if (allowRead && info.providers != null) {
for (int i = 0, len = info.providers.length; i < len; i++) {
final ProviderInfo provider = info.providers[i];
if (AUTHORITY.equals(provider.authority) &&
TextUtils.equals(PERMISSION, provider.readPermission)) {
supported = true;
}
}
}
} catch (NameNotFoundException e) {
// Gmail app not found
}
return supported;
}
@Override
@SuppressWarnings("unchecked")
public List<ProviderInfo> queryContentProviders(String processName,
int uid, int flags) {
try {
ParceledListSlice<ProviderInfo> slice =
mPM.queryContentProviders(processName, uid, flags);
return slice != null ? slice.getList() : Collections.<ProviderInfo>emptyList();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
private static boolean sonyBadgeContentProviderExists() {
boolean exists = false;
ProviderInfo info = ApplicationLoader.applicationContext.getPackageManager().resolveContentProvider(SONY_HOME_PROVIDER_NAME, 0);
if (info != null) {
exists = true;
}
return exists;
}
/**
* Get the AnkiDroid package name that the API will communicate with.
* This can be used to check that a supported version of AnkiDroid is installed,
* or to get the application label and icon, etc.
* @param context a Context that can be used to get the PackageManager
* @return packageId of AnkiDroid if a supported version is not installed, otherwise null
*/
public static String getAnkiDroidPackageName(Context context) {
PackageManager manager = context.getPackageManager();
ProviderInfo pi = manager.resolveContentProvider(FlashCardsContract.AUTHORITY, 0);
if (pi != null) {
return pi.packageName;
} else {
return null;
}
}
@Override
@SuppressWarnings("unchecked")
public List<ProviderInfo> queryContentProviders(String processName,
int uid, int flags, String metaDataKey) {
try {
ParceledListSlice<ProviderInfo> slice =
mPM.queryContentProviders(processName, uid, flags, metaDataKey);
return slice != null ? slice.getList() : Collections.<ProviderInfo>emptyList();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
checkUserId(userId);
synchronized (mPackages) {
final PackageParser.Provider provider = mProvidersByAuthority.get(name);
if (provider != null) {
ProviderInfo providerInfo = PackageParserCompat.generateProviderInfo(provider, flags);
PackageParser.Package p = mPackages.get(providerInfo.packageName);
AppSetting settings = (AppSetting) p.mExtras;
ComponentFixer.fixComponentInfo(settings, providerInfo, userId);
return providerInfo;
}
}
return null;
}
/** @hide **/
@Override
public ProviderInfo resolveContentProviderAsUser(String name, int flags, int userId) {
try {
return mPM.resolveContentProvider(name, flags, userId);
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
}
private void addProviderInfo(ProviderInfo info) {
if (TextUtils.isEmpty(info.processName)) {
info.processName = info.packageName;
}
ProcessItem item = items.get(info.processName);
if (item == null) {
item = new ProcessItem();
item.name = info.processName;
items.put(info.processName, item);
}
item.addProviderInfo(info);
}
/** @param flags intersection of {@code PackageManager.ComponentInfoFlags} and {@code PackageManager.ResolveInfoFlags}. */
@OwnerUser @ProfileUser public static Set<String> detectCriticalSystemPackages(final PackageManager pm, final int flags) {
final Stopwatch stopwatch = Performances.startUptimeStopwatch();
final Set<String> critical_sys_pkgs = new HashSet<>(sCriticalSystemPkgs);
// Detect package names for critical intent actions, as an addition to the white-list of well-known ones.
for (final Intent intent : sCriticalActivityIntents) {
@SuppressLint("WrongConstant") final ResolveInfo info = pm.resolveActivity(intent, MATCH_DEFAULT_ONLY | Hacks.MATCH_ANY_USER_AND_UNINSTALLED);
if (info == null || (info.activityInfo.applicationInfo.flags & FLAG_SYSTEM) == 0) continue;
final String pkg = info.activityInfo.packageName;
Log.i(TAG, "Critical package for " + intent + ": " + pkg);
critical_sys_pkgs.add(pkg);
}
Performances.check(stopwatch, 1, "CriticalActivities");
// Detect package names for critical content providers, as an addition to the white-list of well-known ones.
for (final String authority : sCriticalContentAuthorities) {
if (authority == null) continue; // Nullable for version-specific authorities
final ProviderInfo provider = pm.resolveContentProvider(authority, flags);
if (provider == null || (provider.applicationInfo.flags & FLAG_SYSTEM) == 0 || (provider.flags & FLAG_SINGLE_USER) != 0) continue;
Log.i(TAG, "Critical package for authority \"" + authority + "\": " + provider.packageName);
critical_sys_pkgs.add(provider.packageName);
}
Performances.check(stopwatch, 1, "CriticalProviders");
return critical_sys_pkgs;
}
/**
* Implementation is provided by the parent class.
*/
@Override
public void attachInfo(Context context, ProviderInfo info) {
mAuthority = info.authority;
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(mAuthority, "root", MATCH_ROOTS);
mMatcher.addURI(mAuthority, "root/*", MATCH_ROOT);
mMatcher.addURI(mAuthority, "root/*/recent", MATCH_RECENT);
mMatcher.addURI(mAuthority, "root/*/search", MATCH_SEARCH);
mMatcher.addURI(mAuthority, "document/*", MATCH_DOCUMENT);
mMatcher.addURI(mAuthority, "document/*/children", MATCH_CHILDREN);
mMatcher.addURI(mAuthority, "tree/*/document/*", MATCH_DOCUMENT_TREE);
mMatcher.addURI(mAuthority, "tree/*/document/*/children", MATCH_CHILDREN_TREE);
// Sanity check our setup
if (!info.exported) {
throw new SecurityException("Provider must be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grantUriPermissions");
}
/* if (!android.Manifest.permission.MANAGE_DOCUMENTS.equals(info.readPermission)
|| !android.Manifest.permission.MANAGE_DOCUMENTS.equals(info.writePermission)) {
throw new SecurityException("Provider must be protected by MANAGE_DOCUMENTS");
}
*/
super.attachInfo(context, info);
}
/**
* After the FileProvider is instantiated, this method is called to provide the system with
* information about the provider.
*
* @param context A {@link Context} for the current component.
* @param info A {@link ProviderInfo} for the new provider.
*/
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
// Sanity check our security
if (info.exported) {
throw new SecurityException("Provider must not be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions");
}
mStrategy = getPathStrategy(context, info.authority);
}
@Override public void attachInfo(final Context context, final ProviderInfo info) {
mShuttleAuthority = info.authority;
final String host = info.authority.substring(0, info.authority.lastIndexOf(".shuttle")); // Authority without trailing ".shuttle"
Users.refreshUsers(context); // Users may not be ready at this point, due to the parallel nature of provider initialization.
mTargetAuthority = Users.toId(Users.isOwner() && Users.profile != null ? Users.profile : Users.owner) + "@" + host; // Add user ID.
Log.d(TAG, "Target authority: " + mTargetAuthority);
super.attachInfo(context, info);
}
@Override
@SuppressWarnings("unchecked")
public List<ProviderInfo> queryContentProviders(String processName,
int uid, int flags, String metaDataKey) {
try {
ParceledListSlice<ProviderInfo> slice =
mPM.queryContentProviders(processName, uid, flags, metaDataKey);
return slice != null ? slice.getList() : Collections.<ProviderInfo>emptyList();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
public void onProviderCreated(ProviderInfo stubInfo, ProviderInfo targetInfo) throws RemoteException {
try {
if (this.mApkManager != null) {
this.mApkManager.onProviderCreated(stubInfo, targetInfo);
}
} catch (RemoteException e) {
JLog.log("wuxinrong", "Provider启动回调ActivityManagerService.onProviderCreated 失败 e=" + e.getMessage());
throw e;
} catch (Exception e2) {
JLog.log("wuxinrong", "Provider启动回调ActivityManagerService.onProviderCreated 失败 e=" + e2.getMessage());
}
}
/**
* Setup content provider.
*/
@Before
public void setupContentProvider() {
ProviderInfo info = new ProviderInfo();
info.authority = BindPersonContentProvider.AUTHORITY;
ContentProviderController<BindPersonContentProvider> controller = Robolectric.buildContentProvider(BindPersonContentProvider.class);
controller.create(info);
}
/** {@hide} */
@Override
public void attachInfoForTesting(Context context, ProviderInfo info) {
registerAuthority(info.authority);
super.attachInfoForTesting(context, info);
}
@Override
public ProviderInfo getProviderInfo(ComponentName className, int flags)
throws NameNotFoundException {
try {
ProviderInfo pi = mPM.getProviderInfo(className, flags);
if (pi != null) {
return pi;
}
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
throw new NameNotFoundException(className.toString());
}
public String getExportedContentProvider() {
StringBuilder sb = new StringBuilder();
if (mPInfo.providers != null) {
for (ProviderInfo pi : mPInfo.providers) {
String piName = pi.name;
if (pi.exported) {
//Grant Uri Permissions
piName = piName + " GRANT: " + String.valueOf(pi.grantUriPermissions) + "|";
if (pi.authority != null) {
piName = piName + " AUTHORITY: " + pi.authority + "|";
}
if (pi.readPermission != null) {
piName = piName + " READ: " + pi.readPermission + "|";
}
if (pi.writePermission != null) {
piName = piName + " WRITE: " + pi.writePermission + "|";
}
PathPermission[] pp = pi.pathPermissions;
if (pp != null) {
for (PathPermission pathPermission : pp) {
piName = piName + " PATH: " + pathPermission.getPath() + "|";
piName = piName + " - READ: " + pathPermission.getReadPermission() + "|";
piName = piName + " - WRITE: " + pathPermission.getWritePermission() + "|";
}
}
sb.append(piName + "\n");
}
}
} else {
sb.append(" -- null");
}
return sb.toString();
}
private static void doValidateProcessNames(final Application app, final String[] process_names) {
try {
final PackageInfo info = app.getPackageManager().getPackageInfo(app.getPackageName(),
GET_ACTIVITIES | GET_SERVICES | GET_RECEIVERS | GET_PROVIDERS);
final Set<String> defined_process_names = new HashSet<>();
if (info.activities != null) for (final ActivityInfo activity : info.activities) defined_process_names.add(activity.processName);
if (info.services != null) for (final ServiceInfo service : info.services) defined_process_names.add(service.processName);
if (info.receivers != null) for (final ActivityInfo receiver : info.receivers) defined_process_names.add(receiver.processName);
if (info.providers != null) for (final ProviderInfo provider : info.providers) defined_process_names.add(provider.processName);
for (final String process_name : process_names)
if (! defined_process_names.contains(getFullProcessName(app, process_name)))
throw new IllegalArgumentException("Process name \"" + process_name + "\" is not used by any component in AndroidManifest.xml");
} catch (final PackageManager.NameNotFoundException ignored) {} // Should never happen
}
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
// Sanity check our security
if (info.exported) {
throw new SecurityException("Provider must not be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions");
}
mStrategy = getPathStrategy(context, info.authority);
}
private void initializeContentProviderInfo() {
PackageInfo packageInfo = mPluginClient.mClientPackageInfo;
if ((packageInfo.providers != null)
&& (packageInfo.providers.length > 0)) {
if (TextUtils.isEmpty(mPluginClientContentProviderClass)) {
mPluginClientContentProviderClass = packageInfo.providers[0].name;
}
for (ProviderInfo a : packageInfo.providers) {
if (a.name.equals(mPluginClientContentProviderClass)) {
mProviderInfo = a;
}
}
}
}
@Override
public ProviderInfo getProviderInfo(ComponentName component, int flags) throws NameNotFoundException {
LoadedPlugin plugin = mPluginManager.getLoadedPlugin(component);
if (null != plugin) {
return plugin.mProviderInfos.get(component);
}
return this.mHostPackageManager.getProviderInfo(component, flags);
}
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
// Sanity check our security
if (info.exported) {
throw new SecurityException("Provider must not be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions");
}
mStrategy = getPathStrategy(context, info.authority);
}