gpt4 book ai didi

android - Android Content Provider 权限定义是否违反了 DRY 规则?

转载 作者:搜寻专家 更新时间:2023-11-01 09:48:51 25 4
gpt4 key购买 nike

Android 的Content Provider must have :

At least one authority must be specified.

例如在 Google 的示例中 android-BasicSyncAdapter AndroidManifest.xml

<provider
android:name=".provider.FeedProvider"
android:authorities="com.example.android.basicsyncadapter"
android:exported="false" />

然后要实现这个 CP,需要在 CP 中定义相同的字符串,就像在 android-BasicSyncAdapter FeedProvider.java 中一样。 CONTENT_AUTHORITY

public static final String CONTENT_AUTHORITY = "com.example.android.basicsyncadapter";

因为我们必须定义这个字符串两次,这是否基本上违反了 DRY 规则 - 如果我在一个地方更改它,我必须记得在其他地方也更改它。

最佳答案

其实你不必多次指定权限。在我们的 OpenTasks Provider我们在运行时从 list 中加载权限。

基本思路是这样的:

Context context = getContext();
PackageManager packageManager = context.getPackageManager();
ProviderInfo providerInfo = packageManager.getProviderInfo(
new ComponentName(context, this.getClass()),
PackageManager.GET_PROVIDERS | PackageManager.GET_META_DATA);
String authority = providerInfo.authority;

在 Android 2.2 上,您必须付出一些额外的努力,因为 getProviderInfo 方法尚不存在。

您可以选择只在字符串资源中指定权限,然后像这样从 list 中引用它:

<provider
android:name=".provider.FeedProvider"
android:authorities="@string/authority"
android:exported="false" />

在您的内容提供程序中,您照常加载权限:

String authority = getContext().getString(R.string.authority);

如果您的内容提供者服务于多个权威机构,这会有点困难,但这可能不是一个好主意。

更新以跟进您的评论:

我没有发现为契约(Contract)提供 Context 有什么问题。

而不是像这样写

Cursor c = contentProvider.query(MyContract.Items.CONTENT_URI,
null, null, null, null);

你只要写

Cursor c = contentProvider.query(MyContract.Items.itemsUri(getContext()),
null, null, null, null);

public final interface MyContract {

// ... lots of other tables ...

public final static class Items {
public final static String CONTENT_PATH = "items";

// all the contract definitions

public final static Uri itemsUri(Context context) {
return new Uri.Builder()
.scheme("content")
.authority(context.getString(R.string.authority)).
.path(CONTENT_PATH)
.build();
}
}

没有太大区别,只是当您还需要添加 ID 时会更方便:

Cursor c = contentProvider.query(MyContract.Items.itemUri(getContext(), myItemId),
null, null, null, null);

Context 传递给这些静态方法通常不是问题,因为无论如何您都需要 Context 来获取 ContentResolver

此技术的一个优点是您的代码完全独立于实际权限,您可以轻松地将 ContentProvider 作为库导入到具有不同权限的不同项目中,您不需要更改一行代码。

顺便说一句,我更喜欢第一个版本(从 list 加载权限),因为在那种情况下您甚至不需要 String 资源。你可以 inject ${applicationId}永远不要再碰它。

以下 list fragment 保证您的权限对于您导入它的每个应用程序都是唯一的:

<provider
android:name=".provider.FeedProvider"
android:authorities="${applicationId}.myauthority"
android:exported="false" />

关于android - Android Content Provider 权限定义是否违反了 DRY 规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36713033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com