我从未尝试过Guide或其他DI库,但尝试使用Dagger from square for Android应用程序.它适用于Frgements,但不适用于POJO.该用户指南当做DI的一些知识,因为它没有更详细的解释.我该怎么做才能注入restAdapater我的POJO.如果我使用相同的代码进行字段注入,它可以在Fragment中使用.
public class MyApplication extends Application {
private ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
objectGraph = ObjectGraph.create(new DIModule(this));
}
public ObjectGraph objectGraph() {
return objectGraph;
}
public void inject(Object object) {
objectGraph.inject(object);
}
...
@Module(entryPoints = {
MainActivity.class,
.....,
Auth.class,
RestAdapter.class
})
static class DIModule {@Provides
@Singleton
public RestAdapter provideRestAdapter() {
return new RestAdapter.Builder().setServer(
new Server(Const.BASE_URL)).build();
}
}
}
Run Code Online (Sandbox Code Playgroud)
// POJO
public class Auth {
@Inject
RestAdapter restAdapater;
String Username; …Run Code Online (Sandbox Code Playgroud) 运行我的应用程序的模糊版本会引发以下堆栈跟踪
java.lang.RuntimeException: Unable to create service com.mycompany.myapp.async.alarms.AlarmIntentService: java.lang.IllegalStateException: Errors creating object graph:
dagger.Lazy could not be bound with key dagger.Lazy required by dagger.Lazy com.mycompany.scheduler.c.mNotificationDisplayer
Run Code Online (Sandbox Code Playgroud)
如果我添加-dontobfuscate,它会顺利运行
这是包含该字段的类
public abstract class AbstractAlarmSchedulerService extends IntentService {
@Inject
Lazy<AbstractAlarmSchedulerNotificationDisplayer> mNotificationDisplayer;
Run Code Online (Sandbox Code Playgroud)
我在我的应用程序中从这个类扩展,但它属于一个外部库.
这些是我的匕首计划规则,复制自/sf/answers/1272424401/
#Dagger
-keepattributes *Annotation*
-keepclassmembers,allowobfuscation class * {
@javax.inject.* *;
@dagger.* *;
<init>();
}
-keep class * extends dagger.internal.Binding
-keep class * extends dagger.internal.ModuleAdapter
-keep class **$$ModuleAdapter
-keep class **$$InjectAdapter
-keep class **$$StaticInjection
-keep class dagger.* { *; }
-keep class javax.inject.* …Run Code Online (Sandbox Code Playgroud) 我想使用使用MockRestAdapter创建的模拟Retrofit API服务实例,使用Espresso为Activity编写功能测试(https://github.com/square/retrofit/blob/master/retrofit-mock/src/main/java /retrofit/MockRestAdapter.java).
这有点棘手,因为你无法通过Activity的构造函数注入任何依赖项.
目前,单个Retrofit API服务实例存在于我的Application对象中,我在每个Activities的onCreate()方法中创建了对它的引用.
如何交换模拟Retrofit API服务?也许Dagger就是答案?
在过去的几个月里,我一直在使用Dagger/Retrofit,并且已经看到了为api实现ApiModule类的常见模式.这些ApiModules通常看起来像这样:
@Provides @Singleton Client provideClient(OkHttpClient client) {
return new OkClient(client);
}
@Provides @Singleton Endpoint provideEndpoint() {
return "release".equalsIgnoreCase(BuildConfig.BUILD_TYPE)
? Endpoints.newFixedEndpoint(PRODUCTION_URL, "Foo Production Url")
: Endpoints.newFixedEndpoint(STAGING_URL, "Foo Staging Url");
}
@Provides @Singleton Converter provideConverter(Gson gson) {
return new GsonConverter(gson);
}
@Provides @Singleton RestAdapter provideRestAdapter(Endpoint endpoint, Client client,
Converter converter) {
return new RestAdapter.Builder()
.setClient(client)
.setEndpoint(endpoint)
.setConverter(converter)
.setLogLevel(BuildConfig.DEBUG
? RestAdapter.LogLevel.FULL
: RestAdapter.LogLevel.NONE)
.build();
}
@Provides @Singleton FooApi provideFooApi(RestAdapter restAdapter) {
return restAdapter.create(FooApi.class);
}
Run Code Online (Sandbox Code Playgroud)
但要清理这个,为什么不这样做:
@Provides @Singleton Client provideClient(OkHttpClient client) {
return new …Run Code Online (Sandbox Code Playgroud) 我不确定有什么区别?我什么时候应该使用哪个?
我正在使用匕首和改装.我用Dagger注入了我的Retrofit服务.
现在我想做一个授权请求来获取accessToken.
之后我想使用Request拦截器来增强我的api模块,以便将来使用此访问令牌.
我的想法是在收到访问令牌后使用ObjectGraph.plus()方法,但我不确定这是否是最好的方法.
有人能指出我正确的方向,或者github上有一个示例项目吗?
我正在使用Otto和Dagger.我的一些活动仅在一个帖子上多次收到.
在我看来,发布事件:
@Inject Bus mBus;
在构造函数中:
((MyApplication) mContext.getApplicationContext()).inject(this);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
Log.d(TAG, "Sending SearchResultClickedEvent.");
mBus.post(new SearchResultClickedEvent(mModel.getPlaceId()));
}
});
Run Code Online (Sandbox Code Playgroud)
在我的订阅活动的超类中:
@Inject protected Bus mBus;
在onCreate():
((HarryApplication) getApplicationContext()).inject(this);
在订阅活动中:
@Subscribe
public void on(SearchResultsRecyclerViewHolder.SearchResultClickedEvent event) {
Log.d(TAG, "SearchResultClickedEvent received.");
}
Run Code Online (Sandbox Code Playgroud)
单击后的日志:
03-26 12:59:51.496 24613-24613/D/SearchResultView? Sending SearchResultClickedEvent.
03-26 12:59:51.496 24613-24613/D/Subscriber?SearchResultClickedEvent received.
03-26 12:59:51.497 24613-24613/D/Subscriber?SearchResultClickedEvent received.
03-26 12:59:51.499 24613-24613/D/Subscriber?SearchResultClickedEvent received.
Run Code Online (Sandbox Code Playgroud) 我有一个图书馆项目/模块,Android应用程序和常规Java应用程序都使用它.在Dagger 1中,该项目/模块具有财产complete = false.在@Inject字段中,任何类实现或@Provides方法都不满足.我们的想法是强制complete = true必须提供系统特定实现的"顶层"模块
仅仅是为了举例:在图书馆项目中我有ActLogin活动,有字段@Inject @Named("app version") mAppVersion.登录服务器时使用此字段的值.ActLogin被几个使用此库的应用程序使用.每个应用程序的模块都具有complete = true并提供了价值@Provides @Named("app version") provideAppVersion()
迁移Dagger 2的文档(http://google.github.io/dagger/dagger-1-migration.html)指出:
Dagger 2模块都声明为complete = false和library = true
同时,"主要"文档页面(http://google.github.io/dagger/)指出:
Dagger注释处理器是严格的,如果任何绑定无效或不完整,将导致编译器错误.
后者显然是正确的,因为当试图建立不满意的注入错误时会产生(error: java.lang.String cannot be provided without an @Provides- or @Produces-annotated method).
问题是:是否有可能将这种方法(推迟提供注入)迁移到Dagger 2以及如何?
PS最初我认为这是一个肮脏的解决方法,在库的@Module中提供一些虚拟值,但是又一次 - 你不能在Dagger 2中使用模块覆盖(这是一种WTF(!!!).模块覆盖是最有用的功能我在创建单元测试时).可能我错过了一些非常基本的东西,我希望有人可以指出:-).
随着dagger-android一个现在可以简单地写上如下,并成功注入应用程序的依赖关系:
@Module
public abstract class MainActivityModule {
@ContributesAndroidInjector
abstract MainActivity contributesMainActivity();
}
@Singleton
@Component(modules = {
AndroidSupportInjectionModule.class,
AndroidInjectionModule.class,
AppModule.class,
MainActivityModule.class
})
public interface ApplicationComponent {
void inject(BaseApplication baseApplication);
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
ApplicationComponent build();
}
}
@Module
public abstract class AppModule {}
public class MainActivity extends AppCompatActivity implements
HasSupportFragmentInjector {
@Inject
DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
@Inject
Whatever whatever;
@Override
protected void onCreate(Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public AndroidInjector<Fragment> supportFragmentInjector() {
return dispatchingAndroidInjector;
} …Run Code Online (Sandbox Code Playgroud) 我正在处理我的第一个Android kotlin应用程序.我的第一个活动是使用模拟数据,我现在正在尝试从数据库中获取数据,但代码将无法编译.
Kotlin代码:
@Dao
interface TagGroupDao {
@Query("select * from TagGroup")
fun getAll(): LiveData<List<TagGroup>>
}
Run Code Online (Sandbox Code Playgroud)
这已经生成了这个java代码:
public class TagGroupDao_Impl implements TagGroupDao {
private final RoomDatabase __db;
public TagGroupDao_Impl(RoomDatabase __db) {
this.__db = __db;
}
@Override
public LiveData<List<TagGroup>> getAll() {
final String _sql = "select * from TagGroup";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
return new ComputableLiveData<List<TagGroup>>() {
private Observer _observer;
@Override
protected List<TagGroup> compute() {
if (_observer == null) {
_observer = new Observer("TagGroup") {
@Override
public void onInvalidated(@NonNull Set<String> …Run Code Online (Sandbox Code Playgroud)