点击按钮,在Android中停止运行

时间:2014-05-22 11:02:08

标签: android timer handler runnable

我是Android新手。我试图在点击按钮时停止运行。从solutoins我用google搜索这似乎是非常直接的,但出于某种原因甚至在停止runnable的代码执行后;它只是继续前进。

我在OnCreate();

之外完成了我的声明和实现
//create handlers
    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //do something to the main thread
            new ViewVideoClass().execute();
            timerHandler.postDelayed(this, 1);
        }
    };

当点击一个特定的按钮时,我试图像这样停止runnable:

    @Override
    public void onClick(View v) {
        // Preview Video button clicked
            //this display video feedback from the ip camera
            //The web service sends a frame every interval and I display next frame in 
            //timer (runnable) so that it looks like a video
        if(v.getId() == viewVideoButton.getId()){
            timerHandler.postDelayed(timerRunnable, 1);
        }
        //Rec button clicked
        if(v.getId() == startLoggingButton.getId()){
            if(serviceOffLine == true){
                //firstly stop the handler to release the thread and allow other requests to be made to the service
                timerHandler.removeCallbacks(timerRunnable);
                flagButton = 1;
                //when anyone of the video buttons is clicked, the other should be disabled
                startLoggingVideoOnlyButton.setEnabled(false);

                if(startLoggingButton.getText().toString() == "Rec"){
                    new StartLoggingClass().execute();
                    startLoggingButton.setText("Recording");
                    startLoggingButton.setBackgroundColor(Color.GREEN);
                    startLoggingButton.setTextSize(12);

                    //disable the button, to prevent the user from clicking it again
                    startLoggingButton.setEnabled(false);
                    startLoggingGpsOnlyButton.setEnabled(false);
                    //enable the stop button
                    stopLoggingButton.setEnabled(true);
                    //maybe enable the handler here

                }else{
                startLoggingButton.setText("Rec");
                startLoggingButton.setEnabled(true);
                startLoggingButton.setBackgroundResource(android.R.drawable.btn_default);
                startLoggingButton.setTextSize((float) 18.0);

}

单击[ViewVideoButton]时;计时器启动。理想情况下,我想在单击[StartLoggingButton]时停止它。但由于某种原因,它只是继续运行。

2 个答案:

答案 0 :(得分:0)

如何在timerRunnable中设置一个标志,如下所示

Runnable timerRunnable = new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        //do something to the main thread
        new ViewVideoClass().execute();
        if (mFlag) {
            timerHandler.postDelayed(this, 1);
        }
    }
};

并在按钮单击侦听器中设置标志。

答案 1 :(得分:0)

使用

handler.removeCallbacksAndMessages(null);

从队列中删除所有runnable ...直接:)