9

Is it possible to have private (exported=false) ContentProvider for a library project that's used by many different apps?

The issue is that even when the CP is not exported, it has to have unique authority. When it's not unique then you can't install multiple apps with the same library on the same phone (INSTALL_FAILED_CONFLICTING_PROVIDER).

I know that I can use application ID to define the provider in AndroidManifest like this:

<provider
    android:authorities="${applicationId}.provider.test"
    android:name=".storage.db.MyContentProvider"
    android:exported="false" />

but I can't find a solution to generate the authority in code during runtime to properly initialize a UriMatcher.

BuildConfig.APPLICATION_ID returns an ID of the library project, not the app. I could try to fetch packageId from app's context but then it's not best solution if the app uses flavors with different appIds.

So my ideas to solve this are:

  • finding a proper appplicationId in my library code in runtime (also when flavors with different application IDs are used)
  • find a way to properly match URIs in my UriMatcher without a knowledge of the authority.
LR89
  • 397
  • 1
  • 4
  • 14
  • you might be looking for something called `protectionLevel=signature` if all of your apps are signed with the same key, look here http://stackoverflow.com/questions/6120025/how-to-restrict-content-provider-data-across-applications and here http://stackoverflow.com/questions/23281860/how-do-i-restrict-access-to-my-contentprovider-to-only-my-apps, i did not use or read in details, but the main idea is to allow only apps signed with the same key to access the provider – Yazan Mar 13 '17 at 07:50
  • I don't own the apps that use my library, so the solution should be transparent for the app developer. – LR89 Mar 13 '17 at 07:53

2 Answers2

6

I was able to get the authority in runtime based on an answer found here. The solution looks as follows (API 9+)

private static String getAuthority(final Context appContext) throws PackageManager.NameNotFoundException {
  final ComponentName componentName = new ComponentName(appContext, MyContentProvider.class.getName());
  final ProviderInfo providerInfo = appContext.getPackageManager().getProviderInfo(componentName, 0);
  return providerInfo.authority;
}
Community
  • 1
  • 1
LR89
  • 397
  • 1
  • 4
  • 14
-1

Unfortunately the only way is to request developers of applications who used your library to add tag to their AndroidManifest.xml with their unique authority.

MaxV
  • 2,601
  • 3
  • 18
  • 25