java - 如何在不同的类中引用相同的类变量?
问题描述
我有一个“PowerManager.WakeLock”类型的变量“wl”。我需要使用相同的“wl”变量,而不是不同类中的不同对象。这可以做到吗?
public PowerManager.WakeLock wl;
// This variable needs to be used like a switch in other classes.
// In one class its turned on, in another class I need to call
// a method .Release(), to turn it off,
// but it has to refer to that same "wl" variable.
NotificationReceiver CLass - “持有电源管理器
public class NotificationReceiver extends Service {
public PowerManager powerManager = (PowerManager)
getSystemService(POWER_SERVICE);
public static PowerManager.WakeLock wl =
powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
"My:WakelockTag"); //Non-static field 'powerManager' cannot be referenced from a static context
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
wl.acquire();
return START_NOT_STICKY;
}
//--------------------------------------------------------------------
我需要在其中使用该变量的 MainActivity 类
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent serviceIntent = new Intent (MainActivity.this, ExampleService.class);
startService(serviceIntent);
NotificationReceiver nn = new NotificationReceiver();// Here I make a new object to access the .aquire() method
nn.wl.acquire();
}
});
解决方案
可以通过将变量设为静态来完成。您可以通过 ClassName.variable 访问它。(它将是只有一个类的字段,但可以从您的所有类中访问)
推荐阅读
- javascript - 找到值存在的第一个索引
- pine-script - 挣扎于 v2 到 v4 pinescript 转换,“无法修改函数内部的全局变量”错误
- javascript - 如何在 Vue.js 中获得假值或真值的总和
- python - 找不到scapy模块
- swift - settingsChangedNotification 仅在 Preferences.app 打开时发送(Swift - OSX)
- pentaho - Pentaho/PDI/Kettle:如何用 Excel 电子表格中的值填充“插入/更新”?
- python - 通过从 pandas 和 scikit-learn 中的非缺失值估计方程来估算缺失值
- rust - 尝试在 JNI 中创建字符串并将其添加到 Arraylist
- php - 上传时ffmpeg水印视频
- c# - CS7069:对类型“Route”的引用声称它在 System.Web 中定义,但找不到