开发者

How to inject context using RoboGuice in Android?

开发者 https://www.devze.com 2023-04-02 14:58 出处:网络
I would like to inject my context to my Utility classes, I have seen examples using 开发者_如何学运维Static fields, Are there any ways to do it with out static fields?I tend to use a Provider to injec

I would like to inject my context to my Utility classes, I have seen examples using 开发者_如何学运维Static fields, Are there any ways to do it with out static fields?


I tend to use a Provider to inject the context when I need it.

public class MyClass
{
    private Provider<Context> contextProvider;

    @Inject
    public MyClass(Provider<Context> contextProvider)
    {
        this.contextProvider = contextProvider;
    }

    public doSomething()
    {
        Context c = contextProvider.get();
    }
}


You can do this in several ways, Pass the context to Utility class or use a service locator or anotate the utility class with @Inject attribute. See more details here.

0

精彩评论

暂无评论...
验证码 换一张
取 消