可以使用以下方法将ContentProvider打包到库中,并在运行时设置ContentProvider的权限,以便在没有ContentProvider权限冲突的情况下将其包含到多个项目中。这是有效的,因为真正的'权威'来自AndroidManifest ...而不是ContentProvider类。
先从基本的ContentProvider implementation..AUTHORITY,CONTENT_URI和UriMatcher是静态的,而不是 '最终' ....
public class MyContentProvider extends ContentProvider {
public static String AUTHORITY = "com.foo.bar.content";
public static Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
protected static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
然后,重写 'attachInfo' 的方法,这样当的ContentProvider首先被初始化,你的ContentProvider将被从AndroidManifest收集到的ProviderInfo调用。这将在进行任何可能的查询之前发生,很可能在初始应用程序类设置期间进行。使用此机会将AUTHORITY,CONTENT_URI和UriMatcher重置为其“真实”值,如使用ContentProvider库的应用程序所提供的。
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
AUTHORITY = info.authority;
CONTENT_URI = Uri.parse("content://" + AUTHORITY);
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, AlarmTable.TABLENAME, ALARMS);
uriMatcher.addURI(AUTHORITY, AttributeTable.TABLENAME, ATTRIBUTES);
uriMatcher.addURI(AUTHORITY, DeepLinkTable.TABLENAME, DEEPLINKS);
uriMatcher.addURI(AUTHORITY, NotificationTable.TABLENAME, NOTIFICATIONS);
uriMatcher.addURI(AUTHORITY, MetaDataTable.TABLENAME, RESOURCE_METADATA);
uriMatcher.addURI(AUTHORITY, ResourceTable.TABLENAME, RESOURCES);
uriMatcher.addURI(AUTHORITY, ResourceAttributeTable.TABLENAME, RESOURCES_ATTRIBUTES);
uriMatcher.addURI(AUTHORITY, ResourceTagTable.TABLENAME, RESOURCES_TAGS);
uriMatcher.addURI(AUTHORITY, TagTable.TABLENAME, TAGS);
uriMatcher.addURI(AUTHORITY, UserTagTable.TABLENAME, USER_TAGS);
uriMatcher.addURI(AUTHORITY, UserTable.TABLENAME, USERS);
uriMatcher.addURI(AUTHORITY, CUSTOM, RAW);
}
当应用程序启动时,ContentProvider的实际上是与应用类一起实例化,所以将有机会获得所有所需的程序包信息。 ProviderInfo对象将包含AndroidManifest中提供的信息...包含在最终应用程序中的列表。
<provider android:authorities="com.foo.barapp.content"
android:name="com.foo.bar.MyContentProvider"/>
管理局现将“com.foo.barapp.content”,而不是默认值改写,而UriMatcher将被更新到应用程序的价值,而不是默认。依赖于“AUTHORITY”的类现在将访问更新的值,并且UriMatcher将正确区分传入的查询“com.foo.barapp.content”。
我已经同时测试了这两个示例应用程序和androidTest包,并发现它能正常工作。
你可以尝试申请我的解决方案为类似的任务:http:// stackoverflow。com/a/15964372/1220237 – Sash0k 2013-04-12 06:19:11