【发布时间】:2025-12-24 14:25:10
【问题描述】:
我有一个“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();
}
});
【问题讨论】: