应用程序上下文在非活动类中?

时间:2014-12-12 06:59:08

标签: java android class android-context

这个主题有很多信息,但没有一个可以帮助我。 我在应用程序的应用程序类中有几个全局变量/字段:

public class App extends Application {

private static App instance

public string PUBNUB_SUB = BuildConfig.PUBNUB_SUB_KEY; 
public string PUBNUB_PUB = BuildConfig.PUBNUB_PUB_KEY;


public void onCreate() {
instance = this;

}

public static App getInstance(){
   return instance;
}

}

在活动/片段中我成功地访问了这些变量:

class ActivityA extend Activity {

App baseApp;
Pubnub pubnub;


public void onCreate(Bundle savedInstanceState){

     baseApp = new(App)getApplicationContext();
     Pubnub(baseApp.PUBNUB_SUB, baseApp.PUBNUB_PUB)

}

现在如何在非活动/非碎片类中访问getApplicationContext()?

 public class Events {


 App baseApp;
 Context mContext;
 app = new(LoQooApp)mContext.getApplication(); ???


 public Events(Context context) {
 app = new(LoQooApp)mContext.getApplication(); ???
 }

以上不起作用,应该在哪里

app = new(LoQooApp)getApplication();去吗?

1 个答案:

答案 0 :(得分:1)

看起来PUBNUB_SUBPUBNUB_PUB是常量,因此您可以将它们声明为public static final,然后使用静态引用进行访问:App.PUBNUB_SUBApp.PUBNUB_PUB < / p>