Static way to get 'Context' in Android?

前端 未结 19 2700
猫巷女王i
猫巷女王i 2020-11-21 06:36

Is there a way to get the current Context instance inside a static method?

I\'m looking for that way because I hate saving the \'Context\' instance eac

19条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 07:23

    If you're open to using RoboGuice, you can have the context injected into any class you want. Here's a small sample of how to do it with RoboGuice 2.0 (beta 4 at time of this writing)

    import android.content.Context;
    import android.os.Build;
    import roboguice.inject.ContextSingleton;
    
    import javax.inject.Inject;
    
    @ContextSingleton
    public class DataManager {
        @Inject
        public DataManager(Context context) {
                Properties properties = new Properties();
                properties.load(context.getResources().getAssets().open("data.properties"));
            } catch (IOException e) {
            }
        }
    }
    

提交回复
热议问题