我正在尝试在使用 BLE gatt 服务的 Android Studio 应用程序中实现全局变量。 我需要将从 BLE 接收到的数字保存在全局变量中。
所以我创建了这个类:
public class Globals extends Application {
private List<Float> current = new ArrayList<>();
public float getCurrent() {
return current.get(current.size()-1);
}
public void setCurrent(float someVariable) {
this.current.add(someVariable);
}
}
我还使用 android:name 修改了 list 。我可以在主要 Activity 和某些 fragment 中正确使用这些函数。但我想在与 Application 或 Activity 不同的其他扩展中实现它。
在另一个java文件中我有这个类:
class SerialSocket extends BluetoothGattCallback {
// Here how can i get the function declared in Globals??
Globals globalClass = (Globals) getApplicationContext();
显然我不能在BluetoothGattCallback扩展中使用getApplicationContext(),但是我可以使用什么代码?
最佳答案
您可以创建 Globals 的静态实例并进行访问。
public class Globals extends Application {
private static Globals instance;
private List<Float> current = new ArrayList<>();
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
public float getCurrent() {
return current.get(current.size()-1);
}
public void setCurrent(float someVariable) {
this.current.add(someVariable);
}
public static Globals getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
}
现在,您可以在应用程序中的任何位置访问当前变量或更改值
Globals.getInstance().getCurrent();
关于java - 如何在不同于 'Application' 和 'Activity' 的扩展中实现全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684226/