来自 Activity.onStart() 的静态上下文

Clo*_*ker 1 java static android android-context

我想从一个类生成通知,Utilities.java,的子类之外Context。我也想过提供SingletonContext类和已经看过帖子IKE。我希望能够return != null Context反对,因为通知可以在任何给定时间生成,因为它是从messageReceived()回调生成的。

做这样的事情有什么缺点:

public static Context c;    

public class MainActivity extends Activity{
    @Override
    public void onStart()
      super.onStart()
      c = this.getApplicationContext();
}

//other method somewhere outside this class
public Context getContext(){
   return MainActivity.c
}
Run Code Online (Sandbox Code Playgroud)

我认为这与将其放在 上没有任何不同onCreate(),但是,它可以保证活动开始时上下文是最新的。

Mun*_*Rae 5

上下文在内存中保留对此活动的引用,这可能是您不想要的。也许用

this.getApplicationContext();
Run Code Online (Sandbox Code Playgroud)

反而。这仍然可以让您执行文件 IO 和上下文所需的大多数其他事情。没有具体提到这个活动。