从Activity.onStart静态上下文() [英] Static Context from Activity.onStart()

查看:128
本文介绍了从Activity.onStart静态上下文()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成上下文的子类之外的一类, Utilities.java 的通知。我想过提供 SingletonContext 类,并已经看过帖子IKE的这个。我想能够的回报!= NULL 上下文对象,因为该通知可以在任何给定时间内产生因为它是从一个的messageReceived()回调产生的。

I am trying to generate a notification from a class, Utilities.java, outside of the subclass of Context. I've thought about providing a SingletonContext class and have looked at posts ike this. I'd like to be able to return != null Context object since the notification can be generated at any given time because it is generated from a messageReceived() callback.

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

What are there downsides to doing something like this:

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
}

我不认为这会比把这个上的任何不同的的onCreate(),但是,它保证了环境是最新的活动开始时,

I don't think it would be any different than putting this on the onCreate(), however, it guarantees that the context is up to date when the activity starts.

推荐答案

上下文保持这一活动在内存中,你可能不希望一个参考。也许用

The Context keeps a reference to this activity in memory, which you might not want. Perhaps use

this.getApplicationContext();

来代替。这将仍然让你做文件IO与大多数其他东西文意。如果没有具体提到这项活动。

instead. This will still let you do file IO and most other things a context requires. Without a specific reference to this activity.

这篇关于从Activity.onStart静态上下文()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