2012-03-09 2 views
0

android에 cancel() 메소드가있어 카운트 다운 타이머를 취소합니다. 하지만 카운트 다운 타이머가 다른 스레드에서 실행되고 있기 때문에 버튼 OnClickLitener() 내부에서 취소하면 카운트 다운 타이머가 취소됩니다.
카운트 다운 타이머가 buttonOnclickListener에서 시작되지 않았지만 onClickListener() 내에서 취소되어야합니다.다른 스레드에서 카운트 다운 타이머 중지

답변

2

다음은 두 개의 단추와 타이머의 예입니다. 타이머가 별도의 엔터티로 실행 중입니다. 하나의 버튼으로 시작하여 다른 버튼으로 멈출 수 있습니다.

package com.test; 

import android.app.Activity; 
import android.os.Bundle; 
import android.os.CountDownTimer; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 

public class TimerTestActivity extends Activity { 

    CountDownTimer cdt; 
    TextView display; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Button start = (Button) findViewById(R.id.startButton); 
     start.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       setupCountDown(); 
       cdt.start(); 
      } 
     }); 

     Button stop = (Button) findViewById(R.id.stopButton); 
     stop.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       cdt.cancel(); 
      } 
     }); 
     display = (TextView) findViewById(R.id.display); 
    } 

    private void setupCountDown() { 
     cdt = new CountDownTimer(10000, 1000) { 

      public void onTick(long millisUntilFinished) { 
       display.setText("TICK " + millisUntilFinished/1000); 
      } 

      public void onFinish() { 
       display.setText("BUZZZZ"); 
      }   
     }; 
    } 
} 

과 main.xml에

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/display" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     /> 

    <Button 
     android:id="@+id/startButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Start" /> 

    <Button 
     android:id="@+id/stopButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Stop" /> 

</LinearLayout> 
+0

변수 CDT는 다른 스레드에서 액세스 할 수 있습니다? 나는 최종으로 선언해서는 안된다는 뜻인가요? – Ashwin

+0

나는이 간단한 앱을 포함하기 위해 원래의 답변을 완전히 다시 작성했습니다. 타이머는 한 버튼 클릭으로 시작되고 다른 버튼 클릭으로 취소됩니다. – Tim

+0

답변 해 주셔서 감사합니다. – Ashwin