onPause(),onStop(),onDestroy()不会停止线程

时间:2015-07-12 20:50:25

标签: android multithreading timer

当我运行应用程序并按下后退按钮时onPause(),onStop()或onDestroy()都不会停止time_counter线程,这会导致无休止的消息" elTime:" + elapsedTime。

public class GameBoard extends Activity {

DrawingView drawView;
Thread timer_thread;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    setContentView(R.layout.activity_game_board);
    DrawingView drawingView = (DrawingView)findViewById(R.id.drawing_view);
    drawingView.setInitialParameters(size.x,size.y);

    TextView time_counter_tv = (TextView)findViewById(R.id.time_counter);
    runTimer(time_counter_tv);
}

private void runTimer(final TextView elapsedTimeTV) {
    timer_thread  = new Thread() {
        public void run() {
            final long startTime = SystemClock.elapsedRealtime();
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            long elapsedTime = SystemClock.elapsedRealtime() - startTime;
                            System.out.println("elTime: " + elapsedTime);
                            elapsedTimeTV.setText("Elapsed Time: " + elapsedTime/100 + "s");
                        }
                    });
                    timer_thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    timer_thread.start();
}

@Override
protected void onPause(){
    super.onPause();
    System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-----------------");
    timer_thread.interrupt();
}

@Override
protected void onDestroy() {
    super.onDestroy();
}
}

同样在DrawingView类中,当尝试完成活动时,上述方法也不会停止线程。

public class DrawingView extends View {

public void doSth(){
        if (time_has_come){
            ((Activity)getContext()).finish();
            return;
        }
}

0 个答案:

没有答案