无法找到 com.example.serialprovider.provider.SampleProvider 的提供商信息

Failed to find provider info for com.example.serialprovider.provider.SampleProvider

我一直在尝试从另一个应用程序的自定义 ContentProvider class 获取数据,但我一直收到此错误:无法找到 com.example.serialprovider.provider.SampleProvider..

的提供商信息

我在网上搜索了很多类似的问题,但仍然不知道哪里出了问题,我多次检查了清单,甚至复制了一份 authorities 属性以在接收方应用程序中使用它,但仍然,接收方应用找不到提供商。

这是清单中的声明:

<provider
    android:name=".provider.SampleProvider"
    android:authorities="com.example.serialprovider.provider.SampleProvider"
    android:enabled="true"
    android:exported="true" />

这是 Provider 中 onCreate 和查询方法的实现 class(我使用的是 RoomDatabase):

public class SampleProvider extends ContentProvider {
    
    public SampleProvider() {
    }

    private static final String AUTHORITY = "com.example.serialprovider.provider.SampleProvider";
    private static final String TABLE_NAME = "devicepin";

    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        sURIMatcher.addURI(AUTHORITY, TABLE_NAME, 1);
    }

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        if (sURIMatcher.match(uri) == 1) {
            final Context context = getContext();
            AppDao dao = DatabaseClient.getInstance(context).getAppDatabase().appDao();
            final Cursor cursor = dao.get();
            cursor.setNotificationUri(getContext().getContentResolver(), uri);
            cursor.close();
            return cursor;
        } else {
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
    }
}

下面是我尝试在另一个应用程序“接收器”中获取光标的方法:

private void getPin(){
    new Thread(() -> {
        ContentResolver resolver = getContentResolver();
        try{
            Cursor cursor = resolver.query(Uri.parse("content://com.example.serialprovider.provider.SampleProvider/devciepin"), null, null, null, null);
            cursor.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }).start();
}

光标始终为 null,当我用 try 和 catch 块围绕它时,“找不到提供者信息”是我得到的异常。

原来代码没问题,但是在从另一个应用程序访问 ContentProvider 时,在 Android 11 (API 30) 中引入了一些新限制。

在 Android 11 项行为更改中引用 Documentation

If your app shares a content URI with another app, the intent must grant URI access permissions by setting at least one of the following intent flags: FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION. That way, if the other app targets Android 11, it can still access the content URI. Your app must include the intent flags even when the content URI is associated with a content provider that your app doesn't own.

If your app owns the content provider that's associated with the content URI, verify that the content provider isn't exported. We already recommend this security best practice.