我剛開始學習如何使用Dagger,並且我已將自己的Backend
連接類轉換爲自動注入。如何注入SyncAdapter
該類處理Retrofit並執行網絡請求。它曾經有過的靜態方法,但現在它是一個對象,例如:
Backend.fetchPost(context, 42); // old way
mBackend.fetchPost(42); // mBackend is an injected field
上下文用於檢索提供OAuth令牌與我的後端服務器的AccountManager
。這現在被自動注入。
在活動和片段中效果很好,但我無法弄清楚如何注入我的SyncAdapter
類。
事實上,它是一個我無法控制的框架對象,並且AndroidInjections
沒有準備好注入這種類的靜態方法。
下面是我想獲得工作的代碼:
/**
* Handle the transfer of data between the backend and the app, using the Android sync adapter framework.
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
@Inject
public Backend mBackend; // can't use constructor injection,
// so might aswell use a public field
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
List<Post> posts = mBackend.getPosts();
// do stuf with the posts
}
}
所以我知道我應該在構造函數中調用某個地方@#!.inject(this)
,但我完全不知道我應該如何做到這一點:
- 使用的應用程序類的靜態字段檢索依賴圖的頭,讓它瀏覽它,直到它可以注入的所有字段
- 創建一個工廠類和接口,如FO使用的一個r活動和片段
- 別的東西?
更多關於我的dagger2實現細節:
的
Backend
類有一個@Inject
構造,所以匕首應該能夠構建它,只要它可以得到API和GSON解析器的實例:@Inject public Backend(BackendApi api, @UploadGson Gson uploadGson) { mApi = api; mUploadGson = uploadGson; }
- 的
BackendModule
匕首模塊具有@Provide
方法用於@UploadGson Gson
對象,並從依賴關係列表一個BackendApi
(改型)到應用程序類(通過各種對象,如注射器或記錄器) - 的
BackendModule.class
在modules = {}
聲明本申請的@Component
所以基本上被引用時,給定的應用對象,匕首應能夠實例化類Backend
的對象,我想將其注入到我的SyncAdapter
類中。
我只是不知道如何實際觸發注射。 PS:如上所述,我昨天學了匕首,所以請告訴我,如果你認爲我的執行被破壞了,