这个主题有很多信息,但没有一个可以帮助我。 我在应用程序的应用程序类中有几个全局变量/字段:
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();去吗?
答案 0 :(得分:1)
看起来PUBNUB_SUB
和PUBNUB_PUB
是常量,因此您可以将它们声明为public static final
,然后使用静态引用进行访问:App.PUBNUB_SUB
和App.PUBNUB_PUB
< / p>