如何从类中的另一个函数正确访问方法?

时间:2012-05-04 10:31:10

标签: java android class

我从来没有做过多少Java编程,大多数都是PHP / RUBY / Javascript,所以我不完全确定如何从wLock.release()访问onDestroy

public class SlammedNavigatorActivity extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "SN Wake Lock");
        wLock.acquire();
    }

    public void onDestroy() {
        wLock.release();
    }
}

3 个答案:

答案 0 :(得分:4)

您应该将本地变量wLock转换为私有字段:

public class SlammedNavigatorActivity extends DroidGap {
  private PowerManager.WakeLock wLock;


  public void onCreate(Bundle savedInstanceState) {
    // ...
    wLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "SN Wake Lock");
    // ...
  }
}

答案 1 :(得分:1)

将其设为实例变量:

public class SlammedNavigatorActivity extends DroidGap {

    private PowerManager.WakeLock wLock;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.wLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "SN Wake Lock");
        wLock.acquire();

    }

    public void onDestroy() {
        this.wLock.release();
    }
}

在进行Android编程之前,为什么不学习语言基础知识?阅读Java tutorial或一本关于Java的好书。

答案 2 :(得分:0)

让wLock成为班级成员

public class SlammedNavigatorActivity extends DroidGap {

    private PowerManager.WakeLock wLock;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "SN Wake Lock");
        wLock.acquire();

    }

    public void onDestroy() {

        wLock.release();
    }
}