我对dagger2全新,希望能帮助我:)。
我正在实施一个小型演示,但我承认以下错误: 错误:(20,10)错误:如果没有@Inject构建器或@或@ Produces提供 - 注释方法,则无法提供android.net.ConnectivityManager。 com.edwin.dagger1.MainActivity.connectivityManager [注入的字段类型:android.net.ConnectivityManager connectivityManager]
public class Dagger2Application extends Application {
private SystemComponent systemComponent;
@Override
public void onCreate() {
super.onCreate();
systemComponent = DaggerSystemComponent.builder()
.systemModule(new SystemModule(this))
.build();
}
public SystemComponent getSystemComponent() {
return systemComponent;
}
}

@Module
public class SystemModule {
private final Application application;
public SystemModule(Application application) {
this.application = application;
}
@Provides
@Singleton
public Context provideContext(){
return application;

@Singleton
@Component(modules = SystemModule.class)
public interface SystemComponent {
void inject(MainActivity activity);
}

public class MainActivity extends AppCompatActivity {
@Inject
ConnectivityManager connectivityManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Dagger2Application dagger2Application=(Dagger2Application)getApplication();
dagger2Application.getSystemComponent().inject(this);
boolean activeNetworkMetered = connectivityManager.isActiveNetworkMetered();
Log.d("Network is metered? " , activeNetworkMetered+"");
}
}

答案 0 :(得分:0)
问题在于注入ConnectivityManager类。我修改了一些代码。请看看,希望这会帮助你
public interface IConnectivityManager {
boolean getActiveNetworkMetered();
}
public class IConnectivityManagerImpl implements IConnectivityManager {
private Context context;
public IConnectivityManagerImpl(Context context) {
this.context = context;
}
@Override
public boolean getActiveNetworkMetered() {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.isActiveNetworkMetered();
}
}
MainActivity.class
@Inject
IConnectivityManager connectivityManager;
boolean activeNetworkMetered = connectivityManagers.getActiveNetworkMetered();
Log.d("Network is metered? " , activeNetworkMetered+"");
SystemModule.class
@Provides
@Singleton
public IConnectivityManager provideConnectivity(Context context){
return new IConnectivityManagerImpl(context);
}