【十二】注入框架RoboGuice使用:(Your First Injected ContentProvider)

          上一篇我们简单的介绍了一下RoboGuice的使用(【十一】注入框架RoboGuice使用:(Your First Injection into a Custom View class)),今天我们来看下内容提供者(ContentProvider)的注入。

         和Robo*Activities一样,RoboContentProviders通过RoboGuice也能自己主动获得注入,为了简便我们能够注入 authority URI。这时我们须要定义以下自己的module:

public class ContentProvidersModule extends AbstractModule {
    @Override
    protected void configure() {
    }

    @Provides
    @Named("example_authority_uri")
    public Uri getExampleAuthorityUri() {
        return Uri.parse("content://com.example.data");
    }
}
       以下就是一个使用RoboGuice注入的Android ContentProvider

public class MyExampleContentProvider extends RoboContentProvider {

    @Inject
    @Named("example_authority_uri")
    private Uri contentUri;

    private UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    @Override
    public boolean onCreate() {
        super.onCreate();
        uriMatcher.addURI(contentUri.getAuthority(), "foo/#", 0);
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        switch (uriMatcher.match(uri)) {
            case 0:
                // Return results of your query
                return null;
            default:
                throw new IllegalStateException("could not resolve URI: " + uri);
        }

        return null;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
        return 0;
    }
}
在你的代码中。你能够通过注入的authority URI来回调content provider的方法:

public class ExampleActivity extends RoboFragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    @Inject
    @Named("example_authority_uri")
    private Uri contentUri;


    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(this, Uri.withAppendedPath(contentUri, "foo"), null, null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        getSupportLoaderManager().destroyLoader(1);
        // do something cool with the data!
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

    public void start() {
        getSupportLoaderManager().initLoader(1, null, this);
    }
}
不要忘记你的content provinder在配置文件的注冊

 <provider
            android:authorities="com.example.data"
            android:name=".MyExampleContentProvider"
            android:exported="false" />




posted @ 2017-04-25 12:50  yfceshi  阅读(132)  评论(0编辑  收藏  举报