Android - 如何停止和暂停计时器

发布于 2024-11-10 08:05:52 字数 4391 浏览 1 评论 0原文

我已经遇到了很多问题,尝试暂停和取消暂停计时器,如果我将方向锁定为纵向或横向,它会起作用,但这并不是我想要做的。当然,当您更改方向时会调用 onCreate 方法,因此我取消了计时器任务并将其设置为 null,但是在多次运行方向后,它不再取消计时器任务。我在这里查看了其他人的问题,但似乎没有人能回答我的问题。这是我的代码。目前有点草率,因为我一直在尽我所能让它发挥作用。

public class singleTimer extends Activity implements OnClickListener {

private Integer setTime = 0;
private Integer tmrSeconds = 0;
private Integer tmrMilliSeconds = 0;
private Timer myTimer = new Timer();
private TimerTask myTimerTask;
private TextView timerText;
private boolean isPaused = true;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_timer);
    Bundle extras = getIntent().getExtras();
    setTime = extras.getInt("com.bv.armyprt.timer_duration");
    if (myTimerTask != null) {
        myTimerTask.cancel();
        myTimerTask = null;
    }
    if (savedInstanceState != null) {
        if (savedInstanceState.getInt("tmrSeconds") == 0) {
            tmrSeconds = setTime;
        } else {
            tmrSeconds = savedInstanceState.getInt("tmrSeconds");
            tmrMilliSeconds = savedInstanceState.getInt("tmrMilliseconds");

            if (isPaused == false) {
                myTimer = new Timer();
                myTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        TimerMethod();
                    }
                };
                myTimer.schedule(myTimerTask, 0, 100);
            }

        }
    } else {
        tmrSeconds = setTime;
    }
    timerText = (TextView)findViewById(R.id.timerText);
    timerText.setText(String.format("%03d.%d", tmrSeconds, tmrMilliSeconds));

    TextView timerDesc = (TextView)findViewById(R.id.timerDescription);
    timerDesc.setText("Timer for: " + setTime.toString());
    Button startButton = (Button)findViewById(R.id.timerStart);
    Button stopButton = (Button)findViewById(R.id.timerStop);
    Button closeButton = (Button)findViewById(R.id.timerClose);
    closeButton.setOnClickListener(this);
    startButton.setOnClickListener(this);
    stopButton.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case (R.id.timerStart):
        isPaused = false;
        myTimer = new Timer();
        myTimerTask = new TimerTask() {
            @Override
            public void run() {
                TimerMethod();
            }
        };
        myTimer.schedule(myTimerTask,0, 100);
        break;

    case (R.id.timerStop):
        isPaused = true;
        myTimerTask.cancel();
        myTimerTask = null;
        myTimer.cancel();

        break;

    case (R.id.timerClose):
        onDestroy();
        this.finish();
        break;
    }

}
private void TimerMethod()
{
    //This method is called directly by the timer
    //and runs in the same thread as the timer.
    //We call the method that will work with the UI
    //through the runOnUiThread method.
    this.
    tmrMilliSeconds--;
    this.runOnUiThread(Timer_Tick);
}

private Runnable Timer_Tick = new Runnable() {
    public void run() {

    //This method runs in the same thread as the UI.               
        if (tmrSeconds > 0) {
            if (tmrMilliSeconds <= 0) {
                tmrSeconds--;
                tmrMilliSeconds = 9;
            }
        } else {
            Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(1000);
            myTimer.cancel();
            tmrSeconds = setTime;
            tmrMilliSeconds = 0;
            isPaused = true;
        }

    //Do something to the UI thread here
        timerText.setText(String.format("%03d.%d", tmrSeconds, tmrMilliSeconds));
    }
};

@Override
public void onSaveInstanceState(Bundle savedInstanceState){
    savedInstanceState.putInt("setTimer", setTime);
    savedInstanceState.putInt("tmrSeconds", tmrSeconds);
    savedInstanceState.putInt("tmrMilliseconds", tmrMilliSeconds);

    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    setTime = savedInstanceState.getInt("setTimer");
    tmrSeconds = savedInstanceState.getInt("tmrSeconds");
    tmrMilliSeconds = savedInstanceState.getInt("tmrMilliSeconds");
}
}

I have been running through alot of issues try to pause and unpause a timer, and if I lock the orientation to portrait or landscape it works, but thats not exactly what I want to do. Of course, the onCreate method is called when you change orientation, so im canceling my timertask and setting it to null, but after running through the orientation more than once, it doesnt cancel the timertask anymore. Ive looked through other peoples questions on here but none seem to hold the answer to my quesiton. Heres my code. Its a little sloppy at the moment because ive been trying about everything I can to get it to work.

