用踏板停止简单计时器

时间:2017-05-21 18:48:56

标签: java android multithreading timer handler

我正在尝试从一个开始计数的线程中停止一个计时器。当我按下“开始”按钮时一切正常,但是此刻我按下“停止”按钮我得到下一个错误:

  

致命的例外:主要                                                                                        处理:com.example.user.a4_1_basic_handler,PID:20375                                                                                        java.lang.IllegalStateException:无法执行android:onClick

的方法

我是新手,我只是想尝试使用处理程序来实践线程。如果有人可以告诉我如何完成将是一个加号的线程:)

package com.example.user.a4_1_basic_handler;


import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

//Java variables
int num =0;
boolean stopThread=false;
//Android variables
static final String S_TAG=MainActivity.class.getSimpleName();
Handler handler;
Thread counter = new Thread(new tstart());
tstart test;
// UI
TextView textView;
Button start_button;
Button stop_button;

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

    Log.i(S_TAG,"OnCreate Thread ID: "+Thread.currentThread().getId());
    handler = new Handler(getApplicationContext().getMainLooper());
    tstart test;

    textView=(TextView) findViewById(R.id.textView);
    start_button=(Button) findViewById(R.id.start_button);
    stop_button=(Button) findViewById(R.id.stop_button);
}
//UI
public void OnClick_start(View view){
    counter.start();
}
public void OnClick_stop(View view){
    test.finish();
}
//Methods
public void timer(){
    num++;
    textView.setText(String.valueOf(num));
}
public void clock(){
    try {Thread.sleep(1000);}
    catch (InterruptedException e) {e.printStackTrace();}
}
//Thread
class tstart extends Thread{
    @Override
    public void run() {
        while (!stopThread) {
            clock();
            textView.post(new Runnable() {
                @Override
                public void run() {
                    timer();
                }
            });
        }
    }
    public void finish(){
        stopThread=true;
    }
}
}

1 个答案:

答案 0 :(得分:0)

test未初始化。

 Thread counter = new Thread(new tstart());

counter onCreate()test创建对象的内容test=new tstart(); 需要什么?

test

并使用counter代替public void OnClick_start(View view){ test.start(); }

ForEach

为什么不尝试在Android中运行良好的标准Java计时器java.util.Timerjava.util.TimerTask