Android,Singleton,上下文

时间:2015-07-29 07:59:02

标签: android design-patterns singleton

我遇到了问题。我正在创建一个需要Singleton的帮助器类。该类具有全局上下文变量。我无法做到这一点,因为上下文只能从onCreate中获得,而且这个Singleton实例之前就已创建很多,因为它是静态的。

有人可以帮我解决这个问题。最终需要Singleton实例的Context。

public class Helper { 

  private static Helper sHelper = new Helper() ; 
  private Helper () {} ; 
  public static Helper getInstance() { 
       return sHelper;
  } 

  public boolean doSomething() {
     mContext.getContentResolver; 
     return isDone;
 }
}

3 个答案:

答案 0 :(得分:2)

您可以将上下文设置为ApplicationContext。 您可以创建一个Application类并实现类似:

yourSingletonClass.getInstance().setContext(this);

此调用应位于onCreate方法下的应用程序类中。 有关更多信息,请尝试以下文档: Android - Application class

答案 1 :(得分:0)

您只需将以下上下文传递给助手类。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Set layout on activity
    setContentView(R.layout.activity_main);

    // Find and initialise the relative layout we made 
    RelativeLayout rt = (RelativeLayout)findViewById(R.id.rt);

    // Make layout params for image view we want to add
    LinearLayout.LayoutParams layoutParamsImageView = 
                         new LinearLayout.LayoutParams(50, 50);

    // Create an image view
    ImageView im2 = new ImageView(this);

    // Set layout params on image view
    iv2.setLayoutParams(layoutParamsImageView);

    // Optional attributes 
    iv2.setScaleType(ImageView.ScaleType.CENTER_CROP);
    iv2.setAdjustViewBounds(true);

    // Set image to the view 
    im2.setImageResource(R.drawable.a4);

    // Add view to relative layout we made    
    rt.addView(im2);

}

答案 2 :(得分:0)

你需要传递你的构造助手类的上下文麻烦:

getApplicationContext()
相关问题