public class singleTimer extends Activity implements OnClickListener {

private Integer setTime = 0;
private Integer tmrSeconds = 0;
private Integer tmrMilliSeconds = 0;
private Timer myTimer = new Timer();
private TimerTask myTimerTask;
private TextView timerText;
private boolean isPaused = true;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_timer);
    Bundle extras = getIntent().getExtras();
    setTime = extras.getInt("com.bv.armyprt.timer_duration");
    if (myTimerTask != null) {
        myTimerTask.cancel();
        myTimerTask = null;
    }
    if (savedInstanceState != null) {
        if (savedInstanceState.getInt("tmrSeconds") == 0) {
            tmrSeconds = setTime;
        } else {
            tmrSeconds = savedInstanceState.getInt("tmrSeconds");
            tmrMilliSeconds = savedInstanceState.getInt("tmrMilliseconds");

            if (isPaused == false) {
                myTimer = new Timer();
                myTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        TimerMethod();
                    }
                };
                myTimer.schedule(myTimerTask, 0, 100);
            }

        }
    } else {
        tmrSeconds = setTime;
    }
    timerText = (TextView)findViewById(R.id.timerText);
    timerText.setText(String.format("%03d.%d", tmrSeconds, tmrMilliSeconds));

    TextView timerDesc = (TextView)findViewById(R.id.timerDescription);
    timerDesc.setText("Timer for: " + setTime.toString());
    Button startButton = (Button)findViewById(R.id.timerStart);
    Button stopButton = (Button)findViewById(R.id.timerStop);
    Button closeButton = (Button)findViewById(R.id.timerClose);
    closeButton.setOnClickListener(this);
    startButton.setOnClickListener(this);
    stopButton.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case (R.id.timerStart):
        isPaused = false;
        myTimer = new Timer();
        myTimerTask = new TimerTask() {
            @Override
            public void run() {
                TimerMethod();
            }
        };
        myTimer.schedule(myTimerTask,0, 100);
        break;

    case (R.id.timerStop):
        isPaused = true;
        myTimerTask.cancel();
        myTimerTask = null;
        myTimer.cancel();

        break;

    case (R.id.timerClose):
        onDestroy();
        this.finish();
        break;
    }

}
private void TimerMethod()
{
    //This method is called directly by the timer
    //and runs in the same thread as the timer.
    //We call the method that will work with the UI
    //through the runOnUiThread method.
    this.
    tmrMilliSeconds--;
    this.runOnUiThread(Timer_Tick);
}

private Runnable Timer_Tick = new Runnable() {
    public void run() {

    //This method runs in the same thread as the UI.               
        if (tmrSeconds > 0) {
            if (tmrMilliSeconds <= 0) {
                tmrSeconds--;
                tmrMilliSeconds = 9;
            }
        } else {
            Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(1000);
            myTimer.cancel();
            tmrSeconds = setTime;
            tmrMilliSeconds = 0;
            isPaused = true;
        }

    //Do something to the UI thread here
        timerText.setText(String.format("%03d.%d", tmrSeconds, tmrMilliSeconds));
    }
};

@Override
public void onSaveInstanceState(Bundle savedInstanceState){
    savedInstanceState.putInt("setTimer", setTime);
    savedInstanceState.putInt("tmrSeconds", tmrSeconds);
    savedInstanceState.putInt("tmrMilliseconds", tmrMilliSeconds);

    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    setTime = savedInstanceState.getInt("setTimer");
    tmrSeconds = savedInstanceState.getInt("tmrSeconds");
    tmrMilliSeconds = savedInstanceState.getInt("tmrMilliSeconds");
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尝蛊 2024-11-17 08:05:52

您可以简单地添加一个布尔变量

boolean stopTImer = false ;

,然后在您的timerTask中执行如下操作:

@Overrride
public void run(){
if(!stopTimer){
//do stuff ...
//...
}

当您想停止它时,将布尔值设置为true

you can simply add a boolean variable

boolean stopTImer = false ;

and in your timerTask , do something like this :

@Overrride
public void run(){
if(!stopTimer){
//do stuff ...
//...
}

and when you want to stop it , put the boolean to true

赴月观长安 2024-11-17 08:05:52

您应该在 onStop 期间停止计时器。 Android 可能会创建您的 Activity 的另一个实例,并且当您更改方向时,您将丢失对先前计时器(任务)的引用。

与活动相关的所有对象都遵循活动生命周期。这意味着如果您想保留对象的引用,即使活动被删除(这种情况经常发生),您也必须将对对象的引用存储在其他地方。

You should stop the timer during onStop. Android might create another instance of your Activity and you will lose the reference to your previous timer(task) when you change orientation.

All objects tied to an activity follow the activity lifecycle. That means you have to store the references to objects elsewhere if you want to keep them even if the activity gets deleted (which can happen quite often).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文