Pergunta

So basically i think ive tried every possible way of handling this with the CountDownTimer but the best i got wasn't good enough. What im trying to do exactly is to display a count down timer for a game app, that once the time hits 0 it starts an activity (startActivity) and i got it from there. Now before i get the "just use the CountDownTimer" i will say that i got it to work almost perfectly already. CountDownTimer setText to a view every second and even launched the activity when it hit 0, but should u just hit the back button after the timer started, it would continue to run for the (16000 millis) and force closed the app, im assuming because countdowntimer does not have a method to cancel it onPause nor onStop.

Now I've heard of using handlers and using timers with timertasks instead. Everyone seems to say that they have proper "cancel();" or "removeCallback" methods. Yet i cant see anywhere that has an example of this.

So to conclude where i could use your help is to at least tell me how would you(all you wonderful talented programmers) go about it. Long story short, be able to launch an activity when the clock hits 0 and yet be able to be cancelled at any moment.

This is the last thing i need to do before sending my app to the market. Thanks in advance guys.

Foi útil?

Solução

In the activity that does the launching:

public class YourActivity extends Activity {
private Runnable runnable = new Runnable(){
    @Override
    public void run() {
        startActivity(new Intent(YourActivity.this, YourOtherActivity.class));
    }};
private Handler handler = new Handler();
@Override public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.linearlayoutwithbutton);
    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopTimer();
        }
    });
        startTimer();
}
    private void startTimer(){ handler.postDelayed(runnable, 16000); }
    private void stopTimer(){ handler.removeCallbacks(runnable); }
}

linearlayoutwithbutton.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearlayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <button android:id="@+id/button1" 
            android:text="Cancel" />
</LinearLayout>

Outras dicas

You can cancel the Countdowntimer by overriding onStop() function.

@Override  
    protected void onStop()        
{

        super.onStop();  
        countdowntimer.cancel();  
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top