停止并启动线程Android

时间:2017-02-14 02:19:18

标签: java android

我正在尝试使用经过的时间不断更新的EditText。这由一个线程处理,该线程调用一个方法来计算经过的时间并将EditText文本设置为经过的时间。线程每秒都会睡觉。当用户按下"开始"并且应该在用户按下"停止"时停止。当用户按下"开始"再次,线程应该在0处重新开始(因为重置开始时间)。这是代码:

public class MainActivity extends AppCompatActivity {

    public Date start;
    public Date end;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button startButton = (Button) findViewById(R.id.startButton);
        Button endButton = (Button) findViewById(R.id.stopButton);
        final EditText dateEditText = (EditText) findViewById(R.id.dateEditText) ;
        final EditText hoursEditText = (EditText) findViewById(R.id.hoursEditText); //the one I want to update

        final DateFormat df = new SimpleDateFormat("MM/dd/yy");

        final Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setTimeElapsed(hoursEditText);
                            }
                        });

                    }
                } catch (InterruptedException e) {

                }
            }
        };

        startButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                start = new Date();
                dateEditText.setText(df.format(start));
                hoursEditText.setText("");
                t.start();
            }
        });


        endButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                t.interrupt();
                if (start == null) {
                    //write error message
                }
                else {
                    setTimeElapsed(hoursEditText);
                    start = null;
                }
            }
        });



    }

    public void setTimeElapsed(EditText hoursEditText)
    {
        end = new Date();
        long diff = end.getTime() - start.getTime();
        String diffFormatted = String.format("%02d:%02d:%02d",
                TimeUnit.MILLISECONDS.toHours(diff),
                TimeUnit.MILLISECONDS.toMinutes(diff)
                        - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(diff)),
                TimeUnit.MILLISECONDS.toSeconds(diff)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(diff)));

        hoursEditText.setText(diffFormatted);
    }
}

正如您所看到的,问题是当我按下#34;停止"然后按"开始"再次,应用程序抛出一个错误,因为该线程已在运行。如果我没有中断语句,则应用程序崩溃,因为它认为start为空。我想在按下停止按钮时停止线程,并在按下开始时从0开始计数。

编辑:

我解决此问题的一种方法是使用一种方法创建一个新线程并在我的startButton侦听器中调用该方法

public void startThread(final EditText hoursEditText){
        t = new Thread() {

            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setTimeElapsed(hoursEditText);
                            }
                        });

                    }
                } catch (InterruptedException e) {

                }
            }
        };

        t.start();
    }

但每次有人按下开始时,这会创建一个新线程。这不是一件好事。

1 个答案:

答案 0 :(得分:0)

您可以使用处理程序

endButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(handler != null)
                handler.removeCallbacksAndMessages(null);
            }
        });

//点击结束按钮可以删除处理程序回调

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    public Date start;
    public Date end;
    Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button startButton = (Button) findViewById(R.id.startButton);
        Button endButton = (Button) findViewById(R.id.stopButton);
        final EditText dateEditText = (EditText) findViewById(R.id.dateEditText);
        final EditText hoursEditText = (EditText) findViewById(R.id.hoursEditText); //the one I want to update

        final DateFormat df = new SimpleDateFormat("MM/dd/yy");

        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                setTimeElapsed(hoursEditText);
                handler.postDelayed(this, 100);
            }
        });

        startButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                start = new Date();
                dateEditText.setText(df.format(start));
                hoursEditText.setText("");
                handler.post(thread);
            }
        });


        endButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(handler != null)
                handler.removeCallbacksAndMessages(null);
            }
        });


    }

    public void setTimeElapsed(EditText hoursEditText) {
        end = new Date();
        long diff = end.getTime() - start.getTime();
        String diffFormatted = String.format("%02d:%02d:%02d",
                TimeUnit.MILLISECONDS.toHours(diff),
                TimeUnit.MILLISECONDS.toMinutes(diff)
                        - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(diff)),
                TimeUnit.MILLISECONDS.toSeconds(diff)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(diff)));

        hoursEditText.setText(diffFormatted);
    }
}

完整代码

{{1}}