首页 > 解决方案 > 如何在不同的类中引用相同的类变量?

问题描述

我有一个“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();

        }
    });

标签: javaandroid

解决方案


可以通过将变量设为静态来完成。您可以通过 ClassName.variable 访问它。(它将是只有一个类的字段,但可以从您的所有类中访问)


推荐阅读