Android -如何在应用程序项目中拥有提供者权限?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (25)

一个android库项目包含一些供应商,其权限在合同类中定义如下:

public static final String CONTENT_AUTHORITY = "my.com.library.providers.tester";
private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
提问于
用户回答回答于

它是<provider>使用该android:authorities属性在清单中声明的人。

因此,只要你从提供者中删除所有特定于权限的逻辑,原则上它应该“正常工作”,例如:

  • 那些静态数据成员(现在转移到托管应用)
  • UriMatcher(滚动你自己的东西,不检查权威,但侧重于其他部分Uri

如果出于某种原因,您确信您的提供商需要知道其权限,那么应用程序将不得不在供应商用于实际工作之前将其提供给提供商。可能的方法包括:

  • Since a ContentProvider is a natural singleton, assign it to a static data member, and then supply the authority string to it by a custom method from a custom Application class (as providers are initialized first, so this should work)
  • If you are only supporting API Level 11+, have the custom Application class use call() on ContentResolver to supply the authority to the ContentProvider
  • Assume that the only real calls (e.g., to query(), insert()) are valid, and just lazy-initialize your authority based on what comes in on the first Uri you see
用户回答回答于

我想出的解决方案是将静态初始化程序添加到我们生成的合约中,该合约使用反射来查找类,如果不存在,则使用该静态CONTENT_AUTHORITY字段:

public class QuxContract  {
    public static final String CONTENT_AUTHORITY = initAuthority();

    private static String initAuthority() {
        String authority = "com.example.app.data.qux";

        try {

            ClassLoader loader = QuxContract.class.getClassLoader();

            Class<?> clz = loader.loadClass("com.example.app.data.QuxContentProviderAuthority");
            Field declaredField = clz.getDeclaredField("CONTENT_AUTHORITY");

            authority = declaredField.get(null).toString();
        } catch (ClassNotFoundException e) {} 
        catch (NoSuchFieldException e) {} 
        catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }

        return authority;
    }

    private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
// ...

现在,链接到库项目的每个项目都可以提供自己的权限:

package com.example.app.data;

public class QuxContentProviderAuthority {
    public static final String CONTENT_AUTHORITY = "com.example.app.data.baz";
}

扫码关注云+社区